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

lightningnetwork / lnd / 12375116696

17 Dec 2024 02:29PM UTC coverage: 58.366% (-0.2%) from 58.595%
12375116696

Pull #8777

github

ziggie1984
docs: add release-notes
Pull Request #8777: multi: make deletion of edge atomic.

132 of 177 new or added lines in 6 files covered. (74.58%)

670 existing lines in 37 files now uncovered.

133926 of 229458 relevant lines covered (58.37%)

19223.6 hits per line

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

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

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

72
        byteOrder.PutUint32(scratch, o.Index)
368✔
73
        _, err := w.Write(scratch)
368✔
74
        return err
368✔
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 {
4✔
179
        r.updateMtx.RLock()
4✔
180
        defer r.updateMtx.RUnlock()
4✔
181

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

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

135✔
191
        r.lastUpdated = time.Now()
135✔
192
}
135✔
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 {
381✔
331
        var s serializedPubKey
381✔
332
        copy(s[:], pubKey.SerializeCompressed())
381✔
333
        return s
381✔
334
}
381✔
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 {
1✔
664
        switch c {
1✔
665
        case markedOpen:
1✔
666
                return "markedOpen"
1✔
667
        case channelReadySent:
1✔
668
                return "channelReadySent"
1✔
669
        case addedToGraph:
1✔
670
                return "addedToGraph"
1✔
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) {
108✔
679
        return &Manager{
108✔
680
                cfg:       &cfg,
108✔
681
                chanIDKey: cfg.TempChanIDSeed,
108✔
682
                activeReservations: make(
108✔
683
                        map[serializedPubKey]pendingChannels,
108✔
684
                ),
108✔
685
                signedReservations: make(
108✔
686
                        map[lnwire.ChannelID][32]byte,
108✔
687
                ),
108✔
688
                fundingMsgs: make(
108✔
689
                        chan *fundingMsg, msgBufferSize,
108✔
690
                ),
108✔
691
                fundingRequests: make(
108✔
692
                        chan *InitFundingMsg, msgBufferSize,
108✔
693
                ),
108✔
694
                localDiscoverySignals: &lnutils.SyncMap[
108✔
695
                        lnwire.ChannelID, chan struct{},
108✔
696
                ]{},
108✔
697
                handleChannelReadyBarriers: &lnutils.SyncMap[
108✔
698
                        lnwire.ChannelID, struct{},
108✔
699
                ]{},
108✔
700
                pendingMusigNonces: make(
108✔
701
                        map[lnwire.ChannelID]*musig2.Nonces,
108✔
702
                ),
108✔
703
                quit: make(chan struct{}),
108✔
704
        }, nil
108✔
705
}
108✔
706

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

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

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

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

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

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

2✔
754
                                f.rebroadcastFundingTx(channel)
2✔
755
                        }
2✔
756
                } else if channel.ChanType.IsSingleFunder() &&
9✔
757
                        channel.ChanType.HasFundingTx() &&
9✔
758
                        channel.IsZeroConf() && channel.IsInitiator &&
9✔
759
                        !channel.ZeroConfConfirmed() {
11✔
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)
10✔
772
                go f.advanceFundingState(channel, chanID, nil)
10✔
773
        }
774

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

108✔
778
        return nil
108✔
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 {
105✔
784
        f.stopped.Do(func() {
209✔
785
                log.Info("Funding manager shutting down...")
104✔
786
                defer log.Debug("Funding manager shutdown complete")
104✔
787

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

792
        return nil
105✔
793
}
794

795
// rebroadcastFundingTx publishes the funding tx on startup for each
796
// unconfirmed channel.
797
func (f *Manager) rebroadcastFundingTx(c *channeldb.OpenChannel) {
4✔
798
        var fundingTxBuf bytes.Buffer
4✔
799
        err := c.FundingTxn.Serialize(&fundingTxBuf)
4✔
800
        if err != nil {
4✔
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 {
4✔
809
                log.Debugf("Rebroadcasting funding tx for ChannelPoint(%v): "+
4✔
810
                        "%x", c.FundingOutpoint, fundingTxBuf.Bytes())
4✔
811
        }
4✔
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)
4✔
816

4✔
817
        err = f.cfg.PublishTransaction(c.FundingTxn, label)
4✔
818
        if err != nil {
4✔
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 {
57✔
832
        // Obtain a fresh nonce. We do this by encoding the incremented nonce.
57✔
833
        nextNonce := f.chanIDNonce.Add(1)
57✔
834

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

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

57✔
848
        return nextChanID
57✔
849
}
57✔
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) {
1✔
855
        log.Debugf("Cancelling all reservations for peer %x", nodePub[:])
1✔
856

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

1✔
860
        // We'll attempt to look up this node in the set of active
1✔
861
        // reservations.  If they don't have any, then there's no further work
1✔
862
        // to be done.
1✔
863
        nodeReservations, ok := f.activeReservations[nodePub]
1✔
864
        if !ok {
2✔
865
                log.Debugf("No active reservations for node: %x", nodePub[:])
1✔
866
                return
1✔
867
        }
1✔
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 {
146✔
912
        return &chanIdentifier{
146✔
913
                tempChanID: tempChanID,
146✔
914
        }
146✔
915
}
146✔
916

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

923
// hasChanID returns true if the active channel ID has been set.
924
func (c *chanIdentifier) hasChanID() bool {
23✔
925
        return c.chanIDSet
23✔
926
}
23✔
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) {
23✔
937

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

23✔
941
        // First, notify Brontide to remove the pending channel.
23✔
942
        //
23✔
943
        // NOTE: depending on where we fail the flow, we may not have the
23✔
944
        // active channel ID yet.
23✔
945
        if cid.hasChanID() {
29✔
946
                err := peer.RemovePendingChannel(cid.chanID)
6✔
947
                if err != nil {
6✔
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(
23✔
955
                peer.IdentityKey(), cid.tempChanID, false,
23✔
956
        )
23✔
957
        if err != nil {
34✔
958
                log.Errorf("unable to cancel reservation: %v", err)
11✔
959
        }
11✔
960

961
        // In case the case where the reservation existed, send the funding
962
        // error on the error channel.
963
        if ctx != nil {
36✔
964
                ctx.err <- fundingErr
13✔
965
        }
13✔
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
23✔
970
        switch e := fundingErr.(type) {
23✔
971
        // Let the actual error message be sent to the remote for the
972
        // whitelisted types.
973
        case lnwallet.ReservationError:
7✔
974
                msg = lnwire.ErrorData(e.Error())
7✔
975
        case lnwire.FundingError:
5✔
976
                msg = lnwire.ErrorData(e.Error())
5✔
977
        case chanacceptor.ChanAcceptError:
1✔
978
                msg = lnwire.ErrorData(e.Error())
1✔
979

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

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

23✔
990
        log.Debugf("Sending funding error to peer (%x): %v",
23✔
991
                peer.IdentityKey().SerializeCompressed(), spew.Sdump(errMsg))
23✔
992
        if err := peer.SendMessage(false, errMsg); err != nil {
24✔
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() {
108✔
1024
        defer f.wg.Done()
108✔
1025

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

108✔
1029
        for {
482✔
1030
                select {
374✔
1031
                case fmsg := <-f.fundingMsgs:
211✔
1032
                        switch msg := fmsg.msg.(type) {
211✔
1033
                        case *lnwire.OpenChannel:
55✔
1034
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
55✔
1035

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

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

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

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

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

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

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

1061
                case <-f.quit:
104✔
1062
                        return
104✔
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) {
64✔
1078

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

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

1093
        var chanOpts []lnwallet.ChannelOpt
43✔
1094
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
85✔
1095
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
42✔
1096
        })
42✔
1097
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
85✔
1098
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
42✔
1099
        })
42✔
1100
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
43✔
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(
43✔
1106
                nil, channel, nil, chanOpts...,
43✔
1107
        )
43✔
1108
        if err != nil {
43✔
1109
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1110
                        channel.FundingOutpoint, err)
×
1111
                return
×
1112
        }
×
1113

1114
        for {
191✔
1115
                channelState, shortChanID, err := f.getChannelOpeningState(
148✔
1116
                        &channel.FundingOutpoint,
148✔
1117
                )
148✔
1118
                if err == channeldb.ErrChannelNotFound {
174✔
1119
                        // Channel not in fundingManager's opening database,
26✔
1120
                        // meaning it was successfully announced to the
26✔
1121
                        // network.
26✔
1122
                        // TODO(halseth): could do graph consistency check
26✔
1123
                        // here, and re-add the edge if missing.
26✔
1124
                        log.Debugf("ChannelPoint(%v) with chan_id=%x not "+
26✔
1125
                                "found in opening database, assuming already "+
26✔
1126
                                "announced to the network",
26✔
1127
                                channel.FundingOutpoint, pendingChanID)
26✔
1128
                        return
26✔
1129
                } else if err != nil {
149✔
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(
123✔
1141
                        channel, lnChannel, shortChanID, pendingChanID,
123✔
1142
                        channelState, updateChan,
123✔
1143
                )
123✔
1144
                if err != nil {
141✔
1145
                        log.Errorf("Unable to advance state(%v): %v",
18✔
1146
                                channel.FundingOutpoint, err)
18✔
1147
                        return
18✔
1148
                }
18✔
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 {
123✔
1161

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

123✔
1166
        switch channelState {
123✔
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:
36✔
1170
                err := f.sendChannelReady(channel, lnChannel)
36✔
1171
                if err != nil {
37✔
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(
35✔
1181
                        &channel.FundingOutpoint, channelReadySent,
35✔
1182
                        shortChanID,
35✔
1183
                )
35✔
1184
                if err != nil {
35✔
1185
                        return fmt.Errorf("error setting channel state to"+
×
1186
                                " channelReadySent: %w", err)
×
1187
                }
×
1188

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

35✔
1192
                return nil
35✔
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:
60✔
1197
                // We must wait until we've received the peer's channel_ready
60✔
1198
                // before sending a channel_update according to BOLT#07.
60✔
1199
                received, err := f.receivedChannelReady(
60✔
1200
                        channel.IdentityPub, chanID,
60✔
1201
                )
60✔
1202
                if err != nil {
60✔
UNCOV
1203
                        return fmt.Errorf("failed to check if channel_ready "+
×
UNCOV
1204
                                "was received: %v", err)
×
UNCOV
1205
                }
×
1206

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

1217
                        return nil
24✔
1218
                }
1219

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

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

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

1243
                err := f.annAfterSixConfs(channel, shortChanID)
27✔
1244
                if err != nil {
30✔
1245
                        return fmt.Errorf("error sending channel "+
3✔
1246
                                "announcement: %v", err)
3✔
1247
                }
3✔
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)
25✔
1255
                if err != nil {
25✔
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)
25✔
1265
                if err != nil {
25✔
1266
                        log.Infof("Could not delete initial policy for chanId "+
×
1267
                                "%x", chanID)
×
1268
                }
×
1269

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

25✔
1273
                return nil
25✔
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 {
56✔
1283

56✔
1284
        if channel.IsZeroConf() {
61✔
1285
                // Persist the alias to the alias database.
5✔
1286
                baseScid := channel.ShortChannelID
5✔
1287
                err := f.cfg.AliasManager.AddLocalAlias(
5✔
1288
                        baseScid, baseScid, true, false,
5✔
1289
                )
5✔
1290
                if err != nil {
5✔
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(
5✔
1300
                        &channel.FundingOutpoint, markedOpen,
5✔
1301
                        &channel.ShortChannelID,
5✔
1302
                )
5✔
1303
                if err != nil {
5✔
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)
5✔
1311
                if err != nil {
5✔
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)
5✔
1319

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

1328
                return nil
5✔
1329
        }
1330

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

1340
        if blockchain.IsCoinBaseTx(confChannel.fundingTx) {
33✔
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)
31✔
1389
        log.Debugf("ChannelID(%v) is now fully confirmed! "+
31✔
1390
                "(shortChanID=%v)", chanID, confChannel.shortChanID)
31✔
1391

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

1399
        return nil
31✔
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) {
211✔
1405
        select {
211✔
1406
        case f.fundingMsgs <- &fundingMsg{msg, peer}:
211✔
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) {
55✔
1422

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

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

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

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

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

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

1458
        for _, c := range channels {
68✔
1459
                // Pending channels that have a non-zero thaw height were also
13✔
1460
                // created through a canned funding shim. Those also don't
13✔
1461
                // count towards the DoS protection limit.
13✔
1462
                //
13✔
1463
                // TODO(guggero): Properly store the funding type (wallet, shim,
13✔
1464
                // PSBT) on the channel so we don't need to use the thaw height.
13✔
1465
                if c.IsPending && c.ThawHeight == 0 {
22✔
1466
                        numPending++
9✔
1467
                }
9✔
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 {
60✔
1473
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
5✔
1474

5✔
1475
                return
5✔
1476
        }
5✔
1477

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

1485
        if len(pendingChans) > pendingChansLimit {
51✔
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()
51✔
1494
        if err != nil || !isSynced {
51✔
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 {
54✔
1505
                f.failFundingFlow(
3✔
1506
                        peer, cid,
3✔
1507
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
3✔
1508
                )
3✔
1509
                return
3✔
1510
        }
3✔
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 {
50✔
1515
                f.failFundingFlow(
1✔
1516
                        peer, cid,
1✔
1517
                        lnwallet.ErrChanTooSmall(amt, f.cfg.MinChanSize),
1✔
1518
                )
1✔
1519
                return
1✔
1520
        }
1✔
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 {
50✔
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{
48✔
1532
                Node:        peer.IdentityKey(),
48✔
1533
                OpenChanMsg: msg,
48✔
1534
        }
48✔
1535

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

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

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

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

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

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

5✔
1593
                // If the zero-conf channel type was negotiated, ensure that
5✔
1594
                // the acceptor allows it.
5✔
1595
                if zeroConf && !acceptorResp.ZeroConf {
5✔
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 {
5✔
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
48✔
1628
        switch {
48✔
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(
48✔
1655
                f.cfg.AuxFundingController,
48✔
1656
                func(c AuxFundingController) AuxTapscriptResult {
48✔
1657
                        return c.DeriveTapscriptRoot(msg.PendingChannelID)
×
1658
                },
×
1659
        ).Unpack()
1660
        if err != nil {
48✔
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{
48✔
1669
                ChainHash:        &msg.ChainHash,
48✔
1670
                PendingChanID:    msg.PendingChannelID,
48✔
1671
                NodeID:           peer.IdentityKey(),
48✔
1672
                NodeAddr:         peer.Address(),
48✔
1673
                LocalFundingAmt:  0,
48✔
1674
                RemoteFundingAmt: amt,
48✔
1675
                CommitFeePerKw:   chainfee.SatPerKWeight(msg.FeePerKiloWeight),
48✔
1676
                FundingFeePerKw:  0,
48✔
1677
                PushMSat:         msg.PushAmount,
48✔
1678
                Flags:            msg.ChannelFlags,
48✔
1679
                MinConfs:         1,
48✔
1680
                CommitType:       commitType,
48✔
1681
                ZeroConf:         zeroConf,
48✔
1682
                OptionScidAlias:  scid,
48✔
1683
                ScidAliasFeature: scidFeatureVal,
48✔
1684
                TapscriptRoot:    tapscriptRoot,
48✔
1685
        }
48✔
1686

48✔
1687
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
48✔
1688
        if err != nil {
48✔
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, "+
48✔
1695
                "cannedShim=%v", reservation.IsZeroConf(),
48✔
1696
                reservation.IsPsbt(), reservation.IsCannedShim())
48✔
1697

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

1708
                reservation.AddAlias(aliasScid)
3✔
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)
48✔
1718
        if acceptorResp.MinAcceptDepth != 0 {
48✔
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 {
51✔
1725
                numConfsReq = 0
3✔
1726
        }
3✔
1727

1728
        reservation.SetNumConfsRequired(numConfsReq)
48✔
1729

48✔
1730
        // We'll also validate and apply all the constraints the initiating
48✔
1731
        // party is attempting to dictate for our commitment transaction.
48✔
1732
        stateBounds := &channeldb.ChannelStateBounds{
48✔
1733
                ChanReserve:      msg.ChannelReserve,
48✔
1734
                MaxPendingAmount: msg.MaxValueInFlight,
48✔
1735
                MinHTLC:          msg.HtlcMinimum,
48✔
1736
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
48✔
1737
        }
48✔
1738
        commitParams := &channeldb.CommitmentParams{
48✔
1739
                DustLimit: msg.DustLimit,
48✔
1740
                CsvDelay:  msg.CsvDelay,
48✔
1741
        }
48✔
1742
        err = reservation.CommitConstraints(
48✔
1743
                stateBounds, commitParams, f.cfg.MaxLocalCSVDelay, true,
48✔
1744
        )
48✔
1745
        if err != nil {
49✔
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(
47✔
1756
                f.cfg.EnableUpfrontShutdown, peer, acceptorResp.UpfrontShutdown,
47✔
1757
                f.selectShutdownScript,
47✔
1758
        )
47✔
1759
        if err != nil {
47✔
1760
                f.failFundingFlow(
×
1761
                        peer, cid,
×
1762
                        fmt.Errorf("getUpfrontShutdownScript error: %w", err),
×
1763
                )
×
1764
                return
×
1765
        }
×
1766
        reservation.SetOurUpfrontShutdown(shutdown)
47✔
1767

47✔
1768
        // If a script enforced channel lease is being proposed, we'll need to
47✔
1769
        // validate its custom TLV records.
47✔
1770
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
48✔
1771
                if msg.LeaseExpiry == nil {
1✔
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 {
2✔
1782
                        if uint32(*msg.LeaseExpiry) !=
1✔
1783
                                reservation.LeaseExpiry() {
1✔
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): "+
47✔
1793
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
47✔
1794
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
47✔
1795
                commitType, msg.UpfrontShutdownScript)
47✔
1796

47✔
1797
        // Generate our required constraints for the remote party, using the
47✔
1798
        // values provided by the channel acceptor if they are non-zero.
47✔
1799
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
47✔
1800
        if acceptorResp.CSVDelay != 0 {
47✔
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
47✔
1812
        if msg.DustLimit > maxDustLimit {
47✔
1813
                maxDustLimit = msg.DustLimit
×
1814
        }
×
1815

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

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

1826
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
47✔
1827
        if acceptorResp.HtlcLimit != 0 {
47✔
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
47✔
1834
        if acceptorResp.MinHtlcIn != 0 {
47✔
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()
47✔
1842
        forwardingPolicy := f.defaultForwardingPolicy(
47✔
1843
                ourContribution.ChannelStateBounds,
47✔
1844
        )
47✔
1845

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

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

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

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

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

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

×
1917
                        return
×
1918
                }
×
1919

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

1925
        err = reservation.ProcessSingleContribution(remoteContribution)
47✔
1926
        if err != nil {
53✔
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)",
41✔
1933
                msg.PendingChannelID)
41✔
1934
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
41✔
1935
        log.Debugf("Remote party accepted channel state space bounds: %v",
41✔
1936
                lnutils.SpewLogClosure(bounds))
41✔
1937
        params := remoteContribution.ChannelConfig.CommitmentParams
41✔
1938
        log.Debugf("Remote party accepted commitment rendering params: %v",
41✔
1939
                lnutils.SpewLogClosure(params))
41✔
1940

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

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

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

1971
        if err := peer.SendMessage(true, &fundingAccept); err != nil {
41✔
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) {
33✔
1985

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

1993
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
33✔
1994
        if err != nil {
33✔
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()
33✔
2002

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

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

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

33✔
2013
        // Perform some basic validation of any custom TLV records included.
33✔
2014
        //
33✔
2015
        // TODO: Return errors as funding.Error to give context to remote peer?
33✔
2016
        if resCtx.channelType != nil {
38✔
2017
                // We'll want to quickly check that the ChannelType echoed by
5✔
2018
                // the channel request recipient matches what we proposed.
5✔
2019
                if msg.ChannelType == nil {
6✔
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)
4✔
2026
                ackedFeatures := lnwire.RawFeatureVector(*msg.ChannelType)
4✔
2027
                if !proposedFeatures.Equals(&ackedFeatures) {
4✔
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 {
5✔
2036
                        if msg.LeaseExpiry == nil {
1✔
2037
                                err := errors.New("lease expiry not echoed " +
×
2038
                                        "back")
×
2039
                                f.failFundingFlow(peer, cid, err)
×
2040
                                return
×
2041
                        }
×
2042
                        if uint32(*msg.LeaseExpiry) !=
1✔
2043
                                resCtx.reservation.LeaseExpiry() {
1✔
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 {
33✔
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 {
31✔
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
31✔
2100
        if !resCtx.reservation.IsZeroConf() && minDepth == 0 {
31✔
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))
31✔
2113
        bounds := channeldb.ChannelStateBounds{
31✔
2114
                ChanReserve:      msg.ChannelReserve,
31✔
2115
                MaxPendingAmount: msg.MaxValueInFlight,
31✔
2116
                MinHTLC:          msg.HtlcMinimum,
31✔
2117
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
31✔
2118
        }
31✔
2119
        commitParams := channeldb.CommitmentParams{
31✔
2120
                DustLimit: msg.DustLimit,
31✔
2121
                CsvDelay:  msg.CsvDelay,
31✔
2122
        }
31✔
2123
        err = resCtx.reservation.CommitConstraints(
31✔
2124
                &bounds, &commitParams, resCtx.maxLocalCsv, false,
31✔
2125
        )
31✔
2126
        if err != nil {
32✔
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{
30✔
2133
                ChannelStateBounds: channeldb.ChannelStateBounds{
30✔
2134
                        MaxPendingAmount: resCtx.remoteMaxValue,
30✔
2135
                        ChanReserve:      resCtx.remoteChanReserve,
30✔
2136
                        MinHTLC:          resCtx.remoteMinHtlc,
30✔
2137
                        MaxAcceptedHtlcs: resCtx.remoteMaxHtlcs,
30✔
2138
                },
30✔
2139
                CommitmentParams: channeldb.CommitmentParams{
30✔
2140
                        DustLimit: msg.DustLimit,
30✔
2141
                        CsvDelay:  resCtx.remoteCsvDelay,
30✔
2142
                },
30✔
2143
                MultiSigKey: keychain.KeyDescriptor{
30✔
2144
                        PubKey: copyPubKey(msg.FundingKey),
30✔
2145
                },
30✔
2146
                RevocationBasePoint: keychain.KeyDescriptor{
30✔
2147
                        PubKey: copyPubKey(msg.RevocationPoint),
30✔
2148
                },
30✔
2149
                PaymentBasePoint: keychain.KeyDescriptor{
30✔
2150
                        PubKey: copyPubKey(msg.PaymentPoint),
30✔
2151
                },
30✔
2152
                DelayBasePoint: keychain.KeyDescriptor{
30✔
2153
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
30✔
2154
                },
30✔
2155
                HtlcBasePoint: keychain.KeyDescriptor{
30✔
2156
                        PubKey: copyPubKey(msg.HtlcPoint),
30✔
2157
                },
30✔
2158
        }
30✔
2159

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

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

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

×
2177
                        return
×
2178
                }
×
2179

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

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

30✔
2187
        // The wallet has detected that a PSBT funding process was requested by
30✔
2188
        // the user and has halted the funding process after negotiating the
30✔
2189
        // multisig keys. We now have everything that is needed for the user to
30✔
2190
        // start constructing a PSBT that sends to the multisig funding address.
30✔
2191
        var psbtIntent *chanfunding.PsbtIntent
30✔
2192
        if psbtErr, ok := err.(*lnwallet.PsbtFundingRequired); ok {
31✔
2193
                // Return the information that is needed by the user to
1✔
2194
                // construct the PSBT back to the caller.
1✔
2195
                addr, amt, packet, err := psbtErr.Intent.FundingParams()
1✔
2196
                if err != nil {
1✔
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
1✔
2204
                err = packet.Serialize(&buf)
1✔
2205
                if err != nil {
1✔
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{
1✔
2212
                        PendingChanId: pendingChanID[:],
1✔
2213
                        Update: &lnrpc.OpenStatusUpdate_PsbtFund{
1✔
2214
                                PsbtFund: &lnrpc.ReadyForPsbtFunding{
1✔
2215
                                        FundingAddress: addr.EncodeAddress(),
1✔
2216
                                        FundingAmount:  amt,
1✔
2217
                                        Psbt:           buf.Bytes(),
1✔
2218
                                },
1✔
2219
                        },
1✔
2220
                }
1✔
2221
                psbtIntent = psbtErr.Intent
1✔
2222
        } else if err != nil {
30✔
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, "+
30✔
2230
                "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
30✔
2231
                msg.CsvDelay)
30✔
2232
        bounds = remoteContribution.ChannelConfig.ChannelStateBounds
30✔
2233
        log.Debugf("Remote party accepted channel state space bounds: %v",
30✔
2234
                lnutils.SpewLogClosure(bounds))
30✔
2235
        commitParams = remoteContribution.ChannelConfig.CommitmentParams
30✔
2236
        log.Debugf("Remote party accepted commitment rendering params: %v",
30✔
2237
                lnutils.SpewLogClosure(commitParams))
30✔
2238

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

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

2251
                // With the new goroutine spawned, we can now exit to unblock
2252
                // the main event loop.
2253
                return
1✔
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)
30✔
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) {
1✔
2268

1✔
2269
        // failFlow is a helper that logs an error message with the current
1✔
2270
        // context and then fails the funding flow.
1✔
2271
        peerKey := resCtx.peer.IdentityKey()
1✔
2272
        failFlow := func(errMsg string, cause error) {
2✔
2273
                log.Errorf("Unable to handle funding accept message "+
1✔
2274
                        "for peer_key=%x, pending_chan_id=%x: %s: %v",
1✔
2275
                        peerKey.SerializeCompressed(), cid.tempChanID, errMsg,
1✔
2276
                        cause)
1✔
2277
                f.failFundingFlow(resCtx.peer, cid, cause)
1✔
2278
        }
1✔
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 {
1✔
2284
        case err := <-intent.PsbtReady:
1✔
2285
                switch err {
1✔
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:
1✔
2289
                        failFlow("aborting PSBT flow", err)
1✔
2290
                        return
1✔
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:
1✔
2296
                        log.Infof("Remote canceled, aborting PSBT flow "+
1✔
2297
                                "for peer_key=%x, pending_chan_id=%x",
1✔
2298
                                peerKey.SerializeCompressed(), cid.tempChanID)
1✔
2299
                        return
1✔
2300

2301
                // Nil error means the flow continues normally now.
2302
                case nil:
1✔
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(
1✔
2314
                        f.cfg.AuxFundingController,
1✔
2315
                        func(c AuxFundingController) AuxFundingDescResult {
1✔
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 {
1✔
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)
1✔
2338
                if err != nil {
1✔
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)
1✔
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) {
30✔
2362

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

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

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

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

30✔
2387
        // Before sending FundingCreated sent, we notify Brontide to keep track
30✔
2388
        // of this pending open channel.
30✔
2389
        err := resCtx.peer.AddPendingChannel(channelID, f.quit)
30✔
2390
        if err != nil {
30✔
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)
30✔
2400

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

30✔
2407
        // If this is a taproot channel, then we'll need to populate the musig2
30✔
2408
        // partial sig field instead of the regular commit sig field.
30✔
2409
        if resCtx.reservation.IsTaproot() {
33✔
2410
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
3✔
2411
                if !ok {
3✔
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(
3✔
2421
                        partialSig.ToWireSig(),
3✔
2422
                )
3✔
2423
        } else {
28✔
2424
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
28✔
2425
                if err != nil {
28✔
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)
30✔
2433

30✔
2434
        if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
30✔
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) {
28✔
2450

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

28✔
2454
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
28✔
2455
        if err != nil {
28✔
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
28✔
2466
        log.Infof("completing pending_id(%x) with ChannelPoint(%v)",
28✔
2467
                pendingChanID[:], fundingOut)
28✔
2468

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

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

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

×
2485
                        return
×
2486
                }
×
2487

2488
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
3✔
2489
                        &partialSig,
3✔
2490
                )
3✔
2491
        } else {
26✔
2492
                commitSig, err = msg.CommitSig.ToSignature()
26✔
2493
                if err != nil {
26✔
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(
28✔
2503
                f.cfg.AuxFundingController,
28✔
2504
                func(c AuxFundingController) AuxFundingDescResult {
28✔
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 {
28✔
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(
28✔
2529
                &fundingOut, commitSig, auxFundingDesc,
28✔
2530
        )
28✔
2531
        if err != nil {
28✔
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
28✔
2539

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

28✔
2544
        // If something goes wrong before the funding transaction is confirmed,
28✔
2545
        // we use this convenience method to delete the pending OpenChannel
28✔
2546
        // from the database.
28✔
2547
        deleteFromDatabase := func() {
28✔
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)
28✔
2576
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
28✔
2577

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

28✔
2580
        // For taproot channels, we'll need to send over a partial signature
28✔
2581
        // that includes the nonce along side the signature.
28✔
2582
        _, sig := resCtx.reservation.OurSignatures()
28✔
2583
        if resCtx.reservation.IsTaproot() {
31✔
2584
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
3✔
2585
                if !ok {
3✔
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(
3✔
2596
                        partialSig.ToWireSig(),
3✔
2597
                )
3✔
2598
        } else {
26✔
2599
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
26✔
2600
                if err != nil {
26✔
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 {
28✔
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)
28✔
2621

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

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

28✔
2627
        // With their signature for our version of the commitment transaction
28✔
2628
        // verified, we can now send over our signature to the remote peer.
28✔
2629
        if err := peer.SendMessage(true, fundingSigned); err != nil {
28✔
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)
28✔
2640
        if err != nil {
28✔
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 {
28✔
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{}))
28✔
2656

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

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

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

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

28✔
2708
        // If the pending channel ID is not found, fail the funding flow.
28✔
2709
        if !ok {
28✔
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()
28✔
2723
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
28✔
2724
        if err != nil {
28✔
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 {
28✔
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()
28✔
2744
        permChanID := lnwire.NewChanIDFromOutPoint(*fundingPoint)
28✔
2745
        f.localDiscoverySignals.Store(permChanID, make(chan struct{}))
28✔
2746

28✔
2747
        // We have to store the forwardingPolicy before the reservation context
28✔
2748
        // is deleted. The policy will then be read and applied in
28✔
2749
        // newChanAnnouncement.
28✔
2750
        err = f.saveInitialForwardingPolicy(
28✔
2751
                permChanID, &resCtx.forwardingPolicy,
28✔
2752
        )
28✔
2753
        if err != nil {
28✔
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
28✔
2761
        if resCtx.reservation.IsTaproot() {
31✔
2762
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
3✔
2763
                if err != nil {
3✔
2764
                        f.failFundingFlow(peer, cid, err)
×
2765

×
2766
                        return
×
2767
                }
×
2768

2769
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
3✔
2770
                        &partialSig,
3✔
2771
                )
3✔
2772
        } else {
26✔
2773
                commitSig, err = msg.CommitSig.ToSignature()
26✔
2774
                if err != nil {
26✔
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(
28✔
2782
                nil, commitSig,
28✔
2783
        )
28✔
2784
        if err != nil {
28✔
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)
28✔
2794

28✔
2795
        // Broadcast the finalized funding transaction to the network, but only
28✔
2796
        // if we actually have the funding transaction.
28✔
2797
        if completeChan.ChanType.HasFundingTx() {
55✔
2798
                fundingTx := completeChan.FundingTxn
27✔
2799
                var fundingTxBuf bytes.Buffer
27✔
2800
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
27✔
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",
27✔
2811
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
27✔
2812

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

27✔
2819
                err = f.cfg.PublishTransaction(fundingTx, label)
27✔
2820
                if err != nil {
27✔
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(
28✔
2839
                f.cfg.AuxFundingController,
28✔
2840
                func(controller AuxFundingController) error {
28✔
2841
                        return controller.ChannelFinalized(cid.tempChanID)
×
2842
                },
×
2843
        )
2844
        if err != nil {
28✔
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 {
28✔
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), "+
28✔
2860
                "waiting for channel open on-chain", pendingChanID[:],
28✔
2861
                fundingPoint)
28✔
2862

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

28✔
2875
        select {
28✔
2876
        case resCtx.updates <- upd:
28✔
2877
                // Inform the ChannelNotifier that the channel has entered
28✔
2878
                // pending open state.
28✔
2879
                f.cfg.NotifyPendingOpenChannelEvent(*fundingPoint, completeChan)
28✔
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)
28✔
2887
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
28✔
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) {
58✔
2982

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

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

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

58✔
2999
        select {
58✔
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:
22✔
3007
                // The fundingManager is shutting down, and will resume wait on
22✔
3008
                // startup.
22✔
3009
                return nil, ErrFundingManagerShuttingDown
22✔
3010

3011
        case confirmedChannel, ok := <-confChan:
35✔
3012
                if !ok {
35✔
3013
                        return nil, fmt.Errorf("waiting for funding" +
×
3014
                                "confirmation failed")
×
3015
                }
×
3016
                return confirmedChannel, nil
35✔
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) {
78✔
3023
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
78✔
3024
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
78✔
3025

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

3035
                return pkScript, nil
6✔
3036
        }
3037

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

3046
        return input.WitnessScriptHash(multiSigScript)
73✔
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) {
58✔
3061

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

58✔
3065
        // Register with the ChainNotifier for a notification once the funding
58✔
3066
        // transaction reaches `numConfs` confirmations.
58✔
3067
        txid := completeChan.FundingOutpoint.Hash
58✔
3068
        fundingScript, err := makeFundingScript(completeChan)
58✔
3069
        if err != nil {
58✔
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)
58✔
3076

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

3083
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
58✔
3084
                &txid, fundingScript, numConfs,
58✔
3085
                completeChan.BroadcastHeight(),
58✔
3086
        )
58✔
3087
        if err != nil {
58✔
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",
58✔
3095
                txid, numConfs)
58✔
3096

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

58✔
3100
        // Wait until the specified number of confirmations has been reached,
58✔
3101
        // we get a cancel signal, or the wallet signals a shutdown.
58✔
3102
        select {
58✔
3103
        case confDetails, ok = <-confNtfn.Confirmed:
35✔
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:
21✔
3113
                log.Warnf("fundingManager shutting down, stopping funding "+
21✔
3114
                        "flow for ChannelPoint(%v)",
21✔
3115
                        completeChan.FundingOutpoint)
21✔
3116
                return
21✔
3117
        }
3118

3119
        if !ok {
35✔
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
35✔
3127
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
35✔
3128
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
35✔
3129

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

35✔
3139
        select {
35✔
3140
        case confChan <- &confirmedChannel{
3141
                shortChanID: shortChanID,
3142
                fundingTx:   confDetails.Tx,
3143
        }:
35✔
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) {
26✔
3158

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

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

3168
        defer epochClient.Cancel()
26✔
3169

26✔
3170
        // On block maxHeight we will cancel the funding confirmation wait.
26✔
3171
        broadcastHeight := completeChan.BroadcastHeight()
26✔
3172
        maxHeight := broadcastHeight + MaxWaitNumBlocksFundingConf
26✔
3173
        for {
54✔
3174
                select {
28✔
3175
                case epoch, ok := <-epochClient.Epochs:
5✔
3176
                        if !ok {
5✔
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 {
7✔
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:
16✔
3200
                        return
16✔
3201

3202
                case <-f.quit:
9✔
3203
                        // The fundingManager is shutting down, will resume
9✔
3204
                        // waiting for the funding transaction on startup.
9✔
3205
                        return
9✔
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) {
35✔
3217
        if c.IsInitiator && c.ChanType.HasFundingTx() {
52✔
3218
                shortChanID := c.ShortChanID()
17✔
3219

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

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

17✔
3230
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
17✔
3231
                if err != nil {
17✔
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 {
31✔
3244

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

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

31✔
3251
        // Now that that the channel has been fully confirmed, we'll request
31✔
3252
        // that the wallet fully verify this channel to ensure that it can be
31✔
3253
        // used.
31✔
3254
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
31✔
3255
        if err != nil {
31✔
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() {
34✔
3263
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
3264
                if err != nil {
3✔
3265
                        return fmt.Errorf("unable to request alias: %w", err)
×
3266
                }
×
3267

3268
                err = f.cfg.AliasManager.AddLocalAlias(
3✔
3269
                        aliasScid, confChannel.shortChanID, true, false,
3✔
3270
                )
3✔
3271
                if err != nil {
3✔
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(
31✔
3283
                &fundingPoint, markedOpen, &confChannel.shortChanID,
31✔
3284
        )
31✔
3285
        if err != nil {
31✔
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)
31✔
3293
        if err != nil {
31✔
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)
31✔
3300

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

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

3313
        return nil
31✔
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 {
36✔
3321

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

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

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

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

5✔
3343
                f.nonceMtx.Lock()
5✔
3344
                localNonce, ok := f.pendingMusigNonces[chanID]
5✔
3345
                if !ok {
10✔
3346
                        // If we don't have any nonces generated yet for this
5✔
3347
                        // first state, then we'll generate them now and stow
5✔
3348
                        // them away.  When we receive the funding locked
5✔
3349
                        // message, we'll then pass along this same set of
5✔
3350
                        // nonces.
5✔
3351
                        newNonce, err := channel.GenMusigNonces()
5✔
3352
                        if err != nil {
5✔
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
5✔
3360
                        f.pendingMusigNonces[chanID] = localNonce
5✔
3361
                }
3362
                f.nonceMtx.Unlock()
5✔
3363

5✔
3364
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
5✔
3365
                        localNonce.PubNonce,
5✔
3366
                )
5✔
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() {
43✔
3375
                aliases := f.cfg.AliasManager.GetAliases(
7✔
3376
                        completeChan.ShortChanID(),
7✔
3377
                )
7✔
3378
                if len(aliases) == 0 {
7✔
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]
7✔
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 {
72✔
3399
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
36✔
3400
                if err != nil {
37✔
3401
                        return err
1✔
3402
                }
1✔
3403

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

35✔
3411
                // We could also refresh the channel state instead of checking
35✔
3412
                // whether the feature was negotiated, but this saves us a
35✔
3413
                // database read.
35✔
3414
                if channelReadyMsg.AliasScid == nil && localAlias &&
35✔
3415
                        remoteAlias {
35✔
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 "+
35✔
3448
                        "for ChannelID(%v)", peerKey, chanID)
35✔
3449

35✔
3450
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
70✔
3451
                        // Sending succeeded, we can break out and continue the
35✔
3452
                        // funding flow.
35✔
3453
                        break
35✔
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
35✔
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) {
60✔
3467

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

3477
        // Avoid a tight loop if peer is offline.
3478
        if _, err := f.waitForPeerOnline(node); err != nil {
60✔
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)
60✔
3486
        if err != nil {
60✔
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 {
96✔
3495
                return false, nil
36✔
3496
        }
36✔
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)
25✔
3502

25✔
3503
        return !loaded, nil
25✔
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) {
27✔
3511

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

27✔
3518
        // We don't necessarily want to go as low as the remote party allows.
27✔
3519
        // Check it against our default forwarding policy.
27✔
3520
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
28✔
3521
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
1✔
3522
        }
1✔
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
27✔
3528
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
27✔
3529
        if fwdMaxHTLC > capacityMSat {
27✔
3530
                fwdMaxHTLC = capacityMSat
×
3531
        }
×
3532

3533
        return fwdMinHTLC, fwdMaxHTLC
27✔
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 {
25✔
3548

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

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

25✔
3553
        ann, err := f.newChanAnnouncement(
25✔
3554
                f.cfg.IDKey, completeChan.IdentityPub,
25✔
3555
                &completeChan.LocalChanCfg.MultiSigKey,
25✔
3556
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
25✔
3557
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
25✔
3558
                completeChan.ChanType,
25✔
3559
        )
25✔
3560
        if err != nil {
25✔
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(
25✔
3568
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
25✔
3569
                discovery.ChannelPoint(completeChan.FundingOutpoint),
25✔
3570
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
25✔
3571
        )
25✔
3572
        select {
25✔
3573
        case err := <-errChan:
25✔
3574
                if err != nil {
25✔
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(
25✔
3590
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
25✔
3591
        )
25✔
3592
        select {
25✔
3593
        case err := <-errChan:
25✔
3594
                if err != nil {
25✔
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
25✔
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 {
27✔
3620

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

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

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

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

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

19✔
3667
                fundingScript, err := makeFundingScript(completeChan)
19✔
3668
                if err != nil {
19✔
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(
19✔
3677
                        &txid, fundingScript, numConfs,
19✔
3678
                        completeChan.BroadcastHeight(),
19✔
3679
                )
19✔
3680
                if err != nil {
19✔
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 {
19✔
3689
                case _, ok := <-confNtfn.Confirmed:
17✔
3690
                        if !ok {
17✔
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:
3✔
3699
                        return fmt.Errorf("%v, stopping funding flow for "+
3✔
3700
                                "ChannelPoint(%v)",
3✔
3701
                                ErrFundingManagerShuttingDown,
3✔
3702
                                completeChan.FundingOutpoint)
3✔
3703
                }
3704

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

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

17✔
3711
                // If this is a non-zero-conf option-scid-alias channel, we'll
17✔
3712
                // delete the mappings the gossiper uses so that ChannelUpdates
17✔
3713
                // with aliases won't be accepted. This is done elsewhere for
17✔
3714
                // zero-conf channels.
17✔
3715
                isScidFeature := completeChan.NegotiatedAliasFeature()
17✔
3716
                isZeroConf := completeChan.IsZeroConf()
17✔
3717
                if isScidFeature && !isZeroConf {
18✔
3718
                        baseScid := completeChan.ShortChanID()
1✔
3719
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
1✔
3720
                        if err != nil {
1✔
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(
1✔
3733
                                baseScid, baseScid,
1✔
3734
                        )
1✔
3735
                        if err != nil {
1✔
NEW
3736
                                return fmt.Errorf("failed reassigning alias "+
×
NEW
3737
                                        "edge into graph: %v", err)
×
UNCOV
3738
                        }
×
3739

3740
                        // We send the rassigned ChannelUpdate to the peer.
3741
                        err = f.sendChanUpdate(
1✔
3742
                                completeChan, &baseScid, ourPolicy,
1✔
3743
                        )
1✔
3744
                        if err != nil {
1✔
3745
                                return fmt.Errorf("failed to re-add to "+
×
3746
                                        "graph: %v", err)
×
3747
                        }
×
3748
                }
3749

3750
                // Create and broadcast the proofs required to make this channel
3751
                // public and usable for other nodes for routing.
3752
                err = f.announceChannel(
17✔
3753
                        f.cfg.IDKey, completeChan.IdentityPub,
17✔
3754
                        &completeChan.LocalChanCfg.MultiSigKey,
17✔
3755
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
17✔
3756
                        *shortChanID, chanID, completeChan.ChanType,
17✔
3757
                )
17✔
3758
                if err != nil {
18✔
3759
                        return fmt.Errorf("channel announcement failed: %w",
1✔
3760
                                err)
1✔
3761
                }
1✔
3762

3763
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
17✔
3764
                        "sent to gossiper", &fundingPoint, shortChanID)
17✔
3765
        }
3766

3767
        return nil
25✔
3768
}
3769

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

3784
        // We'll need to refresh the channel state so that things are properly
3785
        // populated when validating the channel state. Otherwise, a panic may
3786
        // occur due to inconsistency in the OpenChannel struct.
3787
        err = c.Refresh()
5✔
3788
        if err != nil {
6✔
3789
                return fmt.Errorf("unable to refresh channel state: %w", err)
1✔
3790
        }
1✔
3791

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

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

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

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

3831
                // Send the ChannelUpdate with the confirmed scid to the peer.
3832
                err = f.sendChanUpdate(
3✔
3833
                        c, &confChan.shortChanID, ourPolicy,
3✔
3834
                )
3✔
3835
                if err != nil {
3✔
NEW
3836
                        return fmt.Errorf("failed to send ChannelUpdate to "+
×
NEW
3837
                                "gossiper: %v", err)
×
UNCOV
3838
                }
×
3839
        }
3840

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

3854
        // Update the confirmed transaction's label.
3855
        f.makeLabelForTx(c)
5✔
3856

5✔
3857
        return nil
5✔
3858
}
3859

3860
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3861
// is the verification nonce for the state created for us after the initial
3862
// commitment transaction signed as part of the funding flow.
3863
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3864
) (*musig2.Nonces, error) {
5✔
3865

5✔
3866
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
5✔
3867
                channel.RevocationProducer,
5✔
3868
        )
5✔
3869
        if err != nil {
5✔
3870
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3871
                        "nonces: %v", err)
×
3872
        }
×
3873

3874
        // We use the _next_ commitment height here as we need to generate the
3875
        // nonce for the next state the remote party will sign for us.
3876
        verNonce, err := channeldb.NewMusigVerificationNonce(
5✔
3877
                channel.LocalChanCfg.MultiSigKey.PubKey,
5✔
3878
                channel.LocalCommitment.CommitHeight+1,
5✔
3879
                musig2ShaChain,
5✔
3880
        )
5✔
3881
        if err != nil {
5✔
3882
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3883
                        "nonces: %v", err)
×
3884
        }
×
3885

3886
        return verNonce, nil
5✔
3887
}
3888

3889
// handleChannelReady finalizes the channel funding process and enables the
3890
// channel to enter normal operating mode.
3891
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3892
        msg *lnwire.ChannelReady) {
29✔
3893

29✔
3894
        defer f.wg.Done()
29✔
3895

29✔
3896
        // If we are in development mode, we'll wait for specified duration
29✔
3897
        // before processing the channel ready message.
29✔
3898
        if f.cfg.Dev != nil {
30✔
3899
                duration := f.cfg.Dev.ProcessChannelReadyWait
1✔
3900
                log.Warnf("Channel(%v): sleeping %v before processing "+
1✔
3901
                        "channel_ready", msg.ChanID, duration)
1✔
3902

1✔
3903
                select {
1✔
3904
                case <-time.After(duration):
1✔
3905
                        log.Warnf("Channel(%v): slept %v before processing "+
1✔
3906
                                "channel_ready", msg.ChanID, duration)
1✔
3907
                case <-f.quit:
×
3908
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
3909
                        return
×
3910
                }
3911
        }
3912

3913
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
29✔
3914
                "peer %x", msg.ChanID,
29✔
3915
                peer.IdentityKey().SerializeCompressed())
29✔
3916

29✔
3917
        // We now load or create a new channel barrier for this channel.
29✔
3918
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
29✔
3919
                msg.ChanID, struct{}{},
29✔
3920
        )
29✔
3921

29✔
3922
        // If we are currently in the process of handling a channel_ready
29✔
3923
        // message for this channel, ignore.
29✔
3924
        if loaded {
31✔
3925
                log.Infof("Already handling channelReady for "+
2✔
3926
                        "ChannelID(%v), ignoring.", msg.ChanID)
2✔
3927
                return
2✔
3928
        }
2✔
3929

3930
        // If not already handling channelReady for this channel, then the
3931
        // `LoadOrStore` has set up a barrier, and it will be removed once this
3932
        // function exits.
3933
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
28✔
3934

28✔
3935
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
28✔
3936
        if ok {
54✔
3937
                // Before we proceed with processing the channel_ready
26✔
3938
                // message, we'll wait for the local waitForFundingConfirmation
26✔
3939
                // goroutine to signal that it has the necessary state in
26✔
3940
                // place. Otherwise, we may be missing critical information
26✔
3941
                // required to handle forwarded HTLC's.
26✔
3942
                select {
26✔
3943
                case <-localDiscoverySignal:
26✔
3944
                        // Fallthrough
3945
                case <-f.quit:
×
3946
                        return
×
3947
                }
3948

3949
                // With the signal received, we can now safely delete the entry
3950
                // from the map.
3951
                f.localDiscoverySignals.Delete(msg.ChanID)
26✔
3952
        }
3953

3954
        // First, we'll attempt to locate the channel whose funding workflow is
3955
        // being finalized by this message. We go to the database rather than
3956
        // our reservation map as we may have restarted, mid funding flow. Also
3957
        // provide the node's public key to make the search faster.
3958
        chanID := msg.ChanID
28✔
3959
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
28✔
3960
        if err != nil {
28✔
3961
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
3962
                        "funding", chanID)
×
3963
                return
×
3964
        }
×
3965

3966
        // If this is a taproot channel, then we can generate the set of nonces
3967
        // the remote party needs to send the next remote commitment here.
3968
        var firstVerNonce *musig2.Nonces
28✔
3969
        if channel.ChanType.IsTaproot() {
33✔
3970
                firstVerNonce, err = genFirstStateMusigNonce(channel)
5✔
3971
                if err != nil {
5✔
3972
                        log.Error(err)
×
3973
                        return
×
3974
                }
×
3975
        }
3976

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

3994
                // We'll store the AliasScid so that invoice creation can use
3995
                // it.
3996
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
7✔
3997
                if err != nil {
7✔
3998
                        log.Errorf("unable to store peer's alias: %v", err)
×
3999
                        return
×
4000
                }
×
4001

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

4019
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4020
                                alias, channel.ShortChannelID, false, false,
×
4021
                        )
×
4022
                        if err != nil {
×
4023
                                log.Errorf("unable to add local alias: %v",
×
4024
                                        err)
×
4025
                                return
×
4026
                        }
×
4027

4028
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4029
                        if err != nil {
×
4030
                                log.Errorf("unable to fetch second "+
×
4031
                                        "commitment point: %v", err)
×
4032
                                return
×
4033
                        }
×
4034

4035
                        channelReadyMsg := lnwire.NewChannelReady(
×
4036
                                chanID, secondPoint,
×
4037
                        )
×
4038
                        channelReadyMsg.AliasScid = &alias
×
4039

×
4040
                        if firstVerNonce != nil {
×
4041
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4042
                                        firstVerNonce.PubNonce,
×
4043
                                )
×
4044
                        }
×
4045

4046
                        err = peer.SendMessage(true, channelReadyMsg)
×
4047
                        if err != nil {
×
4048
                                log.Errorf("unable to send channel_ready: %v",
×
4049
                                        err)
×
4050
                                return
×
4051
                        }
×
4052
                }
4053
        }
4054

4055
        // If the RemoteNextRevocation is non-nil, it means that we have
4056
        // already processed channelReady for this channel, so ignore. This
4057
        // check is after the alias logic so we store the peer's most recent
4058
        // alias. The spec requires us to validate that subsequent
4059
        // channel_ready messages use the same per commitment point (the
4060
        // second), but it is not actually necessary since we'll just end up
4061
        // ignoring it. We are, however, required to *send* the same per
4062
        // commitment point, since another pedantic implementation might
4063
        // verify it.
4064
        if channel.RemoteNextRevocation != nil {
30✔
4065
                log.Infof("Received duplicate channelReady for "+
2✔
4066
                        "ChannelID(%v), ignoring.", chanID)
2✔
4067
                return
2✔
4068
        }
2✔
4069

4070
        // If this is a taproot channel, then we'll need to map the received
4071
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4072
        // required in order to make the channel whole.
4073
        var chanOpts []lnwallet.ChannelOpt
27✔
4074
        if channel.ChanType.IsTaproot() {
32✔
4075
                f.nonceMtx.Lock()
5✔
4076
                localNonce, ok := f.pendingMusigNonces[chanID]
5✔
4077
                if !ok {
6✔
4078
                        // If there's no pending nonce for this channel ID,
1✔
4079
                        // we'll use the one generated above.
1✔
4080
                        localNonce = firstVerNonce
1✔
4081
                        f.pendingMusigNonces[chanID] = firstVerNonce
1✔
4082
                }
1✔
4083
                f.nonceMtx.Unlock()
5✔
4084

5✔
4085
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
5✔
4086
                        chanID)
5✔
4087

5✔
4088
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
5✔
4089
                        errNoLocalNonce,
5✔
4090
                )
5✔
4091
                if err != nil {
5✔
4092
                        cid := newChanIdentifier(msg.ChanID)
×
4093
                        f.sendWarning(peer, cid, err)
×
4094

×
4095
                        return
×
4096
                }
×
4097

4098
                chanOpts = append(
5✔
4099
                        chanOpts,
5✔
4100
                        lnwallet.WithLocalMusigNonces(localNonce),
5✔
4101
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
5✔
4102
                                PubNonce: remoteNonce,
5✔
4103
                        }),
5✔
4104
                )
5✔
4105

5✔
4106
                // Inform the aux funding controller that the liquidity in the
5✔
4107
                // custom channel is now ready to be advertised. We potentially
5✔
4108
                // haven't sent our own channel ready message yet, but other
5✔
4109
                // than that the channel is ready to count toward available
5✔
4110
                // liquidity.
5✔
4111
                err = fn.MapOptionZ(
5✔
4112
                        f.cfg.AuxFundingController,
5✔
4113
                        func(controller AuxFundingController) error {
5✔
4114
                                return controller.ChannelReady(
×
4115
                                        lnwallet.NewAuxChanState(channel),
×
4116
                                )
×
4117
                        },
×
4118
                )
4119
                if err != nil {
5✔
4120
                        cid := newChanIdentifier(msg.ChanID)
×
4121
                        f.sendWarning(peer, cid, err)
×
4122

×
4123
                        return
×
4124
                }
×
4125
        }
4126

4127
        // The channel_ready message contains the next commitment point we'll
4128
        // need to create the next commitment state for the remote party. So
4129
        // we'll insert that into the channel now before passing it along to
4130
        // other sub-systems.
4131
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
27✔
4132
        if err != nil {
27✔
4133
                log.Errorf("unable to insert next commitment point: %v", err)
×
4134
                return
×
4135
        }
×
4136

4137
        // Before we can add the channel to the peer, we'll need to ensure that
4138
        // we have an initial forwarding policy set.
4139
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
27✔
4140
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4141
                        err)
×
4142
        }
×
4143

4144
        err = peer.AddNewChannel(&lnpeer.NewChannel{
27✔
4145
                OpenChannel: channel,
27✔
4146
                ChanOpts:    chanOpts,
27✔
4147
        }, f.quit)
27✔
4148
        if err != nil {
27✔
4149
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4150
                        channel.FundingOutpoint,
×
4151
                        peer.IdentityKey().SerializeCompressed(), err,
×
4152
                )
×
4153
        }
×
4154
}
4155

4156
// handleChannelReadyReceived is called once the remote's channelReady message
4157
// is received and processed. At this stage, we must have sent out our
4158
// channelReady message, once the remote's channelReady is processed, the
4159
// channel is now active, thus we change its state to `addedToGraph` to
4160
// let the channel start handling routing.
4161
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4162
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4163
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
25✔
4164

25✔
4165
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
25✔
4166

25✔
4167
        // Since we've sent+received funding locked at this point, we
25✔
4168
        // can clean up the pending musig2 nonce state.
25✔
4169
        f.nonceMtx.Lock()
25✔
4170
        delete(f.pendingMusigNonces, chanID)
25✔
4171
        f.nonceMtx.Unlock()
25✔
4172

25✔
4173
        var peerAlias *lnwire.ShortChannelID
25✔
4174
        if channel.IsZeroConf() {
30✔
4175
                // We'll need to wait until channel_ready has been received and
5✔
4176
                // the peer lets us know the alias they want to use for the
5✔
4177
                // channel. With this information, we can then construct a
5✔
4178
                // ChannelUpdate for them.  If an alias does not yet exist,
5✔
4179
                // we'll just return, letting the next iteration of the loop
5✔
4180
                // check again.
5✔
4181
                var defaultAlias lnwire.ShortChannelID
5✔
4182
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
5✔
4183
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
5✔
4184
                if foundAlias == defaultAlias {
5✔
4185
                        return nil
×
4186
                }
×
4187

4188
                peerAlias = &foundAlias
5✔
4189
        }
4190

4191
        err := f.addToGraph(channel, scid, peerAlias, nil)
25✔
4192
        if err != nil {
25✔
4193
                return fmt.Errorf("failed adding to graph: %w", err)
×
4194
        }
×
4195

4196
        // As the channel is now added to the ChannelRouter's topology, the
4197
        // channel is moved to the next state of the state machine. It will be
4198
        // moved to the last state (actually deleted from the database) after
4199
        // the channel is finally announced.
4200
        err = f.saveChannelOpeningState(
25✔
4201
                &channel.FundingOutpoint, addedToGraph, scid,
25✔
4202
        )
25✔
4203
        if err != nil {
25✔
4204
                return fmt.Errorf("error setting channel state to"+
×
4205
                        " addedToGraph: %w", err)
×
4206
        }
×
4207

4208
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
25✔
4209
                "added to graph", chanID, scid)
25✔
4210

25✔
4211
        err = fn.MapOptionZ(
25✔
4212
                f.cfg.AuxFundingController,
25✔
4213
                func(controller AuxFundingController) error {
25✔
4214
                        return controller.ChannelReady(
×
4215
                                lnwallet.NewAuxChanState(channel),
×
4216
                        )
×
4217
                },
×
4218
        )
4219
        if err != nil {
25✔
4220
                return fmt.Errorf("failed notifying aux funding controller "+
×
4221
                        "about channel ready: %w", err)
×
4222
        }
×
4223

4224
        // Give the caller a final update notifying them that the channel is
4225
        fundingPoint := channel.FundingOutpoint
25✔
4226
        cp := &lnrpc.ChannelPoint{
25✔
4227
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
25✔
4228
                        FundingTxidBytes: fundingPoint.Hash[:],
25✔
4229
                },
25✔
4230
                OutputIndex: fundingPoint.Index,
25✔
4231
        }
25✔
4232

25✔
4233
        if updateChan != nil {
36✔
4234
                upd := &lnrpc.OpenStatusUpdate{
11✔
4235
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
11✔
4236
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
11✔
4237
                                        ChannelPoint: cp,
11✔
4238
                                },
11✔
4239
                        },
11✔
4240
                        PendingChanId: pendingChanID[:],
11✔
4241
                }
11✔
4242

11✔
4243
                select {
11✔
4244
                case updateChan <- upd:
11✔
4245
                case <-f.quit:
×
4246
                        return ErrFundingManagerShuttingDown
×
4247
                }
4248
        }
4249

4250
        return nil
25✔
4251
}
4252

4253
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4254
// policy set for the given channel. If we don't, we'll fall back to the default
4255
// values.
4256
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4257
        channel *channeldb.OpenChannel) error {
27✔
4258

27✔
4259
        // Before we can add the channel to the peer, we'll need to ensure that
27✔
4260
        // we have an initial forwarding policy set. This should always be the
27✔
4261
        // case except for a channel that was created with lnd <= 0.15.5 and
27✔
4262
        // is still pending while updating to this version.
27✔
4263
        var needDBUpdate bool
27✔
4264
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
27✔
4265
        if err != nil {
27✔
4266
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4267
                        "falling back to default values: %v", err)
×
4268

×
4269
                forwardingPolicy = f.defaultForwardingPolicy(
×
4270
                        channel.LocalChanCfg.ChannelStateBounds,
×
4271
                )
×
4272
                needDBUpdate = true
×
4273
        }
×
4274

4275
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4276
        // after 0.16.x, so if a channel was opened with such a version and is
4277
        // still pending while updating to this version, we'll need to set the
4278
        // values to the default values.
4279
        if forwardingPolicy.MinHTLCOut == 0 {
41✔
4280
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
14✔
4281
                needDBUpdate = true
14✔
4282
        }
14✔
4283
        if forwardingPolicy.MaxHTLC == 0 {
41✔
4284
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
14✔
4285
                needDBUpdate = true
14✔
4286
        }
14✔
4287

4288
        // And finally, if we found that the values currently stored aren't
4289
        // sufficient for the link, we'll update the database.
4290
        if needDBUpdate {
41✔
4291
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
14✔
4292
                if err != nil {
14✔
4293
                        return fmt.Errorf("unable to update initial "+
×
4294
                                "forwarding policy: %v", err)
×
4295
                }
×
4296
        }
4297

4298
        return nil
27✔
4299
}
4300

4301
// chanAnnouncement encapsulates the two authenticated announcements that we
4302
// send out to the network after a new channel has been created locally.
4303
type chanAnnouncement struct {
4304
        chanAnn       *lnwire.ChannelAnnouncement1
4305
        chanUpdateAnn *lnwire.ChannelUpdate1
4306
        chanProof     *lnwire.AnnounceSignatures1
4307
}
4308

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

43✔
4324
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
43✔
4325

43✔
4326
        // The unconditional section of the announcement is the ShortChannelID
43✔
4327
        // itself which compactly encodes the location of the funding output
43✔
4328
        // within the blockchain.
43✔
4329
        chanAnn := &lnwire.ChannelAnnouncement1{
43✔
4330
                ShortChannelID: shortChanID,
43✔
4331
                Features:       lnwire.NewRawFeatureVector(),
43✔
4332
                ChainHash:      chainHash,
43✔
4333
        }
43✔
4334

43✔
4335
        // If this is a taproot channel, then we'll set a special bit in the
43✔
4336
        // feature vector to indicate to the routing layer that this needs a
43✔
4337
        // slightly different type of validation.
43✔
4338
        //
43✔
4339
        // TODO(roasbeef): temp, remove after gossip 1.5
43✔
4340
        if chanType.IsTaproot() {
48✔
4341
                log.Debugf("Applying taproot feature bit to "+
5✔
4342
                        "ChannelAnnouncement for %v", chanID)
5✔
4343

5✔
4344
                chanAnn.Features.Set(
5✔
4345
                        lnwire.SimpleTaprootChannelsRequiredStaging,
5✔
4346
                )
5✔
4347
        }
5✔
4348

4349
        // The chanFlags field indicates which directed edge of the channel is
4350
        // being updated within the ChannelUpdateAnnouncement announcement
4351
        // below. A value of zero means it's the edge of the "first" node and 1
4352
        // being the other node.
4353
        var chanFlags lnwire.ChanUpdateChanFlags
43✔
4354

43✔
4355
        // The lexicographical ordering of the two identity public keys of the
43✔
4356
        // nodes indicates which of the nodes is "first". If our serialized
43✔
4357
        // identity key is lower than theirs then we're the "first" node and
43✔
4358
        // second otherwise.
43✔
4359
        selfBytes := localPubKey.SerializeCompressed()
43✔
4360
        remoteBytes := remotePubKey.SerializeCompressed()
43✔
4361
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
65✔
4362
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
22✔
4363
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
22✔
4364
                copy(
22✔
4365
                        chanAnn.BitcoinKey1[:],
22✔
4366
                        localFundingKey.PubKey.SerializeCompressed(),
22✔
4367
                )
22✔
4368
                copy(
22✔
4369
                        chanAnn.BitcoinKey2[:],
22✔
4370
                        remoteFundingKey.SerializeCompressed(),
22✔
4371
                )
22✔
4372

22✔
4373
                // If we're the first node then update the chanFlags to
22✔
4374
                // indicate the "direction" of the update.
22✔
4375
                chanFlags = 0
22✔
4376
        } else {
44✔
4377
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
22✔
4378
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
22✔
4379
                copy(
22✔
4380
                        chanAnn.BitcoinKey1[:],
22✔
4381
                        remoteFundingKey.SerializeCompressed(),
22✔
4382
                )
22✔
4383
                copy(
22✔
4384
                        chanAnn.BitcoinKey2[:],
22✔
4385
                        localFundingKey.PubKey.SerializeCompressed(),
22✔
4386
                )
22✔
4387

22✔
4388
                // If we're the second node then update the chanFlags to
22✔
4389
                // indicate the "direction" of the update.
22✔
4390
                chanFlags = 1
22✔
4391
        }
22✔
4392

4393
        // Our channel update message flags will signal that we support the
4394
        // max_htlc field.
4395
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
43✔
4396

43✔
4397
        // We announce the channel with the default values. Some of
43✔
4398
        // these values can later be changed by crafting a new ChannelUpdate.
43✔
4399
        chanUpdateAnn := &lnwire.ChannelUpdate1{
43✔
4400
                ShortChannelID: shortChanID,
43✔
4401
                ChainHash:      chainHash,
43✔
4402
                Timestamp:      uint32(time.Now().Unix()),
43✔
4403
                MessageFlags:   msgFlags,
43✔
4404
                ChannelFlags:   chanFlags,
43✔
4405
                TimeLockDelta: uint16(
43✔
4406
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
43✔
4407
                ),
43✔
4408
                HtlcMinimumMsat: fwdMinHTLC,
43✔
4409
                HtlcMaximumMsat: fwdMaxHTLC,
43✔
4410
        }
43✔
4411

43✔
4412
        // The caller of newChanAnnouncement is expected to provide the initial
43✔
4413
        // forwarding policy to be announced. If no persisted initial policy
43✔
4414
        // values are found, then we will use the default policy values in the
43✔
4415
        // channel announcement.
43✔
4416
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
43✔
4417
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
43✔
4418
                return nil, errors.Errorf("unable to generate channel "+
×
4419
                        "update announcement: %v", err)
×
4420
        }
×
4421

4422
        switch {
43✔
4423
        case ourPolicy != nil:
1✔
4424
                // If ourPolicy is non-nil, modify the default parameters of the
1✔
4425
                // ChannelUpdate.
1✔
4426
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
1✔
4427
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
1✔
4428
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
1✔
4429
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
1✔
4430
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
1✔
4431
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
1✔
4432
                chanUpdateAnn.FeeRate = uint32(
1✔
4433
                        ourPolicy.FeeProportionalMillionths,
1✔
4434
                )
1✔
4435

4436
        case storedFwdingPolicy != nil:
43✔
4437
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
43✔
4438
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
43✔
4439

4440
        default:
×
4441
                log.Infof("No channel forwarding policy specified for channel "+
×
4442
                        "announcement of ChannelID(%v). "+
×
4443
                        "Assuming default fee parameters.", chanID)
×
4444
                chanUpdateAnn.BaseFee = uint32(
×
4445
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4446
                )
×
4447
                chanUpdateAnn.FeeRate = uint32(
×
4448
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4449
                )
×
4450
        }
4451

4452
        // With the channel update announcement constructed, we'll generate a
4453
        // signature that signs a double-sha digest of the announcement.
4454
        // This'll serve to authenticate this announcement and any other future
4455
        // updates we may send.
4456
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
43✔
4457
        if err != nil {
43✔
4458
                return nil, err
×
4459
        }
×
4460
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
43✔
4461
        if err != nil {
43✔
4462
                return nil, errors.Errorf("unable to generate channel "+
×
4463
                        "update announcement signature: %v", err)
×
4464
        }
×
4465
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
43✔
4466
        if err != nil {
43✔
4467
                return nil, errors.Errorf("unable to generate channel "+
×
4468
                        "update announcement signature: %v", err)
×
4469
        }
×
4470

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

4495
        // Finally, we'll generate the announcement proof which we'll use to
4496
        // provide the other side with the necessary signatures required to
4497
        // allow them to reconstruct the full channel announcement.
4498
        proof := &lnwire.AnnounceSignatures1{
43✔
4499
                ChannelID:      chanID,
43✔
4500
                ShortChannelID: shortChanID,
43✔
4501
        }
43✔
4502
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
43✔
4503
        if err != nil {
43✔
4504
                return nil, err
×
4505
        }
×
4506
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
43✔
4507
        if err != nil {
43✔
4508
                return nil, err
×
4509
        }
×
4510

4511
        return &chanAnnouncement{
43✔
4512
                chanAnn:       chanAnn,
43✔
4513
                chanUpdateAnn: chanUpdateAnn,
43✔
4514
                chanProof:     proof,
43✔
4515
        }, nil
43✔
4516
}
4517

4518
// announceChannel announces a newly created channel to the rest of the network
4519
// by crafting the two authenticated announcements required for the peers on
4520
// the network to recognize the legitimacy of the channel. The crafted
4521
// announcements are then sent to the channel router to handle broadcasting to
4522
// the network during its next trickle.
4523
// This method is synchronous and will return when all the network requests
4524
// finish, either successfully or with an error.
4525
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4526
        localFundingKey *keychain.KeyDescriptor,
4527
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4528
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
17✔
4529

17✔
4530
        // First, we'll create the batch of announcements to be sent upon
17✔
4531
        // initial channel creation. This includes the channel announcement
17✔
4532
        // itself, the channel update announcement, and our half of the channel
17✔
4533
        // proof needed to fully authenticate the channel.
17✔
4534
        //
17✔
4535
        // We can pass in zeroes for the min and max htlc policy, because we
17✔
4536
        // only use the channel announcement message from the returned struct.
17✔
4537
        ann, err := f.newChanAnnouncement(
17✔
4538
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
17✔
4539
                shortChanID, chanID, 0, 0, nil, chanType,
17✔
4540
        )
17✔
4541
        if err != nil {
17✔
4542
                log.Errorf("can't generate channel announcement: %v", err)
×
4543
                return err
×
4544
        }
×
4545

4546
        // We only send the channel proof announcement and the node announcement
4547
        // because addToGraph previously sent the ChannelAnnouncement and
4548
        // the ChannelUpdate announcement messages. The channel proof and node
4549
        // announcements are broadcast to the greater network.
4550
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
17✔
4551
        select {
17✔
4552
        case err := <-errChan:
17✔
4553
                if err != nil {
18✔
4554
                        if graph.IsError(err, graph.ErrOutdated,
1✔
4555
                                graph.ErrIgnored) {
1✔
4556

×
4557
                                log.Debugf("Graph rejected "+
×
4558
                                        "AnnounceSignatures: %v", err)
×
4559
                        } else {
1✔
4560
                                log.Errorf("Unable to send channel "+
1✔
4561
                                        "proof: %v", err)
1✔
4562
                                return err
1✔
4563
                        }
1✔
4564
                }
4565

4566
        case <-f.quit:
×
4567
                return ErrFundingManagerShuttingDown
×
4568
        }
4569

4570
        // Now that the channel is announced to the network, we will also
4571
        // obtain and send a node announcement. This is done since a node
4572
        // announcement is only accepted after a channel is known for that
4573
        // particular node, and this might be our first channel.
4574
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
17✔
4575
        if err != nil {
17✔
4576
                log.Errorf("can't generate node announcement: %v", err)
×
4577
                return err
×
4578
        }
×
4579

4580
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
17✔
4581
        select {
17✔
4582
        case err := <-errChan:
17✔
4583
                if err != nil {
18✔
4584
                        if graph.IsError(err, graph.ErrOutdated,
1✔
4585
                                graph.ErrIgnored) {
2✔
4586

1✔
4587
                                log.Debugf("Graph rejected "+
1✔
4588
                                        "NodeAnnouncement: %v", err)
1✔
4589
                        } else {
1✔
4590
                                log.Errorf("Unable to send node "+
×
4591
                                        "announcement: %v", err)
×
4592
                                return err
×
4593
                        }
×
4594
                }
4595

4596
        case <-f.quit:
×
4597
                return ErrFundingManagerShuttingDown
×
4598
        }
4599

4600
        return nil
17✔
4601
}
4602

4603
// sendChanUpdate sends a ChannelUpdate to the gossiper which is as a
4604
// consequence sent to the peer.
4605
//
4606
// TODO(ziggie): Refactor the gossip msges so that not always all msges have
4607
// to be created but only the ones which are needed.
4608
func (f *Manager) sendChanUpdate(completeChan *channeldb.OpenChannel,
4609
        shortChanID *lnwire.ShortChannelID,
4610
        ourPolicy *models.ChannelEdgePolicy) error {
3✔
4611

3✔
4612
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
3✔
4613

3✔
4614
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
3✔
4615

3✔
4616
        ann, err := f.newChanAnnouncement(
3✔
4617
                f.cfg.IDKey, completeChan.IdentityPub,
3✔
4618
                &completeChan.LocalChanCfg.MultiSigKey,
3✔
4619
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
3✔
4620
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
3✔
4621
                completeChan.ChanType,
3✔
4622
        )
3✔
4623
        if err != nil {
3✔
NEW
4624
                return fmt.Errorf("error generating channel "+
×
NEW
4625
                        "announcement: %v", err)
×
NEW
4626
        }
×
4627

4628
        errChan := f.cfg.SendAnnouncement(ann.chanUpdateAnn)
3✔
4629
        select {
3✔
4630
        case err := <-errChan:
3✔
4631
                if err != nil {
4✔
4632
                        if graph.IsError(err, graph.ErrOutdated,
1✔
4633
                                graph.ErrIgnored) {
2✔
4634

1✔
4635
                                log.Debugf("Graph rejected "+
1✔
4636
                                        "ChannelUpdate: %v", err)
1✔
4637
                        } else {
1✔
NEW
4638
                                return fmt.Errorf("error sending channel "+
×
NEW
4639
                                        "update: %v", err)
×
NEW
4640
                        }
×
4641
                }
NEW
4642
        case <-f.quit:
×
NEW
4643
                return ErrFundingManagerShuttingDown
×
4644
        }
4645

4646
        return nil
3✔
4647
}
4648

4649
// InitFundingWorkflow sends a message to the funding manager instructing it
4650
// to initiate a single funder workflow with the source peer.
4651
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
57✔
4652
        f.fundingRequests <- msg
57✔
4653
}
57✔
4654

4655
// getUpfrontShutdownScript takes a user provided script and a getScript
4656
// function which can be used to generate an upfront shutdown script. If our
4657
// peer does not support the feature, this function will error if a non-zero
4658
// script was provided by the user, and return an empty script otherwise. If
4659
// our peer does support the feature, we will return the user provided script
4660
// if non-zero, or a freshly generated script if our node is configured to set
4661
// upfront shutdown scripts automatically.
4662
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4663
        script lnwire.DeliveryAddress,
4664
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4665
        error) {
109✔
4666

109✔
4667
        // Check whether the remote peer supports upfront shutdown scripts.
109✔
4668
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
109✔
4669
                lnwire.UpfrontShutdownScriptOptional,
109✔
4670
        )
109✔
4671

109✔
4672
        // If the peer does not support upfront shutdown scripts, and one has been
109✔
4673
        // provided, return an error because the feature is not supported.
109✔
4674
        if !remoteUpfrontShutdown && len(script) != 0 {
110✔
4675
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4676
        }
1✔
4677

4678
        // If the peer does not support upfront shutdown, return an empty address.
4679
        if !remoteUpfrontShutdown {
211✔
4680
                return nil, nil
103✔
4681
        }
103✔
4682

4683
        // If the user has provided an script and the peer supports the feature,
4684
        // return it. Note that user set scripts override the enable upfront
4685
        // shutdown flag.
4686
        if len(script) > 0 {
8✔
4687
                return script, nil
3✔
4688
        }
3✔
4689

4690
        // If we do not have setting of upfront shutdown script enabled, return
4691
        // an empty script.
4692
        if !enableUpfrontShutdown {
5✔
4693
                return nil, nil
2✔
4694
        }
2✔
4695

4696
        // We can safely send a taproot address iff, both sides have negotiated
4697
        // the shutdown-any-segwit feature.
4698
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4699
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4700

1✔
4701
        return getScript(taprootOK)
1✔
4702
}
4703

4704
// handleInitFundingMsg creates a channel reservation within the daemon's
4705
// wallet, then sends a funding request to the remote peer kicking off the
4706
// funding workflow.
4707
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
57✔
4708
        var (
57✔
4709
                peerKey        = msg.Peer.IdentityKey()
57✔
4710
                localAmt       = msg.LocalFundingAmt
57✔
4711
                baseFee        = msg.BaseFee
57✔
4712
                feeRate        = msg.FeeRate
57✔
4713
                minHtlcIn      = msg.MinHtlcIn
57✔
4714
                remoteCsvDelay = msg.RemoteCsvDelay
57✔
4715
                maxValue       = msg.MaxValueInFlight
57✔
4716
                maxHtlcs       = msg.MaxHtlcs
57✔
4717
                maxCSV         = msg.MaxLocalCsv
57✔
4718
                chanReserve    = msg.RemoteChanReserve
57✔
4719
                outpoints      = msg.Outpoints
57✔
4720
        )
57✔
4721

57✔
4722
        // If no maximum CSV delay was set for this channel, we use our default
57✔
4723
        // value.
57✔
4724
        if maxCSV == 0 {
114✔
4725
                maxCSV = f.cfg.MaxLocalCSVDelay
57✔
4726
        }
57✔
4727

4728
        log.Infof("Initiating fundingRequest(local_amt=%v "+
57✔
4729
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
57✔
4730
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
57✔
4731
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
57✔
4732

57✔
4733
        // We set the channel flags to indicate whether we want this channel to
57✔
4734
        // be announced to the network.
57✔
4735
        var channelFlags lnwire.FundingFlag
57✔
4736
        if !msg.Private {
109✔
4737
                // This channel will be announced.
52✔
4738
                channelFlags = lnwire.FFAnnounceChannel
52✔
4739
        }
52✔
4740

4741
        // If the caller specified their own channel ID, then we'll use that.
4742
        // Otherwise we'll generate a fresh one as normal.  This will be used
4743
        // to track this reservation throughout its lifetime.
4744
        var chanID PendingChanID
57✔
4745
        if msg.PendingChanID == zeroID {
114✔
4746
                chanID = f.nextPendingChanID()
57✔
4747
        } else {
58✔
4748
                // If the user specified their own pending channel ID, then
1✔
4749
                // we'll ensure it doesn't collide with any existing pending
1✔
4750
                // channel ID.
1✔
4751
                chanID = msg.PendingChanID
1✔
4752
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
1✔
4753
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4754
                                "already present", chanID[:])
×
4755
                        return
×
4756
                }
×
4757
        }
4758

4759
        // Check whether the peer supports upfront shutdown, and get an address
4760
        // which should be used (either a user specified address or a new
4761
        // address from the wallet if our node is configured to set shutdown
4762
        // address by default).
4763
        shutdown, err := getUpfrontShutdownScript(
57✔
4764
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
57✔
4765
                f.selectShutdownScript,
57✔
4766
        )
57✔
4767
        if err != nil {
57✔
4768
                msg.Err <- err
×
4769
                return
×
4770
        }
×
4771

4772
        // Initialize a funding reservation with the local wallet. If the
4773
        // wallet doesn't have enough funds to commit to this channel, then the
4774
        // request will fail, and be aborted.
4775
        //
4776
        // Before we init the channel, we'll also check to see what commitment
4777
        // format we can use with this peer. This is dependent on *both* us and
4778
        // the remote peer are signaling the proper feature bit.
4779
        chanType, commitType, err := negotiateCommitmentType(
57✔
4780
                msg.ChannelType, msg.Peer.LocalFeatures(),
57✔
4781
                msg.Peer.RemoteFeatures(),
57✔
4782
        )
57✔
4783
        if err != nil {
58✔
4784
                log.Errorf("channel type negotiation failed: %v", err)
1✔
4785
                msg.Err <- err
1✔
4786
                return
1✔
4787
        }
1✔
4788

4789
        var (
57✔
4790
                zeroConf bool
57✔
4791
                scid     bool
57✔
4792
        )
57✔
4793

57✔
4794
        if chanType != nil {
62✔
4795
                // Check if the returned chanType includes either the zero-conf
5✔
4796
                // or scid-alias bits.
5✔
4797
                featureVec := lnwire.RawFeatureVector(*chanType)
5✔
4798
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
5✔
4799
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
5✔
4800

5✔
4801
                // The option-scid-alias channel type for a public channel is
5✔
4802
                // disallowed.
5✔
4803
                if scid && !msg.Private {
5✔
4804
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4805
                                "public channel")
×
4806
                        log.Error(err)
×
4807
                        msg.Err <- err
×
4808

×
4809
                        return
×
4810
                }
×
4811
        }
4812

4813
        // First, we'll query the fee estimator for a fee that should get the
4814
        // commitment transaction confirmed by the next few blocks (conf target
4815
        // of 3). We target the near blocks here to ensure that we'll be able
4816
        // to execute a timely unilateral channel closure if needed.
4817
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
57✔
4818
        if err != nil {
57✔
4819
                msg.Err <- err
×
4820
                return
×
4821
        }
×
4822

4823
        // For anchor channels cap the initial commit fee rate at our defined
4824
        // maximum.
4825
        if commitType.HasAnchors() &&
57✔
4826
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
62✔
4827

5✔
4828
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
5✔
4829
        }
5✔
4830

4831
        var scidFeatureVal bool
57✔
4832
        if hasFeatures(
57✔
4833
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
57✔
4834
                lnwire.ScidAliasOptional,
57✔
4835
        ) {
61✔
4836

4✔
4837
                scidFeatureVal = true
4✔
4838
        }
4✔
4839

4840
        // At this point, if we have an AuxFundingController active, we'll check
4841
        // to see if we have a special tapscript root to use in our MuSig2
4842
        // funding output.
4843
        tapscriptRoot, err := fn.MapOptionZ(
57✔
4844
                f.cfg.AuxFundingController,
57✔
4845
                func(c AuxFundingController) AuxTapscriptResult {
57✔
4846
                        return c.DeriveTapscriptRoot(chanID)
×
4847
                },
×
4848
        ).Unpack()
4849
        if err != nil {
57✔
4850
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4851
                log.Error(err)
×
4852
                msg.Err <- err
×
4853

×
4854
                return
×
4855
        }
×
4856

4857
        req := &lnwallet.InitFundingReserveMsg{
57✔
4858
                ChainHash:         &msg.ChainHash,
57✔
4859
                PendingChanID:     chanID,
57✔
4860
                NodeID:            peerKey,
57✔
4861
                NodeAddr:          msg.Peer.Address(),
57✔
4862
                SubtractFees:      msg.SubtractFees,
57✔
4863
                LocalFundingAmt:   localAmt,
57✔
4864
                RemoteFundingAmt:  0,
57✔
4865
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
57✔
4866
                MinFundAmt:        msg.MinFundAmt,
57✔
4867
                RemoteChanReserve: chanReserve,
57✔
4868
                Outpoints:         outpoints,
57✔
4869
                CommitFeePerKw:    commitFeePerKw,
57✔
4870
                FundingFeePerKw:   msg.FundingFeePerKw,
57✔
4871
                PushMSat:          msg.PushAmt,
57✔
4872
                Flags:             channelFlags,
57✔
4873
                MinConfs:          msg.MinConfs,
57✔
4874
                CommitType:        commitType,
57✔
4875
                ChanFunder:        msg.ChanFunder,
57✔
4876
                // Unconfirmed Utxos which are marked by the sweeper subsystem
57✔
4877
                // are excluded from the coin selection because they are not
57✔
4878
                // final and can be RBFed by the sweeper subsystem.
57✔
4879
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
115✔
4880
                        // Utxos with at least 1 confirmation are safe to use
58✔
4881
                        // for channel openings because they don't bare the risk
58✔
4882
                        // of being replaced (BIP 125 RBF).
58✔
4883
                        if u.Confirmations > 0 {
59✔
4884
                                return true
1✔
4885
                        }
1✔
4886

4887
                        // Query the sweeper storage to make sure we don't use
4888
                        // an unconfirmed utxo still in use by the sweeper
4889
                        // subsystem.
4890
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
58✔
4891
                },
4892
                ZeroConf:         zeroConf,
4893
                OptionScidAlias:  scid,
4894
                ScidAliasFeature: scidFeatureVal,
4895
                Memo:             msg.Memo,
4896
                TapscriptRoot:    tapscriptRoot,
4897
        }
4898

4899
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
57✔
4900
        if err != nil {
58✔
4901
                msg.Err <- err
1✔
4902
                return
1✔
4903
        }
1✔
4904

4905
        if zeroConf {
60✔
4906
                // Store the alias for zero-conf channels in the underlying
3✔
4907
                // partial channel state.
3✔
4908
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
4909
                if err != nil {
3✔
4910
                        msg.Err <- err
×
4911
                        return
×
4912
                }
×
4913

4914
                reservation.AddAlias(aliasScid)
3✔
4915
        }
4916

4917
        // Set our upfront shutdown address in the existing reservation.
4918
        reservation.SetOurUpfrontShutdown(shutdown)
57✔
4919

57✔
4920
        // Now that we have successfully reserved funds for this channel in the
57✔
4921
        // wallet, we can fetch the final channel capacity. This is done at
57✔
4922
        // this point since the final capacity might change in case of
57✔
4923
        // SubtractFees=true.
57✔
4924
        capacity := reservation.Capacity()
57✔
4925

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

57✔
4929
        // If the remote CSV delay was not set in the open channel request,
57✔
4930
        // we'll use the RequiredRemoteDelay closure to compute the delay we
57✔
4931
        // require given the total amount of funds within the channel.
57✔
4932
        if remoteCsvDelay == 0 {
113✔
4933
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
56✔
4934
        }
56✔
4935

4936
        // If no minimum HTLC value was specified, use the default one.
4937
        if minHtlcIn == 0 {
113✔
4938
                minHtlcIn = f.cfg.DefaultMinHtlcIn
56✔
4939
        }
56✔
4940

4941
        // If no max value was specified, use the default one.
4942
        if maxValue == 0 {
113✔
4943
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
56✔
4944
        }
56✔
4945

4946
        if maxHtlcs == 0 {
114✔
4947
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
57✔
4948
        }
57✔
4949

4950
        // Once the reservation has been created, and indexed, queue a funding
4951
        // request to the remote peer, kicking off the funding workflow.
4952
        ourContribution := reservation.OurContribution()
57✔
4953

57✔
4954
        // Prepare the optional channel fee values from the initFundingMsg. If
57✔
4955
        // useBaseFee or useFeeRate are false the client did not provide fee
57✔
4956
        // values hence we assume default fee settings from the config.
57✔
4957
        forwardingPolicy := f.defaultForwardingPolicy(
57✔
4958
                ourContribution.ChannelStateBounds,
57✔
4959
        )
57✔
4960
        if baseFee != nil {
59✔
4961
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
2✔
4962
        }
2✔
4963

4964
        if feeRate != nil {
59✔
4965
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
2✔
4966
        }
2✔
4967

4968
        // Fetch our dust limit which is part of the default channel
4969
        // constraints, and log it.
4970
        ourDustLimit := ourContribution.DustLimit
57✔
4971

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

57✔
4974
        // If the channel reserve is not specified, then we calculate an
57✔
4975
        // appropriate amount here.
57✔
4976
        if chanReserve == 0 {
110✔
4977
                chanReserve = f.cfg.RequiredRemoteChanReserve(
53✔
4978
                        capacity, ourDustLimit,
53✔
4979
                )
53✔
4980
        }
53✔
4981

4982
        // If a pending channel map for this peer isn't already created, then
4983
        // we create one, ultimately allowing us to track this pending
4984
        // reservation within the target peer.
4985
        peerIDKey := newSerializedKey(peerKey)
57✔
4986
        f.resMtx.Lock()
57✔
4987
        if _, ok := f.activeReservations[peerIDKey]; !ok {
107✔
4988
                f.activeReservations[peerIDKey] = make(pendingChannels)
50✔
4989
        }
50✔
4990

4991
        resCtx := &reservationWithCtx{
57✔
4992
                chanAmt:           capacity,
57✔
4993
                forwardingPolicy:  *forwardingPolicy,
57✔
4994
                remoteCsvDelay:    remoteCsvDelay,
57✔
4995
                remoteMinHtlc:     minHtlcIn,
57✔
4996
                remoteMaxValue:    maxValue,
57✔
4997
                remoteMaxHtlcs:    maxHtlcs,
57✔
4998
                remoteChanReserve: chanReserve,
57✔
4999
                maxLocalCsv:       maxCSV,
57✔
5000
                channelType:       chanType,
57✔
5001
                reservation:       reservation,
57✔
5002
                peer:              msg.Peer,
57✔
5003
                updates:           msg.Updates,
57✔
5004
                err:               msg.Err,
57✔
5005
        }
57✔
5006
        f.activeReservations[peerIDKey][chanID] = resCtx
57✔
5007
        f.resMtx.Unlock()
57✔
5008

57✔
5009
        // Update the timestamp once the InitFundingMsg has been handled.
57✔
5010
        defer resCtx.updateTimestamp()
57✔
5011

57✔
5012
        // Check the sanity of the selected channel constraints.
57✔
5013
        bounds := &channeldb.ChannelStateBounds{
57✔
5014
                ChanReserve:      chanReserve,
57✔
5015
                MaxPendingAmount: maxValue,
57✔
5016
                MinHTLC:          minHtlcIn,
57✔
5017
                MaxAcceptedHtlcs: maxHtlcs,
57✔
5018
        }
57✔
5019
        commitParams := &channeldb.CommitmentParams{
57✔
5020
                DustLimit: ourDustLimit,
57✔
5021
                CsvDelay:  remoteCsvDelay,
57✔
5022
        }
57✔
5023
        err = lnwallet.VerifyConstraints(
57✔
5024
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
57✔
5025
        )
57✔
5026
        if err != nil {
59✔
5027
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
2✔
5028
                if reserveErr != nil {
2✔
5029
                        log.Errorf("unable to cancel reservation: %v",
×
5030
                                reserveErr)
×
5031
                }
×
5032

5033
                msg.Err <- err
2✔
5034
                return
2✔
5035
        }
5036

5037
        // When opening a script enforced channel lease, include the required
5038
        // expiry TLV record in our proposal.
5039
        var leaseExpiry *lnwire.LeaseExpiry
55✔
5040
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
56✔
5041
                leaseExpiry = new(lnwire.LeaseExpiry)
1✔
5042
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
1✔
5043
        }
1✔
5044

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

55✔
5048
        reservation.SetState(lnwallet.SentOpenChannel)
55✔
5049

55✔
5050
        fundingOpen := lnwire.OpenChannel{
55✔
5051
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
55✔
5052
                PendingChannelID:      chanID,
55✔
5053
                FundingAmount:         capacity,
55✔
5054
                PushAmount:            msg.PushAmt,
55✔
5055
                DustLimit:             ourDustLimit,
55✔
5056
                MaxValueInFlight:      maxValue,
55✔
5057
                ChannelReserve:        chanReserve,
55✔
5058
                HtlcMinimum:           minHtlcIn,
55✔
5059
                FeePerKiloWeight:      uint32(commitFeePerKw),
55✔
5060
                CsvDelay:              remoteCsvDelay,
55✔
5061
                MaxAcceptedHTLCs:      maxHtlcs,
55✔
5062
                FundingKey:            ourContribution.MultiSigKey.PubKey,
55✔
5063
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
55✔
5064
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
55✔
5065
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
55✔
5066
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
55✔
5067
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
55✔
5068
                ChannelFlags:          channelFlags,
55✔
5069
                UpfrontShutdownScript: shutdown,
55✔
5070
                ChannelType:           chanType,
55✔
5071
                LeaseExpiry:           leaseExpiry,
55✔
5072
        }
55✔
5073

55✔
5074
        if commitType.IsTaproot() {
58✔
5075
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
3✔
5076
                        ourContribution.LocalNonce.PubNonce,
3✔
5077
                )
3✔
5078
        }
3✔
5079

5080
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
55✔
5081
                e := fmt.Errorf("unable to send funding request message: %w",
×
5082
                        err)
×
5083
                log.Errorf(e.Error())
×
5084

×
5085
                // Since we were unable to send the initial message to the peer
×
5086
                // and start the funding flow, we'll cancel this reservation.
×
5087
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5088
                if err != nil {
×
5089
                        log.Errorf("unable to cancel reservation: %v", err)
×
5090
                }
×
5091

5092
                msg.Err <- e
×
5093
                return
×
5094
        }
5095
}
5096

5097
// handleWarningMsg processes the warning which was received from remote peer.
5098
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
42✔
5099
        log.Warnf("received warning message from peer %x: %v",
42✔
5100
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
42✔
5101
}
42✔
5102

5103
// handleErrorMsg processes the error which was received from remote peer,
5104
// depending on the type of error we should do different clean up steps and
5105
// inform the user about it.
5106
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
1✔
5107
        chanID := msg.ChanID
1✔
5108
        peerKey := peer.IdentityKey()
1✔
5109

1✔
5110
        // First, we'll attempt to retrieve and cancel the funding workflow
1✔
5111
        // that this error was tied to. If we're unable to do so, then we'll
1✔
5112
        // exit early as this was an unwarranted error.
1✔
5113
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
1✔
5114
        if err != nil {
1✔
5115
                log.Warnf("Received error for non-existent funding "+
×
5116
                        "flow: %v (%v)", err, msg.Error())
×
5117
                return
×
5118
        }
×
5119

5120
        // If we did indeed find the funding workflow, then we'll return the
5121
        // error back to the caller (if any), and cancel the workflow itself.
5122
        fundingErr := fmt.Errorf("received funding error from %x: %v",
1✔
5123
                peerKey.SerializeCompressed(), msg.Error(),
1✔
5124
        )
1✔
5125
        log.Errorf(fundingErr.Error())
1✔
5126

1✔
5127
        // If this was a PSBT funding flow, the remote likely timed out because
1✔
5128
        // we waited too long. Return a nice error message to the user in that
1✔
5129
        // case so the user knows what's the problem.
1✔
5130
        if resCtx.reservation.IsPsbt() {
2✔
5131
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
1✔
5132
                        fundingErr)
1✔
5133
        }
1✔
5134

5135
        resCtx.err <- fundingErr
1✔
5136
}
5137

5138
// pruneZombieReservations loops through all pending reservations and fails the
5139
// funding flow for any reservations that have not been updated since the
5140
// ReservationTimeout and are not locked waiting for the funding transaction.
5141
func (f *Manager) pruneZombieReservations() {
4✔
5142
        zombieReservations := make(pendingChannels)
4✔
5143

4✔
5144
        f.resMtx.RLock()
4✔
5145
        for _, pendingReservations := range f.activeReservations {
8✔
5146
                for pendingChanID, resCtx := range pendingReservations {
8✔
5147
                        if resCtx.isLocked() {
4✔
5148
                                continue
×
5149
                        }
5150

5151
                        // We don't want to expire PSBT funding reservations.
5152
                        // These reservations are always initiated by us and the
5153
                        // remote peer is likely going to cancel them after some
5154
                        // idle time anyway. So no need for us to also prune
5155
                        // them.
5156
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
4✔
5157
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
4✔
5158
                        if !resCtx.reservation.IsPsbt() && isExpired {
8✔
5159
                                zombieReservations[pendingChanID] = resCtx
4✔
5160
                        }
4✔
5161
                }
5162
        }
5163
        f.resMtx.RUnlock()
4✔
5164

4✔
5165
        for pendingChanID, resCtx := range zombieReservations {
8✔
5166
                err := fmt.Errorf("reservation timed out waiting for peer "+
4✔
5167
                        "(peer_id:%x, chan_id:%x)",
4✔
5168
                        resCtx.peer.IdentityKey().SerializeCompressed(),
4✔
5169
                        pendingChanID[:])
4✔
5170
                log.Warnf(err.Error())
4✔
5171

4✔
5172
                chanID := lnwire.NewChanIDFromOutPoint(
4✔
5173
                        *resCtx.reservation.FundingOutpoint(),
4✔
5174
                )
4✔
5175

4✔
5176
                // Create channel identifier and set the channel ID.
4✔
5177
                cid := newChanIdentifier(pendingChanID)
4✔
5178
                cid.setChanID(chanID)
4✔
5179

4✔
5180
                f.failFundingFlow(resCtx.peer, cid, err)
4✔
5181
        }
4✔
5182
}
5183

5184
// cancelReservationCtx does all needed work in order to securely cancel the
5185
// reservation.
5186
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5187
        pendingChanID PendingChanID,
5188
        byRemote bool) (*reservationWithCtx, error) {
25✔
5189

25✔
5190
        log.Infof("Cancelling funding reservation for node_key=%x, "+
25✔
5191
                "chan_id=%x", peerKey.SerializeCompressed(), pendingChanID[:])
25✔
5192

25✔
5193
        peerIDKey := newSerializedKey(peerKey)
25✔
5194
        f.resMtx.Lock()
25✔
5195
        defer f.resMtx.Unlock()
25✔
5196

25✔
5197
        nodeReservations, ok := f.activeReservations[peerIDKey]
25✔
5198
        if !ok {
34✔
5199
                // No reservations for this node.
9✔
5200
                return nil, errors.Errorf("no active reservations for peer(%x)",
9✔
5201
                        peerIDKey[:])
9✔
5202
        }
9✔
5203

5204
        ctx, ok := nodeReservations[pendingChanID]
17✔
5205
        if !ok {
19✔
5206
                return nil, errors.Errorf("unknown channel (id: %x) for "+
2✔
5207
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5208
        }
2✔
5209

5210
        // If the reservation was a PSBT funding flow and it was canceled by the
5211
        // remote peer, then we need to thread through a different error message
5212
        // to the subroutine that's waiting for the user input so it can return
5213
        // a nice error message to the user.
5214
        if ctx.reservation.IsPsbt() && byRemote {
16✔
5215
                ctx.reservation.RemoteCanceled()
1✔
5216
        }
1✔
5217

5218
        if err := ctx.reservation.Cancel(); err != nil {
15✔
5219
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5220
                        err)
×
5221
        }
×
5222

5223
        delete(nodeReservations, pendingChanID)
15✔
5224

15✔
5225
        // If this was the last active reservation for this peer, delete the
15✔
5226
        // peer's entry altogether.
15✔
5227
        if len(nodeReservations) == 0 {
30✔
5228
                delete(f.activeReservations, peerIDKey)
15✔
5229
        }
15✔
5230
        return ctx, nil
15✔
5231
}
5232

5233
// deleteReservationCtx deletes the reservation uniquely identified by the
5234
// target public key of the peer, and the specified pending channel ID.
5235
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5236
        pendingChanID PendingChanID) {
55✔
5237

55✔
5238
        peerIDKey := newSerializedKey(peerKey)
55✔
5239
        f.resMtx.Lock()
55✔
5240
        defer f.resMtx.Unlock()
55✔
5241

55✔
5242
        nodeReservations, ok := f.activeReservations[peerIDKey]
55✔
5243
        if !ok {
55✔
5244
                // No reservations for this node.
×
5245
                return
×
5246
        }
×
5247
        delete(nodeReservations, pendingChanID)
55✔
5248

55✔
5249
        // If this was the last active reservation for this peer, delete the
55✔
5250
        // peer's entry altogether.
55✔
5251
        if len(nodeReservations) == 0 {
103✔
5252
                delete(f.activeReservations, peerIDKey)
48✔
5253
        }
48✔
5254
}
5255

5256
// getReservationCtx returns the reservation context for a particular pending
5257
// channel ID for a target peer.
5258
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5259
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
89✔
5260

89✔
5261
        peerIDKey := newSerializedKey(peerKey)
89✔
5262
        f.resMtx.RLock()
89✔
5263
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
89✔
5264
        f.resMtx.RUnlock()
89✔
5265

89✔
5266
        if !ok {
90✔
5267
                return nil, errors.Errorf("unknown channel (id: %x) for "+
1✔
5268
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
1✔
5269
        }
1✔
5270

5271
        return resCtx, nil
89✔
5272
}
5273

5274
// IsPendingChannel returns a boolean indicating whether the channel identified
5275
// by the pendingChanID and given peer is pending, meaning it is in the process
5276
// of being funded. After the funding transaction has been confirmed, the
5277
// channel will receive a new, permanent channel ID, and will no longer be
5278
// considered pending.
5279
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5280
        peer lnpeer.Peer) bool {
1✔
5281

1✔
5282
        peerIDKey := newSerializedKey(peer.IdentityKey())
1✔
5283
        f.resMtx.RLock()
1✔
5284
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
1✔
5285
        f.resMtx.RUnlock()
1✔
5286

1✔
5287
        return ok
1✔
5288
}
1✔
5289

5290
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
376✔
5291
        var tmp btcec.JacobianPoint
376✔
5292
        pub.AsJacobian(&tmp)
376✔
5293
        tmp.ToAffine()
376✔
5294
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
376✔
5295
}
376✔
5296

5297
// defaultForwardingPolicy returns the default forwarding policy based on the
5298
// default routing policy and our local channel constraints.
5299
func (f *Manager) defaultForwardingPolicy(
5300
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
103✔
5301

103✔
5302
        return &models.ForwardingPolicy{
103✔
5303
                MinHTLCOut:    bounds.MinHTLC,
103✔
5304
                MaxHTLC:       bounds.MaxPendingAmount,
103✔
5305
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
103✔
5306
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
103✔
5307
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
103✔
5308
        }
103✔
5309
}
103✔
5310

5311
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5312
// chanPoint in the channelOpeningStateBucket.
5313
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5314
        forwardingPolicy *models.ForwardingPolicy) error {
68✔
5315

68✔
5316
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
68✔
5317
                chanID, forwardingPolicy,
68✔
5318
        )
68✔
5319
}
68✔
5320

5321
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5322
// channel id from the database which will be applied during the channel
5323
// announcement phase.
5324
func (f *Manager) getInitialForwardingPolicy(
5325
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
95✔
5326

95✔
5327
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
95✔
5328
}
95✔
5329

5330
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5331
// the database.
5332
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
25✔
5333
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
25✔
5334
}
25✔
5335

5336
// saveChannelOpeningState saves the channelOpeningState for the provided
5337
// chanPoint to the channelOpeningStateBucket.
5338
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5339
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
93✔
5340

93✔
5341
        var outpointBytes bytes.Buffer
93✔
5342
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
93✔
5343
                return err
×
5344
        }
×
5345

5346
        // Save state and the uint64 representation of the shortChanID
5347
        // for later use.
5348
        scratch := make([]byte, 10)
93✔
5349
        byteOrder.PutUint16(scratch[:2], uint16(state))
93✔
5350
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
93✔
5351

93✔
5352
        return f.cfg.ChannelDB.SaveChannelOpeningState(
93✔
5353
                outpointBytes.Bytes(), scratch,
93✔
5354
        )
93✔
5355
}
5356

5357
// getChannelOpeningState fetches the channelOpeningState for the provided
5358
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5359
// is not found.
5360
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5361
        channelOpeningState, *lnwire.ShortChannelID, error) {
252✔
5362

252✔
5363
        var outpointBytes bytes.Buffer
252✔
5364
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
252✔
5365
                return 0, nil, err
×
5366
        }
×
5367

5368
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
252✔
5369
                outpointBytes.Bytes(),
252✔
5370
        )
252✔
5371
        if err != nil {
300✔
5372
                return 0, nil, err
48✔
5373
        }
48✔
5374

5375
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
205✔
5376
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
205✔
5377
        return state, &shortChanID, nil
205✔
5378
}
5379

5380
// deleteChannelOpeningState removes any state for chanPoint from the database.
5381
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
25✔
5382
        var outpointBytes bytes.Buffer
25✔
5383
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
25✔
5384
                return err
×
5385
        }
×
5386

5387
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
25✔
5388
                outpointBytes.Bytes(),
25✔
5389
        )
25✔
5390
}
5391

5392
// selectShutdownScript selects the shutdown script we should send to the peer.
5393
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5394
// script.
5395
func (f *Manager) selectShutdownScript(taprootOK bool,
5396
) (lnwire.DeliveryAddress, error) {
×
5397

×
5398
        addrType := lnwallet.WitnessPubKey
×
5399
        if taprootOK {
×
5400
                addrType = lnwallet.TaprootPubkey
×
5401
        }
×
5402

5403
        addr, err := f.cfg.Wallet.NewAddress(
×
5404
                addrType, false, lnwallet.DefaultAccountName,
×
5405
        )
×
5406
        if err != nil {
×
5407
                return nil, err
×
5408
        }
×
5409

5410
        return txscript.PayToAddrScript(addr)
×
5411
}
5412

5413
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5414
// and then returns the online peer.
5415
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5416
        error) {
105✔
5417

105✔
5418
        peerChan := make(chan lnpeer.Peer, 1)
105✔
5419

105✔
5420
        var peerKey [33]byte
105✔
5421
        copy(peerKey[:], peerPubkey.SerializeCompressed())
105✔
5422

105✔
5423
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
105✔
5424

105✔
5425
        var peer lnpeer.Peer
105✔
5426
        select {
105✔
5427
        case peer = <-peerChan:
104✔
5428
        case <-f.quit:
1✔
5429
                return peer, ErrFundingManagerShuttingDown
1✔
5430
        }
5431
        return peer, nil
104✔
5432
}
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