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

lightningnetwork / lnd / 17561168350

08 Sep 2025 07:01PM UTC coverage: 66.621% (-0.01%) from 66.634%
17561168350

Pull #10202

github

web-flow
Merge f11f23c6c into 6c9e0f348
Pull Request #10202: Makefile+tools: reduce LND linter docker image size by 85% from `2330 MB` to `355 MB`

136114 of 204312 relevant lines covered (66.62%)

21457.39 hits per line

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

74.31
/funding/manager.go
1
package funding
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

102
        msgBufferSize = 50
103

104
        // pendingChansLimit is the maximum number of pending channels that we
105
        // can have. After this point, pending channel opens will start to be
106
        // rejected.
107
        pendingChansLimit = 50
108
)
109

110
var (
111
        // ErrFundingManagerShuttingDown is an error returned when attempting to
112
        // process a funding request/message but the funding manager has already
113
        // been signaled to shut down.
114
        ErrFundingManagerShuttingDown = errors.New("funding manager shutting " +
115
                "down")
116

117
        // ErrConfirmationTimeout is an error returned when we as a responder
118
        // are waiting for a funding transaction to confirm, but too many
119
        // blocks pass without confirmation.
120
        ErrConfirmationTimeout = errors.New("timeout waiting for funding " +
121
                "confirmation")
122

123
        // errUpfrontShutdownScriptNotSupported is returned if an upfront
124
        // shutdown script is set for a peer that does not support the feature
125
        // bit.
126
        errUpfrontShutdownScriptNotSupported = errors.New("peer does not " +
127
                "support option upfront shutdown script")
128

129
        zeroID [32]byte
130
)
131

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

145
        chanAmt btcutil.Amount
146

147
        // forwardingPolicy is the policy provided by the initFundingMsg.
148
        forwardingPolicy models.ForwardingPolicy
149

150
        // Constraints we require for the remote.
151
        remoteCsvDelay    uint16
152
        remoteMinHtlc     lnwire.MilliSatoshi
153
        remoteMaxValue    lnwire.MilliSatoshi
154
        remoteMaxHtlcs    uint16
155
        remoteChanReserve btcutil.Amount
156

157
        // maxLocalCsv is the maximum csv we will accept from the remote.
158
        maxLocalCsv uint16
159

160
        // channelType is the explicit channel type proposed by the initiator of
161
        // the channel.
162
        channelType *lnwire.ChannelType
163

164
        updateMtx   sync.RWMutex
165
        lastUpdated time.Time
166

167
        updates chan *lnrpc.OpenStatusUpdate
168
        err     chan error
169
}
170

171
// isLocked checks the reservation's timestamp to determine whether it is
172
// locked.
173
func (r *reservationWithCtx) isLocked() bool {
6✔
174
        r.updateMtx.RLock()
6✔
175
        defer r.updateMtx.RUnlock()
6✔
176

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

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

137✔
186
        r.lastUpdated = time.Now()
137✔
187
}
137✔
188

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

198
        // TargetPubkey is the public key of the peer.
199
        TargetPubkey *btcec.PublicKey
200

201
        // ChainHash is the target genesis hash for this channel.
202
        ChainHash chainhash.Hash
203

204
        // SubtractFees set to true means that fees will be subtracted
205
        // from the LocalFundingAmt.
206
        SubtractFees bool
207

208
        // LocalFundingAmt is the size of the channel.
209
        LocalFundingAmt btcutil.Amount
210

211
        // BaseFee is the base fee charged for routing payments regardless of
212
        // the number of milli-satoshis sent.
213
        BaseFee *uint64
214

215
        // FeeRate is the fee rate in ppm (parts per million) that will be
216
        // charged proportionally based on the value of each forwarded HTLC, the
217
        // lowest possible rate is 0 with a granularity of 0.000001
218
        // (millionths).
219
        FeeRate *uint64
220

221
        // PushAmt is the amount pushed to the counterparty.
222
        PushAmt lnwire.MilliSatoshi
223

224
        // FundingFeePerKw is the fee for the funding transaction.
225
        FundingFeePerKw chainfee.SatPerKWeight
226

227
        // Private determines whether or not this channel will be private.
228
        Private bool
229

230
        // MinHtlcIn is the minimum incoming HTLC that we accept.
231
        MinHtlcIn lnwire.MilliSatoshi
232

233
        // RemoteCsvDelay is the CSV delay we require for the remote peer.
234
        RemoteCsvDelay uint16
235

236
        // RemoteChanReserve is the channel reserve we required for the remote
237
        // peer.
238
        RemoteChanReserve btcutil.Amount
239

240
        // MinConfs indicates the minimum number of confirmations that each
241
        // output selected to fund the channel should satisfy.
242
        MinConfs int32
243

244
        // ShutdownScript is an optional upfront shutdown script for the
245
        // channel. This value is optional, so may be nil.
246
        ShutdownScript lnwire.DeliveryAddress
247

248
        // MaxValueInFlight is the maximum amount of coins in MilliSatoshi
249
        // that can be pending within the channel. It only applies to the
250
        // remote party.
251
        MaxValueInFlight lnwire.MilliSatoshi
252

253
        // MaxHtlcs is the maximum number of HTLCs that the remote peer
254
        // can offer us.
255
        MaxHtlcs uint16
256

257
        // MaxLocalCsv is the maximum local csv delay we will accept from our
258
        // peer.
259
        MaxLocalCsv uint16
260

261
        // FundUpToMaxAmt is the maximum amount to try to commit to. If set, the
262
        // MinFundAmt field denotes the acceptable minimum amount to commit to,
263
        // while trying to commit as many coins as possible up to this value.
264
        FundUpToMaxAmt btcutil.Amount
265

266
        // MinFundAmt must be set iff FundUpToMaxAmt is set. It denotes the
267
        // minimum amount to commit to.
268
        MinFundAmt btcutil.Amount
269

270
        // Outpoints is a list of client-selected outpoints that should be used
271
        // for funding a channel. If LocalFundingAmt is specified then this
272
        // amount is allocated from the sum of outpoints towards funding. If
273
        // the FundUpToMaxAmt is specified the entirety of selected funds is
274
        // allocated towards channel funding.
275
        Outpoints []wire.OutPoint
276

277
        // ChanFunder is an optional channel funder that allows the caller to
278
        // control exactly how the channel funding is carried out. If not
279
        // specified, then the default chanfunding.WalletAssembler will be
280
        // used.
281
        ChanFunder chanfunding.Assembler
282

283
        // PendingChanID is not all zeroes (the default value), then this will
284
        // be the pending channel ID used for the funding flow within the wire
285
        // protocol.
286
        PendingChanID PendingChanID
287

288
        // ChannelType allows the caller to use an explicit channel type for the
289
        // funding negotiation. This type will only be observed if BOTH sides
290
        // support explicit channel type negotiation.
291
        ChannelType *lnwire.ChannelType
292

293
        // Memo is any arbitrary information we wish to store locally about the
294
        // channel that will be useful to our future selves.
295
        Memo []byte
296

297
        // Updates is a channel which updates to the opening status of the
298
        // channel are sent on.
299
        Updates chan *lnrpc.OpenStatusUpdate
300

301
        // Err is a channel which errors encountered during the funding flow are
302
        // sent on.
303
        Err chan error
304
}
305

306
// fundingMsg is sent by the ProcessFundingMsg function and packages a
307
// funding-specific lnwire.Message along with the lnpeer.Peer that sent it.
308
type fundingMsg struct {
309
        msg  lnwire.Message
310
        peer lnpeer.Peer
311
}
312

313
// pendingChannels is a map instantiated per-peer which tracks all active
314
// pending single funded channels indexed by their pending channel identifier,
315
// which is a set of 32-bytes generated via a CSPRNG.
316
type pendingChannels map[PendingChanID]*reservationWithCtx
317

318
// serializedPubKey is used within the FundingManager's activeReservations list
319
// to identify the nodes with which the FundingManager is actively working to
320
// initiate new channels.
321
type serializedPubKey [33]byte
322

323
// newSerializedKey creates a new serialized public key from an instance of a
324
// live pubkey object.
325
func newSerializedKey(pubKey *btcec.PublicKey) serializedPubKey {
383✔
326
        var s serializedPubKey
383✔
327
        copy(s[:], pubKey.SerializeCompressed())
383✔
328
        return s
383✔
329
}
383✔
330

331
// DevConfig specifies configs used for integration test only.
332
type DevConfig struct {
333
        // ProcessChannelReadyWait is the duration to sleep before processing
334
        // remote node's channel ready message once the channel as been marked
335
        // as `channelReadySent`.
336
        ProcessChannelReadyWait time.Duration
337

338
        // MaxWaitNumBlocksFundingConf is the maximum number of blocks to wait
339
        // for the funding transaction to be confirmed before forgetting
340
        // channels that aren't initiated by us.
341
        MaxWaitNumBlocksFundingConf uint32
342
}
343

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

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

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

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

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

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

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

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

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

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

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

398
        // CurrentNodeAnnouncement should return the latest, fully signed node
399
        // announcement from the backing Lightning Network node with a fresh
400
        // timestamp.
401
        CurrentNodeAnnouncement func() (lnwire.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, *btcec.PublicKey)
514

515
        // OpenChannelPredicate is a predicate on the lnwire.OpenChannel message
516
        // and on the requesting node's public key that returns a bool which
517
        // tells the funding manager whether or not to accept the channel.
518
        OpenChannelPredicate chanacceptor.ChannelAcceptor
519

520
        // NotifyPendingOpenChannelEvent informs the ChannelNotifier when
521
        // channels enter a pending state.
522
        NotifyPendingOpenChannelEvent func(wire.OutPoint,
523
                *channeldb.OpenChannel, *btcec.PublicKey)
524

525
        // NotifyFundingTimeout informs the ChannelNotifier when a pending-open
526
        // channel times out because the funding transaction hasn't confirmed.
527
        // This is only called for the fundee and only if the channel is
528
        // zero-conf.
529
        NotifyFundingTimeout func(wire.OutPoint, *btcec.PublicKey)
530

531
        // EnableUpfrontShutdown specifies whether the upfront shutdown script
532
        // is enabled.
533
        EnableUpfrontShutdown bool
534

535
        // MaxAnchorsCommitFeeRate is the max commitment fee rate we'll use as
536
        // the initiator for channels of the anchor type.
537
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
538

539
        // DeleteAliasEdge allows the Manager to delete an alias channel edge
540
        // from the graph. It also returns our local to-be-deleted policy.
541
        DeleteAliasEdge func(scid lnwire.ShortChannelID) (
542
                *models.ChannelEdgePolicy, error)
543

544
        // AliasManager is an implementation of the aliasHandler interface that
545
        // abstracts away the handling of many alias functions.
546
        AliasManager aliasHandler
547

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

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

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

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

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

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

586
        // cfg is a copy of the configuration struct that the FundingManager
587
        // was initialized with.
588
        cfg *Config
589

590
        // chanIDKey is a cryptographically random key that's used to generate
591
        // temporary channel ID's.
592
        chanIDKey [32]byte
593

594
        // chanIDNonce is a nonce that's incremented for each new funding
595
        // reservation created.
596
        chanIDNonce atomic.Uint64
597

598
        // nonceMtx is a mutex that guards the pendingMusigNonces.
599
        nonceMtx sync.RWMutex
600

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

612
        // activeReservations is a map which houses the state of all pending
613
        // funding workflows.
614
        activeReservations map[serializedPubKey]pendingChannels
615

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

623
        // resMtx guards both of the maps above to ensure that all access is
624
        // goroutine safe.
625
        resMtx sync.RWMutex
626

627
        // fundingMsgs is a channel that relays fundingMsg structs from
628
        // external sub-systems using the ProcessFundingMsg call.
629
        fundingMsgs chan *fundingMsg
630

631
        // fundingRequests is a channel used to receive channel initiation
632
        // requests from a local subsystem within the daemon.
633
        fundingRequests chan *InitFundingMsg
634

635
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
636

637
        handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
638

639
        quit chan struct{}
640
        wg   sync.WaitGroup
641
}
642

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

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

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

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

666
func (c channelOpeningState) String() string {
3✔
667
        switch c {
3✔
668
        case markedOpen:
3✔
669
                return "markedOpen"
3✔
670
        case channelReadySent:
3✔
671
                return "channelReadySent"
3✔
672
        case addedToGraph:
3✔
673
                return "addedToGraph"
3✔
674
        default:
×
675
                return "unknown"
×
676
        }
677
}
678

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

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

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

733
        for _, channel := range allChannels {
122✔
734
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
12✔
735

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

4✔
745
                        f.localDiscoverySignals.Store(
4✔
746
                                chanID, make(chan struct{}),
4✔
747
                        )
4✔
748

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

4✔
757
                                f.rebroadcastFundingTx(channel)
4✔
758
                        }
4✔
759
                } else if channel.ChanType.IsSingleFunder() &&
11✔
760
                        channel.ChanType.HasFundingTx() &&
11✔
761
                        channel.IsZeroConf() && channel.IsInitiator &&
11✔
762
                        !channel.ZeroConfConfirmed() {
13✔
763

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

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

778
        f.wg.Add(1) // TODO(roasbeef): tune
110✔
779
        go f.reservationCoordinator()
110✔
780

110✔
781
        return nil
110✔
782
}
783

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

106✔
791
                close(f.quit)
106✔
792
                f.wg.Wait()
106✔
793
        })
106✔
794

795
        return nil
107✔
796
}
797

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

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

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

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

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

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

59✔
838
        var nonceBytes [8]byte
59✔
839
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
59✔
840

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

59✔
851
        return nextChanID
59✔
852
}
59✔
853

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

3✔
860
        f.resMtx.Lock()
3✔
861
        defer f.resMtx.Unlock()
3✔
862

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

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

881
                resCtx.err <- fmt.Errorf("peer disconnected")
×
882
                delete(nodeReservations, pendingID)
×
883
        }
884

885
        // Finally, we'll delete the node itself from the set of reservations.
886
        delete(f.activeReservations, nodePub)
×
887
}
888

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

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

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

913
// newChanIdentifier creates a new chanIdentifier.
914
func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
148✔
915
        return &chanIdentifier{
148✔
916
                tempChanID: tempChanID,
148✔
917
        }
148✔
918
}
148✔
919

920
// setChanID updates the `chanIdentifier` with the active channel ID.
921
func (c *chanIdentifier) setChanID(chanID lnwire.ChannelID) {
91✔
922
        c.chanID = chanID
91✔
923
        c.chanIDSet = true
91✔
924
}
91✔
925

926
// hasChanID returns true if the active channel ID has been set.
927
func (c *chanIdentifier) hasChanID() bool {
25✔
928
        return c.chanIDSet
25✔
929
}
25✔
930

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

25✔
941
        log.Debugf("Failing funding flow for pending_id=%v: %v",
25✔
942
                cid.tempChanID, fundingErr)
25✔
943

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

957
        ctx, err := f.cancelReservationCtx(
25✔
958
                peer.IdentityKey(), cid.tempChanID, false,
25✔
959
        )
25✔
960
        if err != nil {
38✔
961
                log.Errorf("unable to cancel reservation: %v", err)
13✔
962
        }
13✔
963

964
        // In case the case where the reservation existed, send the funding
965
        // error on the error channel.
966
        if ctx != nil {
40✔
967
                ctx.err <- fundingErr
15✔
968
        }
15✔
969

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

983
        // For all other error types we just send a generic error.
984
        default:
15✔
985
                msg = lnwire.ErrorData("funding failed due to internal error")
15✔
986
        }
987

988
        errMsg := &lnwire.Error{
25✔
989
                ChanID: cid.tempChanID,
25✔
990
                Data:   msg,
25✔
991
        }
25✔
992

25✔
993
        log.Debugf("Sending funding error to peer (%x): %v",
25✔
994
                peer.IdentityKey().SerializeCompressed(),
25✔
995
                lnutils.SpewLogClosure(errMsg))
25✔
996

25✔
997
        if err := peer.SendMessage(false, errMsg); err != nil {
26✔
998
                log.Errorf("unable to send error message to peer %v", err)
1✔
999
        }
1✔
1000
}
1001

1002
// sendWarning sends a new warning message to the target peer, targeting the
1003
// specified cid with the passed funding error.
1004
func (f *Manager) sendWarning(peer lnpeer.Peer, cid *chanIdentifier,
1005
        fundingErr error) {
×
1006

×
1007
        msg := fundingErr.Error()
×
1008

×
1009
        errMsg := &lnwire.Warning{
×
1010
                ChanID: cid.tempChanID,
×
1011
                Data:   lnwire.WarningData(msg),
×
1012
        }
×
1013

×
1014
        log.Debugf("Sending funding warning to peer (%x): %v",
×
1015
                peer.IdentityKey().SerializeCompressed(),
×
1016
                lnutils.SpewLogClosure(errMsg),
×
1017
        )
×
1018

×
1019
        if err := peer.SendMessage(false, errMsg); err != nil {
×
1020
                log.Errorf("unable to send error message to peer %v", err)
×
1021
        }
×
1022
}
1023

1024
// reservationCoordinator is the primary goroutine tasked with progressing the
1025
// funding workflow between the wallet, and any outside peers or local callers.
1026
//
1027
// NOTE: This MUST be run as a goroutine.
1028
func (f *Manager) reservationCoordinator() {
110✔
1029
        defer f.wg.Done()
110✔
1030

110✔
1031
        zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
110✔
1032
        defer zombieSweepTicker.Stop()
110✔
1033

110✔
1034
        for {
486✔
1035
                select {
376✔
1036
                case fmsg := <-f.fundingMsgs:
213✔
1037
                        switch msg := fmsg.msg.(type) {
213✔
1038
                        case *lnwire.OpenChannel:
57✔
1039
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
57✔
1040

1041
                        case *lnwire.AcceptChannel:
35✔
1042
                                f.funderProcessAcceptChannel(fmsg.peer, msg)
35✔
1043

1044
                        case *lnwire.FundingCreated:
30✔
1045
                                f.fundeeProcessFundingCreated(fmsg.peer, msg)
30✔
1046

1047
                        case *lnwire.FundingSigned:
30✔
1048
                                f.funderProcessFundingSigned(fmsg.peer, msg)
30✔
1049

1050
                        case *lnwire.ChannelReady:
31✔
1051
                                f.wg.Add(1)
31✔
1052
                                go f.handleChannelReady(fmsg.peer, msg)
31✔
1053

1054
                        case *lnwire.Warning:
42✔
1055
                                f.handleWarningMsg(fmsg.peer, msg)
42✔
1056

1057
                        case *lnwire.Error:
3✔
1058
                                f.handleErrorMsg(fmsg.peer, msg)
3✔
1059
                        }
1060
                case req := <-f.fundingRequests:
59✔
1061
                        f.handleInitFundingMsg(req)
59✔
1062

1063
                case <-zombieSweepTicker.C:
3✔
1064
                        f.pruneZombieReservations()
3✔
1065

1066
                case <-f.quit:
106✔
1067
                        return
106✔
1068
                }
1069
        }
1070
}
1071

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

66✔
1084
        defer f.wg.Done()
66✔
1085

66✔
1086
        // If the channel is still pending we must wait for the funding
66✔
1087
        // transaction to confirm.
66✔
1088
        if channel.IsPending {
124✔
1089
                err := f.advancePendingChannelState(channel, pendingChanID)
58✔
1090
                if err != nil {
82✔
1091
                        log.Errorf("Unable to advance pending state of "+
24✔
1092
                                "ChannelPoint(%v): %v",
24✔
1093
                                channel.FundingOutpoint, err)
24✔
1094
                        return
24✔
1095
                }
24✔
1096
        }
1097

1098
        var chanOpts []lnwallet.ChannelOpt
45✔
1099
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
87✔
1100
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
42✔
1101
        })
42✔
1102
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
87✔
1103
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
42✔
1104
        })
42✔
1105
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
45✔
1106
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
1107
        })
×
1108

1109
        // We create the state-machine object which wraps the database state.
1110
        lnChannel, err := lnwallet.NewLightningChannel(
45✔
1111
                nil, channel, nil, chanOpts...,
45✔
1112
        )
45✔
1113
        if err != nil {
45✔
1114
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1115
                        channel.FundingOutpoint, err)
×
1116
                return
×
1117
        }
×
1118

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

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

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

125✔
1167
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
125✔
1168
        log.Debugf("Channel(%v) with ShortChanID %v has opening state %v",
125✔
1169
                chanID, shortChanID, channelState)
125✔
1170

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

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

1194
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
37✔
1195
                        "sent ChannelReady", chanID, shortChanID)
37✔
1196

37✔
1197
                return nil
37✔
1198

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

1212
                if !received {
100✔
1213
                        // We haven't received ChannelReady, so we'll continue
38✔
1214
                        // to the next iteration of the loop after sleeping for
38✔
1215
                        // checkPeerChannelReadyInterval.
38✔
1216
                        select {
38✔
1217
                        case <-time.After(checkPeerChannelReadyInterval):
26✔
1218
                        case <-f.quit:
15✔
1219
                                return ErrFundingManagerShuttingDown
15✔
1220
                        }
1221

1222
                        return nil
26✔
1223
                }
1224

1225
                return f.handleChannelReadyReceived(
27✔
1226
                        channel, shortChanID, pendingChanID, updateChan,
27✔
1227
                )
27✔
1228

1229
        // The channel was added to the Router's topology, but the channel
1230
        // announcement was not sent.
1231
        case addedToGraph:
31✔
1232
                if channel.IsZeroConf() {
40✔
1233
                        // If this is a zero-conf channel, then we will wait
9✔
1234
                        // for it to be confirmed before announcing it to the
9✔
1235
                        // greater network.
9✔
1236
                        err := f.waitForZeroConfChannel(channel)
9✔
1237
                        if err != nil {
14✔
1238
                                return fmt.Errorf("failed waiting for zero "+
5✔
1239
                                        "channel: %v", err)
5✔
1240
                        }
5✔
1241

1242
                        // Update the local shortChanID variable such that
1243
                        // annAfterSixConfs uses the confirmed SCID.
1244
                        confirmedScid := channel.ZeroConfRealScid()
7✔
1245
                        shortChanID = &confirmedScid
7✔
1246
                }
1247

1248
                err := f.annAfterSixConfs(channel, shortChanID)
29✔
1249
                if err != nil {
34✔
1250
                        return fmt.Errorf("error sending channel "+
5✔
1251
                                "announcement: %v", err)
5✔
1252
                }
5✔
1253

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

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

1275
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
1276
                        "announced", chanID, shortChanID)
27✔
1277

27✔
1278
                return nil
27✔
1279
        }
1280

1281
        return fmt.Errorf("undefined channelState: %v", channelState)
×
1282
}
1283

1284
// advancePendingChannelState waits for a pending channel's funding tx to
1285
// confirm, and marks it open in the database when that happens.
1286
func (f *Manager) advancePendingChannelState(channel *channeldb.OpenChannel,
1287
        pendingChanID PendingChanID) error {
58✔
1288

58✔
1289
        if channel.IsZeroConf() {
65✔
1290
                // Persist the alias to the alias database.
7✔
1291
                baseScid := channel.ShortChannelID
7✔
1292
                err := f.cfg.AliasManager.AddLocalAlias(
7✔
1293
                        baseScid, baseScid, true, false,
7✔
1294
                )
7✔
1295
                if err != nil {
7✔
1296
                        return fmt.Errorf("error adding local alias to "+
×
1297
                                "store: %v", err)
×
1298
                }
×
1299

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

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

1321
                // Inform the ChannelNotifier that the channel has transitioned
1322
                // from pending open to open.
1323
                f.cfg.NotifyOpenChannelEvent(
7✔
1324
                        channel.FundingOutpoint, channel.IdentityPub,
7✔
1325
                )
7✔
1326

7✔
1327
                // Find and close the discoverySignal for this channel such
7✔
1328
                // that ChannelReady messages will be processed.
7✔
1329
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
7✔
1330
                discoverySignal, ok := f.localDiscoverySignals.Load(chanID)
7✔
1331
                if ok {
14✔
1332
                        close(discoverySignal)
7✔
1333
                }
7✔
1334

1335
                return nil
7✔
1336
        }
1337

1338
        confChannel, err := f.waitForFundingWithTimeout(channel)
54✔
1339
        if err == ErrConfirmationTimeout {
59✔
1340
                return f.fundingTimeout(channel, pendingChanID)
5✔
1341
        } else if err != nil {
79✔
1342
                return fmt.Errorf("error waiting for funding "+
22✔
1343
                        "confirmation for ChannelPoint(%v): %v",
22✔
1344
                        channel.FundingOutpoint, err)
22✔
1345
        }
22✔
1346

1347
        if blockchain.IsCoinBaseTx(confChannel.fundingTx) {
35✔
1348
                // If it's a coinbase transaction, we need to wait for it to
2✔
1349
                // mature. We wait out an additional MinAcceptDepth on top of
2✔
1350
                // the coinbase maturity as an extra margin of safety.
2✔
1351
                maturity := f.cfg.Wallet.Cfg.NetParams.CoinbaseMaturity
2✔
1352
                numCoinbaseConfs := uint32(maturity)
2✔
1353

2✔
1354
                if channel.NumConfsRequired > maturity {
2✔
1355
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1356
                }
×
1357

1358
                txid := &channel.FundingOutpoint.Hash
2✔
1359
                fundingScript, err := makeFundingScript(channel)
2✔
1360
                if err != nil {
2✔
1361
                        log.Errorf("unable to create funding script for "+
×
1362
                                "ChannelPoint(%v): %v",
×
1363
                                channel.FundingOutpoint, err)
×
1364

×
1365
                        return err
×
1366
                }
×
1367

1368
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
2✔
1369
                        txid, fundingScript, numCoinbaseConfs,
2✔
1370
                        channel.BroadcastHeight(),
2✔
1371
                )
2✔
1372
                if err != nil {
2✔
1373
                        log.Errorf("Unable to register for confirmation of "+
×
1374
                                "ChannelPoint(%v): %v",
×
1375
                                channel.FundingOutpoint, err)
×
1376

×
1377
                        return err
×
1378
                }
×
1379

1380
                select {
2✔
1381
                case _, ok := <-confNtfn.Confirmed:
2✔
1382
                        if !ok {
2✔
1383
                                return fmt.Errorf("ChainNotifier shutting "+
×
1384
                                        "down, can't complete funding flow "+
×
1385
                                        "for ChannelPoint(%v)",
×
1386
                                        channel.FundingOutpoint)
×
1387
                        }
×
1388

1389
                case <-f.quit:
×
1390
                        return ErrFundingManagerShuttingDown
×
1391
                }
1392
        }
1393

1394
        // Success, funding transaction was confirmed.
1395
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
33✔
1396
        log.Debugf("ChannelID(%v) is now fully confirmed! "+
33✔
1397
                "(shortChanID=%v)", chanID, confChannel.shortChanID)
33✔
1398

33✔
1399
        err = f.handleFundingConfirmation(channel, confChannel)
33✔
1400
        if err != nil {
33✔
1401
                return fmt.Errorf("unable to handle funding "+
×
1402
                        "confirmation for ChannelPoint(%v): %v",
×
1403
                        channel.FundingOutpoint, err)
×
1404
        }
×
1405

1406
        return nil
33✔
1407
}
1408

1409
// ProcessFundingMsg sends a message to the internal fundingManager goroutine,
1410
// allowing it to handle the lnwire.Message.
1411
func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer) {
213✔
1412
        select {
213✔
1413
        case f.fundingMsgs <- &fundingMsg{msg, peer}:
213✔
1414
        case <-f.quit:
×
1415
                return
×
1416
        }
1417
}
1418

1419
// fundeeProcessOpenChannel creates an initial 'ChannelReservation' within the
1420
// wallet, then responds to the source peer with an accept channel message
1421
// progressing the funding workflow.
1422
//
1423
// TODO(roasbeef): add error chan to all, let channelManager handle
1424
// error+propagate.
1425
//
1426
//nolint:funlen
1427
func (f *Manager) fundeeProcessOpenChannel(peer lnpeer.Peer,
1428
        msg *lnwire.OpenChannel) {
57✔
1429

57✔
1430
        // Check number of pending channels to be smaller than maximum allowed
57✔
1431
        // number and send ErrorGeneric to remote peer if condition is
57✔
1432
        // violated.
57✔
1433
        peerPubKey := peer.IdentityKey()
57✔
1434
        peerIDKey := newSerializedKey(peerPubKey)
57✔
1435

57✔
1436
        amt := msg.FundingAmount
57✔
1437

57✔
1438
        // We get all pending channels for this peer. This is the list of the
57✔
1439
        // active reservations and the channels pending open in the database.
57✔
1440
        f.resMtx.RLock()
57✔
1441
        reservations := f.activeReservations[peerIDKey]
57✔
1442

57✔
1443
        // We don't count reservations that were created from a canned funding
57✔
1444
        // shim. The user has registered the shim and therefore expects this
57✔
1445
        // channel to arrive.
57✔
1446
        numPending := 0
57✔
1447
        for _, res := range reservations {
69✔
1448
                if !res.reservation.IsCannedShim() {
24✔
1449
                        numPending++
12✔
1450
                }
12✔
1451
        }
1452
        f.resMtx.RUnlock()
57✔
1453

57✔
1454
        // Create the channel identifier.
57✔
1455
        cid := newChanIdentifier(msg.PendingChannelID)
57✔
1456

57✔
1457
        // Also count the channels that are already pending. There we don't know
57✔
1458
        // the underlying intent anymore, unfortunately.
57✔
1459
        channels, err := f.cfg.ChannelDB.FetchOpenChannels(peerPubKey)
57✔
1460
        if err != nil {
57✔
1461
                f.failFundingFlow(peer, cid, err)
×
1462
                return
×
1463
        }
×
1464

1465
        for _, c := range channels {
72✔
1466
                // Pending channels that have a non-zero thaw height were also
15✔
1467
                // created through a canned funding shim. Those also don't
15✔
1468
                // count towards the DoS protection limit.
15✔
1469
                //
15✔
1470
                // TODO(guggero): Properly store the funding type (wallet, shim,
15✔
1471
                // PSBT) on the channel so we don't need to use the thaw height.
15✔
1472
                if c.IsPending && c.ThawHeight == 0 {
26✔
1473
                        numPending++
11✔
1474
                }
11✔
1475
        }
1476

1477
        // TODO(roasbeef): modify to only accept a _single_ pending channel per
1478
        // block unless white listed
1479
        if numPending >= f.cfg.MaxPendingChannels {
64✔
1480
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
7✔
1481

7✔
1482
                return
7✔
1483
        }
7✔
1484

1485
        // Ensure that the pendingChansLimit is respected.
1486
        pendingChans, err := f.cfg.ChannelDB.FetchPendingChannels()
53✔
1487
        if err != nil {
53✔
1488
                f.failFundingFlow(peer, cid, err)
×
1489
                return
×
1490
        }
×
1491

1492
        if len(pendingChans) > pendingChansLimit {
53✔
1493
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1494
                return
×
1495
        }
×
1496

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

1510
        // Ensure that the remote party respects our maximum channel size.
1511
        if amt > f.cfg.MaxChanSize {
58✔
1512
                f.failFundingFlow(
5✔
1513
                        peer, cid,
5✔
1514
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
5✔
1515
                )
5✔
1516
                return
5✔
1517
        }
5✔
1518

1519
        // We'll, also ensure that the remote party isn't attempting to propose
1520
        // a channel that's below our current min channel size.
1521
        if amt < f.cfg.MinChanSize {
54✔
1522
                f.failFundingFlow(
3✔
1523
                        peer, cid,
3✔
1524
                        lnwallet.ErrChanTooSmall(amt, f.cfg.MinChanSize),
3✔
1525
                )
3✔
1526
                return
3✔
1527
        }
3✔
1528

1529
        // If request specifies non-zero push amount and 'rejectpush' is set,
1530
        // signal an error.
1531
        if f.cfg.RejectPush && msg.PushAmount > 0 {
52✔
1532
                f.failFundingFlow(peer, cid, lnwallet.ErrNonZeroPushAmount())
1✔
1533
                return
1✔
1534
        }
1✔
1535

1536
        // Send the OpenChannel request to the ChannelAcceptor to determine
1537
        // whether this node will accept the channel.
1538
        chanReq := &chanacceptor.ChannelAcceptRequest{
50✔
1539
                Node:        peer.IdentityKey(),
50✔
1540
                OpenChanMsg: msg,
50✔
1541
        }
50✔
1542

50✔
1543
        // Query our channel acceptor to determine whether we should reject
50✔
1544
        // the channel.
50✔
1545
        acceptorResp := f.cfg.OpenChannelPredicate.Accept(chanReq)
50✔
1546
        if acceptorResp.RejectChannel() {
53✔
1547
                f.failFundingFlow(peer, cid, acceptorResp.ChanAcceptError)
3✔
1548
                return
3✔
1549
        }
3✔
1550

1551
        log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
50✔
1552
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
50✔
1553
                msg.CsvDelay, msg.PendingChannelID,
50✔
1554
                peer.IdentityKey().SerializeCompressed())
50✔
1555

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

1577
        var scidFeatureVal bool
50✔
1578
        if hasFeatures(
50✔
1579
                peer.LocalFeatures(), peer.RemoteFeatures(),
50✔
1580
                lnwire.ScidAliasOptional,
50✔
1581
        ) {
56✔
1582

6✔
1583
                scidFeatureVal = true
6✔
1584
        }
6✔
1585

1586
        var (
50✔
1587
                zeroConf bool
50✔
1588
                scid     bool
50✔
1589
        )
50✔
1590

50✔
1591
        // Only echo back a channel type in AcceptChannel if we actually used
50✔
1592
        // explicit negotiation above.
50✔
1593
        if chanType != nil {
57✔
1594
                // Check if the channel type includes the zero-conf or
7✔
1595
                // scid-alias bits.
7✔
1596
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
1597
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
1598
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
1599

7✔
1600
                // If the zero-conf channel type was negotiated, ensure that
7✔
1601
                // the acceptor allows it.
7✔
1602
                if zeroConf && !acceptorResp.ZeroConf {
7✔
1603
                        // Fail the funding flow.
×
1604
                        flowErr := fmt.Errorf("channel acceptor blocked " +
×
1605
                                "zero-conf channel negotiation")
×
1606
                        log.Errorf("Cancelling funding flow for %v based on "+
×
1607
                                "channel acceptor response: %v", cid, flowErr)
×
1608
                        f.failFundingFlow(peer, cid, flowErr)
×
1609
                        return
×
1610
                }
×
1611

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

1629
                        // Set zeroConf to true to enable the zero-conf flow.
1630
                        zeroConf = true
×
1631
                }
1632
        }
1633

1634
        public := msg.ChannelFlags&lnwire.FFAnnounceChannel != 0
50✔
1635
        switch {
50✔
1636
        // Sending the option-scid-alias channel type for a public channel is
1637
        // disallowed.
1638
        case public && scid:
×
1639
                err = fmt.Errorf("option-scid-alias chantype for public " +
×
1640
                        "channel")
×
1641
                log.Errorf("Cancelling funding flow for public channel %v "+
×
1642
                        "with scid-alias: %v", cid, err)
×
1643
                f.failFundingFlow(peer, cid, err)
×
1644

×
1645
                return
×
1646

1647
        // The current variant of taproot channels can only be used with
1648
        // unadvertised channels for now.
1649
        case commitType.IsTaproot() && public:
×
1650
                err = fmt.Errorf("taproot channel type for public channel")
×
1651
                log.Errorf("Cancelling funding flow for public taproot "+
×
1652
                        "channel %v: %v", cid, err)
×
1653
                f.failFundingFlow(peer, cid, err)
×
1654

×
1655
                return
×
1656
        }
1657

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

×
1672
                return
×
1673
        }
×
1674

1675
        req := &lnwallet.InitFundingReserveMsg{
50✔
1676
                ChainHash:        &msg.ChainHash,
50✔
1677
                PendingChanID:    msg.PendingChannelID,
50✔
1678
                NodeID:           peer.IdentityKey(),
50✔
1679
                NodeAddr:         peer.Address(),
50✔
1680
                LocalFundingAmt:  0,
50✔
1681
                RemoteFundingAmt: amt,
50✔
1682
                CommitFeePerKw:   chainfee.SatPerKWeight(msg.FeePerKiloWeight),
50✔
1683
                FundingFeePerKw:  0,
50✔
1684
                PushMSat:         msg.PushAmount,
50✔
1685
                Flags:            msg.ChannelFlags,
50✔
1686
                MinConfs:         1,
50✔
1687
                CommitType:       commitType,
50✔
1688
                ZeroConf:         zeroConf,
50✔
1689
                OptionScidAlias:  scid,
50✔
1690
                ScidAliasFeature: scidFeatureVal,
50✔
1691
                TapscriptRoot:    tapscriptRoot,
50✔
1692
        }
50✔
1693

50✔
1694
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
50✔
1695
        if err != nil {
50✔
1696
                log.Errorf("Unable to initialize reservation: %v", err)
×
1697
                f.failFundingFlow(peer, cid, err)
×
1698
                return
×
1699
        }
×
1700

1701
        log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
50✔
1702
                "cannedShim=%v", reservation.IsZeroConf(),
50✔
1703
                reservation.IsPsbt(), reservation.IsCannedShim())
50✔
1704

50✔
1705
        if zeroConf {
55✔
1706
                // Store an alias for zero-conf channels. Other option-scid
5✔
1707
                // channels will do this at a later point.
5✔
1708
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
1709
                if err != nil {
5✔
1710
                        log.Errorf("Unable to request alias: %v", err)
×
1711
                        f.failFundingFlow(peer, cid, err)
×
1712
                        return
×
1713
                }
×
1714

1715
                reservation.AddAlias(aliasScid)
5✔
1716
        }
1717

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

1729
        // We'll ignore the min_depth calculated above if this is a zero-conf
1730
        // channel.
1731
        if zeroConf {
55✔
1732
                numConfsReq = 0
5✔
1733
        }
5✔
1734

1735
        reservation.SetNumConfsRequired(numConfsReq)
50✔
1736

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

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

49✔
1775
        // If a script enforced channel lease is being proposed, we'll need to
49✔
1776
        // validate its custom TLV records.
49✔
1777
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
52✔
1778
                if msg.LeaseExpiry == nil {
3✔
1779
                        err := errors.New("missing lease expiry")
×
1780
                        f.failFundingFlow(peer, cid, err)
×
1781
                        return
×
1782
                }
×
1783

1784
                // If we had a shim registered for this channel prior to
1785
                // receiving its corresponding OpenChannel message, then we'll
1786
                // validate the proposed LeaseExpiry against what was registered
1787
                // in our shim.
1788
                if reservation.LeaseExpiry() != 0 {
6✔
1789
                        if uint32(*msg.LeaseExpiry) !=
3✔
1790
                                reservation.LeaseExpiry() {
3✔
1791

×
1792
                                err := errors.New("lease expiry mismatch")
×
1793
                                f.failFundingFlow(peer, cid, err)
×
1794
                                return
×
1795
                        }
×
1796
                }
1797
        }
1798

1799
        log.Infof("Requiring %v confirmations for pendingChan(%x): "+
49✔
1800
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
49✔
1801
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
49✔
1802
                commitType, msg.UpfrontShutdownScript)
49✔
1803

49✔
1804
        // Generate our required constraints for the remote party, using the
49✔
1805
        // values provided by the channel acceptor if they are non-zero.
49✔
1806
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
49✔
1807
        if acceptorResp.CSVDelay != 0 {
49✔
1808
                remoteCsvDelay = acceptorResp.CSVDelay
×
1809
        }
×
1810

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

1823
        chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
49✔
1824
        if acceptorResp.Reserve != 0 {
49✔
1825
                chanReserve = acceptorResp.Reserve
×
1826
        }
×
1827

1828
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
49✔
1829
        if acceptorResp.InFlightTotal != 0 {
49✔
1830
                remoteMaxValue = acceptorResp.InFlightTotal
×
1831
        }
×
1832

1833
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
49✔
1834
        if acceptorResp.HtlcLimit != 0 {
49✔
1835
                maxHtlcs = acceptorResp.HtlcLimit
×
1836
        }
×
1837

1838
        // Default to our default minimum hltc value, replacing it with the
1839
        // channel acceptor's value if it is set.
1840
        minHtlc := f.cfg.DefaultMinHtlcIn
49✔
1841
        if acceptorResp.MinHtlcIn != 0 {
49✔
1842
                minHtlc = acceptorResp.MinHtlcIn
×
1843
        }
×
1844

1845
        // If we are handling a FundingOpen request then we need to specify the
1846
        // default channel fees since they are not provided by the responder
1847
        // interactively.
1848
        ourContribution := reservation.OurContribution()
49✔
1849
        forwardingPolicy := f.defaultForwardingPolicy(
49✔
1850
                ourContribution.ChannelStateBounds,
49✔
1851
        )
49✔
1852

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

49✔
1877
        // Update the timestamp once the fundingOpenMsg has been handled.
49✔
1878
        defer resCtx.updateTimestamp()
49✔
1879

49✔
1880
        cfg := channeldb.ChannelConfig{
49✔
1881
                ChannelStateBounds: channeldb.ChannelStateBounds{
49✔
1882
                        MaxPendingAmount: remoteMaxValue,
49✔
1883
                        ChanReserve:      chanReserve,
49✔
1884
                        MinHTLC:          minHtlc,
49✔
1885
                        MaxAcceptedHtlcs: maxHtlcs,
49✔
1886
                },
49✔
1887
                CommitmentParams: channeldb.CommitmentParams{
49✔
1888
                        DustLimit: msg.DustLimit,
49✔
1889
                        CsvDelay:  remoteCsvDelay,
49✔
1890
                },
49✔
1891
                MultiSigKey: keychain.KeyDescriptor{
49✔
1892
                        PubKey: copyPubKey(msg.FundingKey),
49✔
1893
                },
49✔
1894
                RevocationBasePoint: keychain.KeyDescriptor{
49✔
1895
                        PubKey: copyPubKey(msg.RevocationPoint),
49✔
1896
                },
49✔
1897
                PaymentBasePoint: keychain.KeyDescriptor{
49✔
1898
                        PubKey: copyPubKey(msg.PaymentPoint),
49✔
1899
                },
49✔
1900
                DelayBasePoint: keychain.KeyDescriptor{
49✔
1901
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
49✔
1902
                },
49✔
1903
                HtlcBasePoint: keychain.KeyDescriptor{
49✔
1904
                        PubKey: copyPubKey(msg.HtlcPoint),
49✔
1905
                },
49✔
1906
        }
49✔
1907

49✔
1908
        // With our parameters set, we'll now process their contribution so we
49✔
1909
        // can move the funding workflow ahead.
49✔
1910
        remoteContribution := &lnwallet.ChannelContribution{
49✔
1911
                FundingAmount:        amt,
49✔
1912
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
49✔
1913
                ChannelConfig:        &cfg,
49✔
1914
                UpfrontShutdown:      msg.UpfrontShutdownScript,
49✔
1915
        }
49✔
1916

49✔
1917
        if resCtx.reservation.IsTaproot() {
54✔
1918
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
1919
                if err != nil {
5✔
1920
                        log.Error(errNoLocalNonce)
×
1921

×
1922
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1923

×
1924
                        return
×
1925
                }
×
1926

1927
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
1928
                        PubNonce: localNonce,
5✔
1929
                }
5✔
1930
        }
1931

1932
        err = reservation.ProcessSingleContribution(remoteContribution)
49✔
1933
        if err != nil {
55✔
1934
                log.Errorf("unable to add contribution reservation: %v", err)
6✔
1935
                f.failFundingFlow(peer, cid, err)
6✔
1936
                return
6✔
1937
        }
6✔
1938

1939
        log.Infof("Sending fundingResp for pending_id(%x)",
43✔
1940
                msg.PendingChannelID)
43✔
1941
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
43✔
1942
        log.Debugf("Remote party accepted channel state space bounds: %v",
43✔
1943
                lnutils.SpewLogClosure(bounds))
43✔
1944
        params := remoteContribution.ChannelConfig.CommitmentParams
43✔
1945
        log.Debugf("Remote party accepted commitment rendering params: %v",
43✔
1946
                lnutils.SpewLogClosure(params))
43✔
1947

43✔
1948
        reservation.SetState(lnwallet.SentAcceptChannel)
43✔
1949

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

43✔
1972
        if commitType.IsTaproot() {
48✔
1973
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
1974
                        ourContribution.LocalNonce.PubNonce,
5✔
1975
                )
5✔
1976
        }
5✔
1977

1978
        if err := peer.SendMessage(true, &fundingAccept); err != nil {
43✔
1979
                log.Errorf("unable to send funding response to peer: %v", err)
×
1980
                f.failFundingFlow(peer, cid, err)
×
1981
                return
×
1982
        }
×
1983
}
1984

1985
// funderProcessAcceptChannel processes a response to the workflow initiation
1986
// sent by the remote peer. This message then queues a message with the funding
1987
// outpoint, and a commitment signature to the remote peer.
1988
//
1989
//nolint:funlen
1990
func (f *Manager) funderProcessAcceptChannel(peer lnpeer.Peer,
1991
        msg *lnwire.AcceptChannel) {
35✔
1992

35✔
1993
        pendingChanID := msg.PendingChannelID
35✔
1994
        peerKey := peer.IdentityKey()
35✔
1995
        var peerKeyBytes []byte
35✔
1996
        if peerKey != nil {
70✔
1997
                peerKeyBytes = peerKey.SerializeCompressed()
35✔
1998
        }
35✔
1999

2000
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
35✔
2001
        if err != nil {
35✔
2002
                log.Warnf("Can't find reservation (peerKey:%x, chan_id:%v)",
×
2003
                        peerKeyBytes, pendingChanID)
×
2004
                return
×
2005
        }
×
2006

2007
        // Update the timestamp once the fundingAcceptMsg has been handled.
2008
        defer resCtx.updateTimestamp()
35✔
2009

35✔
2010
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
35✔
2011
                return
×
2012
        }
×
2013

2014
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
35✔
2015
                pendingChanID[:])
35✔
2016

35✔
2017
        // Create the channel identifier.
35✔
2018
        cid := newChanIdentifier(msg.PendingChannelID)
35✔
2019

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

2040
                // We'll want to do the same with the LeaseExpiry if one should
2041
                // be set.
2042
                if resCtx.reservation.LeaseExpiry() != 0 {
9✔
2043
                        if msg.LeaseExpiry == nil {
3✔
2044
                                err := errors.New("lease expiry not echoed " +
×
2045
                                        "back")
×
2046
                                f.failFundingFlow(peer, cid, err)
×
2047
                                return
×
2048
                        }
×
2049
                        if uint32(*msg.LeaseExpiry) !=
3✔
2050
                                resCtx.reservation.LeaseExpiry() {
3✔
2051

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

×
2067
                _, negotiatedCommitType, err := negotiateCommitmentType(
×
2068
                        msg.ChannelType, peer.LocalFeatures(),
×
2069
                        peer.RemoteFeatures(),
×
2070
                )
×
2071
                if err != nil {
×
2072
                        err := errors.New("received unexpected channel type")
×
2073
                        f.failFundingFlow(peer, cid, err)
×
2074
                        return
×
2075
                }
×
2076

2077
                if implicitCommitType != negotiatedCommitType {
×
2078
                        err := errors.New("negotiated unexpected channel type")
×
2079
                        f.failFundingFlow(peer, cid, err)
×
2080
                        return
×
2081
                }
×
2082
        }
2083

2084
        // The required number of confirmations should not be greater than the
2085
        // maximum number of confirmations required by the ChainNotifier to
2086
        // properly dispatch confirmations.
2087
        if msg.MinAcceptDepth > chainntnfs.MaxNumConfs {
35✔
2088
                err := lnwallet.ErrNumConfsTooLarge(
1✔
2089
                        msg.MinAcceptDepth, chainntnfs.MaxNumConfs,
1✔
2090
                )
1✔
2091
                log.Warnf("Unacceptable channel constraints: %v", err)
1✔
2092
                f.failFundingFlow(peer, cid, err)
1✔
2093
                return
1✔
2094
        }
1✔
2095

2096
        // Check that zero-conf channels have minimum depth set to 0.
2097
        if resCtx.reservation.IsZeroConf() && msg.MinAcceptDepth != 0 {
33✔
2098
                err = fmt.Errorf("zero-conf channel has min_depth non-zero")
×
2099
                log.Warn(err)
×
2100
                f.failFundingFlow(peer, cid, err)
×
2101
                return
×
2102
        }
×
2103

2104
        // If this is not a zero-conf channel but the peer responded with a
2105
        // min-depth of zero, we will use our minimum of 1 instead.
2106
        minDepth := msg.MinAcceptDepth
33✔
2107
        if !resCtx.reservation.IsZeroConf() && minDepth == 0 {
33✔
2108
                log.Infof("Responder to pending_id=%v sent a minimum "+
×
2109
                        "confirmation depth of 0 for non-zero-conf channel. "+
×
2110
                        "We will use a minimum depth of 1 instead.",
×
2111
                        cid.tempChanID)
×
2112

×
2113
                minDepth = 1
×
2114
        }
×
2115

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

2139
        cfg := channeldb.ChannelConfig{
32✔
2140
                ChannelStateBounds: channeldb.ChannelStateBounds{
32✔
2141
                        MaxPendingAmount: resCtx.remoteMaxValue,
32✔
2142
                        ChanReserve:      resCtx.remoteChanReserve,
32✔
2143
                        MinHTLC:          resCtx.remoteMinHtlc,
32✔
2144
                        MaxAcceptedHtlcs: resCtx.remoteMaxHtlcs,
32✔
2145
                },
32✔
2146
                CommitmentParams: channeldb.CommitmentParams{
32✔
2147
                        DustLimit: msg.DustLimit,
32✔
2148
                        CsvDelay:  resCtx.remoteCsvDelay,
32✔
2149
                },
32✔
2150
                MultiSigKey: keychain.KeyDescriptor{
32✔
2151
                        PubKey: copyPubKey(msg.FundingKey),
32✔
2152
                },
32✔
2153
                RevocationBasePoint: keychain.KeyDescriptor{
32✔
2154
                        PubKey: copyPubKey(msg.RevocationPoint),
32✔
2155
                },
32✔
2156
                PaymentBasePoint: keychain.KeyDescriptor{
32✔
2157
                        PubKey: copyPubKey(msg.PaymentPoint),
32✔
2158
                },
32✔
2159
                DelayBasePoint: keychain.KeyDescriptor{
32✔
2160
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
32✔
2161
                },
32✔
2162
                HtlcBasePoint: keychain.KeyDescriptor{
32✔
2163
                        PubKey: copyPubKey(msg.HtlcPoint),
32✔
2164
                },
32✔
2165
        }
32✔
2166

32✔
2167
        // The remote node has responded with their portion of the channel
32✔
2168
        // contribution. At this point, we can process their contribution which
32✔
2169
        // allows us to construct and sign both the commitment transaction, and
32✔
2170
        // the funding transaction.
32✔
2171
        remoteContribution := &lnwallet.ChannelContribution{
32✔
2172
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
32✔
2173
                ChannelConfig:        &cfg,
32✔
2174
                UpfrontShutdown:      msg.UpfrontShutdownScript,
32✔
2175
        }
32✔
2176

32✔
2177
        if resCtx.reservation.IsTaproot() {
37✔
2178
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
2179
                if err != nil {
5✔
2180
                        log.Error(errNoLocalNonce)
×
2181

×
2182
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2183

×
2184
                        return
×
2185
                }
×
2186

2187
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
2188
                        PubNonce: localNonce,
5✔
2189
                }
5✔
2190
        }
2191

2192
        err = resCtx.reservation.ProcessContribution(remoteContribution)
32✔
2193

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

2236
        log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+
32✔
2237
                "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
32✔
2238
                msg.CsvDelay)
32✔
2239
        bounds = remoteContribution.ChannelConfig.ChannelStateBounds
32✔
2240
        log.Debugf("Remote party accepted channel state space bounds: %v",
32✔
2241
                lnutils.SpewLogClosure(bounds))
32✔
2242
        commitParams = remoteContribution.ChannelConfig.CommitmentParams
32✔
2243
        log.Debugf("Remote party accepted commitment rendering params: %v",
32✔
2244
                lnutils.SpewLogClosure(commitParams))
32✔
2245

32✔
2246
        // If the user requested funding through a PSBT, we cannot directly
32✔
2247
        // continue now and need to wait for the fully funded and signed PSBT
32✔
2248
        // to arrive. To not block any other channels from opening, we wait in
32✔
2249
        // a separate goroutine.
32✔
2250
        if psbtIntent != nil {
35✔
2251
                f.wg.Add(1)
3✔
2252
                go func() {
6✔
2253
                        defer f.wg.Done()
3✔
2254

3✔
2255
                        f.waitForPsbt(psbtIntent, resCtx, cid)
3✔
2256
                }()
3✔
2257

2258
                // With the new goroutine spawned, we can now exit to unblock
2259
                // the main event loop.
2260
                return
3✔
2261
        }
2262

2263
        // In a normal, non-PSBT funding flow, we can jump directly to the next
2264
        // step where we expect our contribution to be finalized.
2265
        f.continueFundingAccept(resCtx, cid)
32✔
2266
}
2267

2268
// waitForPsbt blocks until either a signed PSBT arrives, an error occurs or
2269
// the funding manager shuts down. In the case of a valid PSBT, the funding flow
2270
// is continued.
2271
//
2272
// NOTE: This method must be called as a goroutine.
2273
func (f *Manager) waitForPsbt(intent *chanfunding.PsbtIntent,
2274
        resCtx *reservationWithCtx, cid *chanIdentifier) {
3✔
2275

3✔
2276
        // failFlow is a helper that logs an error message with the current
3✔
2277
        // context and then fails the funding flow.
3✔
2278
        peerKey := resCtx.peer.IdentityKey()
3✔
2279
        failFlow := func(errMsg string, cause error) {
6✔
2280
                log.Errorf("Unable to handle funding accept message "+
3✔
2281
                        "for peer_key=%x, pending_chan_id=%x: %s: %v",
3✔
2282
                        peerKey.SerializeCompressed(), cid.tempChanID, errMsg,
3✔
2283
                        cause)
3✔
2284
                f.failFundingFlow(resCtx.peer, cid, cause)
3✔
2285
        }
3✔
2286

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

2299
                // If the remote canceled the funding reservation, we don't need
2300
                // to send another fail message. But we want to inform the user
2301
                // about what happened.
2302
                case chanfunding.ErrRemoteCanceled:
3✔
2303
                        log.Infof("Remote canceled, aborting PSBT flow "+
3✔
2304
                                "for peer_key=%x, pending_chan_id=%x",
3✔
2305
                                peerKey.SerializeCompressed(), cid.tempChanID)
3✔
2306
                        return
3✔
2307

2308
                // Nil error means the flow continues normally now.
2309
                case nil:
3✔
2310

2311
                // For any other error, we'll fail the funding flow.
2312
                default:
×
2313
                        failFlow("error waiting for PSBT flow", err)
×
2314
                        return
×
2315
                }
2316

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

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

2350
                // We are now ready to continue the funding flow.
2351
                f.continueFundingAccept(resCtx, cid)
3✔
2352

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

2364
// continueFundingAccept continues the channel funding flow once our
2365
// contribution is finalized, the channel output is known and the funding
2366
// transaction is signed.
2367
func (f *Manager) continueFundingAccept(resCtx *reservationWithCtx,
2368
        cid *chanIdentifier) {
32✔
2369

32✔
2370
        // Now that we have their contribution, we can extract, then send over
32✔
2371
        // both the funding out point and our signature for their version of
32✔
2372
        // the commitment transaction to the remote peer.
32✔
2373
        outPoint := resCtx.reservation.FundingOutpoint()
32✔
2374
        _, sig := resCtx.reservation.OurSignatures()
32✔
2375

32✔
2376
        // A new channel has almost finished the funding process. In order to
32✔
2377
        // properly synchronize with the writeHandler goroutine, we add a new
32✔
2378
        // channel to the barriers map which will be closed once the channel is
32✔
2379
        // fully open.
32✔
2380
        channelID := lnwire.NewChanIDFromOutPoint(*outPoint)
32✔
2381
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
32✔
2382

32✔
2383
        // The next message that advances the funding flow will reference the
32✔
2384
        // channel via its permanent channel ID, so we'll set up this mapping
32✔
2385
        // so we can retrieve the reservation context once we get the
32✔
2386
        // FundingSigned message.
32✔
2387
        f.resMtx.Lock()
32✔
2388
        f.signedReservations[channelID] = cid.tempChanID
32✔
2389
        f.resMtx.Unlock()
32✔
2390

32✔
2391
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
32✔
2392
                cid.tempChanID[:])
32✔
2393

32✔
2394
        // Before sending FundingCreated sent, we notify Brontide to keep track
32✔
2395
        // of this pending open channel.
32✔
2396
        err := resCtx.peer.AddPendingChannel(channelID, f.quit)
32✔
2397
        if err != nil {
32✔
2398
                pubKey := resCtx.peer.IdentityKey().SerializeCompressed()
×
2399
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2400
                        channelID, pubKey, err)
×
2401
        }
×
2402

2403
        // Once Brontide is aware of this channel, we need to set it in
2404
        // chanIdentifier so this channel will be removed from Brontide if the
2405
        // funding flow fails.
2406
        cid.setChanID(channelID)
32✔
2407

32✔
2408
        // Send the FundingCreated msg.
32✔
2409
        fundingCreated := &lnwire.FundingCreated{
32✔
2410
                PendingChannelID: cid.tempChanID,
32✔
2411
                FundingPoint:     *outPoint,
32✔
2412
        }
32✔
2413

32✔
2414
        // If this is a taproot channel, then we'll need to populate the musig2
32✔
2415
        // partial sig field instead of the regular commit sig field.
32✔
2416
        if resCtx.reservation.IsTaproot() {
37✔
2417
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
5✔
2418
                if !ok {
5✔
2419
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2420
                                sig)
×
2421
                        log.Error(err)
×
2422
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2423

×
2424
                        return
×
2425
                }
×
2426

2427
                fundingCreated.PartialSig = lnwire.MaybePartialSigWithNonce(
5✔
2428
                        partialSig.ToWireSig(),
5✔
2429
                )
5✔
2430
        } else {
30✔
2431
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
30✔
2432
                if err != nil {
30✔
2433
                        log.Errorf("Unable to parse signature: %v", err)
×
2434
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2435
                        return
×
2436
                }
×
2437
        }
2438

2439
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
32✔
2440

32✔
2441
        if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
32✔
2442
                log.Errorf("Unable to send funding complete message: %v", err)
×
2443
                f.failFundingFlow(resCtx.peer, cid, err)
×
2444
                return
×
2445
        }
×
2446
}
2447

2448
// fundeeProcessFundingCreated progresses the funding workflow when the daemon
2449
// is on the responding side of a single funder workflow. Once this message has
2450
// been processed, a signature is sent to the remote peer allowing it to
2451
// broadcast the funding transaction, progressing the workflow into the final
2452
// stage.
2453
//
2454
//nolint:funlen
2455
func (f *Manager) fundeeProcessFundingCreated(peer lnpeer.Peer,
2456
        msg *lnwire.FundingCreated) {
30✔
2457

30✔
2458
        peerKey := peer.IdentityKey()
30✔
2459
        pendingChanID := msg.PendingChannelID
30✔
2460

30✔
2461
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
30✔
2462
        if err != nil {
30✔
2463
                log.Warnf("can't find reservation (peer_id:%v, chan_id:%x)",
×
2464
                        peerKey, pendingChanID[:])
×
2465
                return
×
2466
        }
×
2467

2468
        // The channel initiator has responded with the funding outpoint of the
2469
        // final funding transaction, as well as a signature for our version of
2470
        // the commitment transaction. So at this point, we can validate the
2471
        // initiator's commitment transaction, then send our own if it's valid.
2472
        fundingOut := msg.FundingPoint
30✔
2473
        log.Infof("completing pending_id(%x) with ChannelPoint(%v)",
30✔
2474
                pendingChanID[:], fundingOut)
30✔
2475

30✔
2476
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
30✔
2477
                return
×
2478
        }
×
2479

2480
        // Create the channel identifier without setting the active channel ID.
2481
        cid := newChanIdentifier(pendingChanID)
30✔
2482

30✔
2483
        // For taproot channels, the commit signature is actually the partial
30✔
2484
        // signature. Otherwise, we can convert the ECDSA commit signature into
30✔
2485
        // our internal input.Signature type.
30✔
2486
        var commitSig input.Signature
30✔
2487
        if resCtx.reservation.IsTaproot() {
35✔
2488
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
5✔
2489
                if err != nil {
5✔
2490
                        f.failFundingFlow(peer, cid, err)
×
2491

×
2492
                        return
×
2493
                }
×
2494

2495
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
5✔
2496
                        &partialSig,
5✔
2497
                )
5✔
2498
        } else {
28✔
2499
                commitSig, err = msg.CommitSig.ToSignature()
28✔
2500
                if err != nil {
28✔
2501
                        log.Errorf("unable to parse signature: %v", err)
×
2502
                        f.failFundingFlow(peer, cid, err)
×
2503
                        return
×
2504
                }
×
2505
        }
2506

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

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

2544
        // Get forwarding policy before deleting the reservation context.
2545
        forwardingPolicy := resCtx.forwardingPolicy
30✔
2546

30✔
2547
        // The channel is marked IsPending in the database, and can be removed
30✔
2548
        // from the set of active reservations.
30✔
2549
        f.deleteReservationCtx(peerKey, cid.tempChanID)
30✔
2550

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

×
2568
                // Close the channel with us as the initiator because we are
×
2569
                // deciding to exit the funding flow due to an internal error.
×
2570
                if err := completeChan.CloseChannel(
×
2571
                        closeInfo, channeldb.ChanStatusLocalCloseInitiator,
×
2572
                ); err != nil {
×
2573
                        log.Errorf("Failed closing channel %v: %v",
×
2574
                                completeChan.FundingOutpoint, err)
×
2575
                }
×
2576
        }
2577

2578
        // A new channel has almost finished the funding process. In order to
2579
        // properly synchronize with the writeHandler goroutine, we add a new
2580
        // channel to the barriers map which will be closed once the channel is
2581
        // fully open.
2582
        channelID := lnwire.NewChanIDFromOutPoint(fundingOut)
30✔
2583
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
30✔
2584

30✔
2585
        fundingSigned := &lnwire.FundingSigned{}
30✔
2586

30✔
2587
        // For taproot channels, we'll need to send over a partial signature
30✔
2588
        // that includes the nonce along side the signature.
30✔
2589
        _, sig := resCtx.reservation.OurSignatures()
30✔
2590
        if resCtx.reservation.IsTaproot() {
35✔
2591
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
5✔
2592
                if !ok {
5✔
2593
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2594
                                sig)
×
2595
                        log.Error(err)
×
2596
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2597
                        deleteFromDatabase()
×
2598

×
2599
                        return
×
2600
                }
×
2601

2602
                fundingSigned.PartialSig = lnwire.MaybePartialSigWithNonce(
5✔
2603
                        partialSig.ToWireSig(),
5✔
2604
                )
5✔
2605
        } else {
28✔
2606
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
28✔
2607
                if err != nil {
28✔
2608
                        log.Errorf("unable to parse signature: %v", err)
×
2609
                        f.failFundingFlow(peer, cid, err)
×
2610
                        deleteFromDatabase()
×
2611

×
2612
                        return
×
2613
                }
×
2614
        }
2615

2616
        // Before sending FundingSigned, we notify Brontide first to keep track
2617
        // of this pending open channel.
2618
        if err := peer.AddPendingChannel(channelID, f.quit); err != nil {
30✔
2619
                pubKey := peer.IdentityKey().SerializeCompressed()
×
2620
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2621
                        cid.chanID, pubKey, err)
×
2622
        }
×
2623

2624
        // Once Brontide is aware of this channel, we need to set it in
2625
        // chanIdentifier so this channel will be removed from Brontide if the
2626
        // funding flow fails.
2627
        cid.setChanID(channelID)
30✔
2628

30✔
2629
        fundingSigned.ChanID = cid.chanID
30✔
2630

30✔
2631
        log.Infof("sending FundingSigned for pending_id(%x) over "+
30✔
2632
                "ChannelPoint(%v)", pendingChanID[:], fundingOut)
30✔
2633

30✔
2634
        // With their signature for our version of the commitment transaction
30✔
2635
        // verified, we can now send over our signature to the remote peer.
30✔
2636
        if err := peer.SendMessage(true, fundingSigned); err != nil {
30✔
2637
                log.Errorf("unable to send FundingSigned message: %v", err)
×
2638
                f.failFundingFlow(peer, cid, err)
×
2639
                deleteFromDatabase()
×
2640
                return
×
2641
        }
×
2642

2643
        // With a permanent channel id established we can save the respective
2644
        // forwarding policy in the database. In the channel announcement phase
2645
        // this forwarding policy is retrieved and applied.
2646
        err = f.saveInitialForwardingPolicy(cid.chanID, &forwardingPolicy)
30✔
2647
        if err != nil {
30✔
2648
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2649
        }
×
2650

2651
        // Now that we've sent over our final signature for this channel, we'll
2652
        // send it to the ChainArbitrator so it can watch for any on-chain
2653
        // actions during this final confirmation stage.
2654
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
30✔
2655
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2656
                        "arbitration: %v", fundingOut, err)
×
2657
        }
×
2658

2659
        // Create an entry in the local discovery map so we can ensure that we
2660
        // process the channel confirmation fully before we receive a
2661
        // channel_ready message.
2662
        f.localDiscoverySignals.Store(cid.chanID, make(chan struct{}))
30✔
2663

30✔
2664
        // Inform the ChannelNotifier that the channel has entered
30✔
2665
        // pending open state.
30✔
2666
        f.cfg.NotifyPendingOpenChannelEvent(
30✔
2667
                fundingOut, completeChan, completeChan.IdentityPub,
30✔
2668
        )
30✔
2669

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

2690
// funderProcessFundingSigned processes the final message received in a single
2691
// funder workflow. Once this message is processed, the funding transaction is
2692
// broadcast. Once the funding transaction reaches a sufficient number of
2693
// confirmations, a message is sent to the responding peer along with a compact
2694
// encoding of the location of the channel within the blockchain.
2695
func (f *Manager) funderProcessFundingSigned(peer lnpeer.Peer,
2696
        msg *lnwire.FundingSigned) {
30✔
2697

30✔
2698
        // As the funding signed message will reference the reservation by its
30✔
2699
        // permanent channel ID, we'll need to perform an intermediate look up
30✔
2700
        // before we can obtain the reservation.
30✔
2701
        f.resMtx.Lock()
30✔
2702
        pendingChanID, ok := f.signedReservations[msg.ChanID]
30✔
2703
        delete(f.signedReservations, msg.ChanID)
30✔
2704
        f.resMtx.Unlock()
30✔
2705

30✔
2706
        // Create the channel identifier and set the channel ID.
30✔
2707
        //
30✔
2708
        // NOTE: we may get an empty pending channel ID here if the key cannot
30✔
2709
        // be found, which means when we cancel the reservation context in
30✔
2710
        // `failFundingFlow`, we will get an error. In this case, we will send
30✔
2711
        // an error msg to our peer using the active channel ID.
30✔
2712
        //
30✔
2713
        // TODO(yy): refactor the funding flow to fix this case.
30✔
2714
        cid := newChanIdentifier(pendingChanID)
30✔
2715
        cid.setChanID(msg.ChanID)
30✔
2716

30✔
2717
        // If the pending channel ID is not found, fail the funding flow.
30✔
2718
        if !ok {
30✔
2719
                // NOTE: we directly overwrite the pending channel ID here for
×
2720
                // this rare case since we don't have a valid pending channel
×
2721
                // ID.
×
2722
                cid.tempChanID = msg.ChanID
×
2723

×
2724
                err := fmt.Errorf("unable to find signed reservation for "+
×
2725
                        "chan_id=%x", msg.ChanID)
×
2726
                log.Warnf(err.Error())
×
2727
                f.failFundingFlow(peer, cid, err)
×
2728
                return
×
2729
        }
×
2730

2731
        peerKey := peer.IdentityKey()
30✔
2732
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
30✔
2733
        if err != nil {
30✔
2734
                log.Warnf("Unable to find reservation (peer_id:%v, "+
×
2735
                        "chan_id:%x)", peerKey, pendingChanID[:])
×
2736
                // TODO: add ErrChanNotFound?
×
2737
                f.failFundingFlow(peer, cid, err)
×
2738
                return
×
2739
        }
×
2740

2741
        if resCtx.reservation.State() != lnwallet.SentFundingCreated {
30✔
2742
                err := fmt.Errorf("unable to find reservation for chan_id=%x",
×
2743
                        msg.ChanID)
×
2744
                f.failFundingFlow(peer, cid, err)
×
2745

×
2746
                return
×
2747
        }
×
2748

2749
        // Create an entry in the local discovery map so we can ensure that we
2750
        // process the channel confirmation fully before we receive a
2751
        // channel_ready message.
2752
        fundingPoint := resCtx.reservation.FundingOutpoint()
30✔
2753
        permChanID := lnwire.NewChanIDFromOutPoint(*fundingPoint)
30✔
2754
        f.localDiscoverySignals.Store(permChanID, make(chan struct{}))
30✔
2755

30✔
2756
        // We have to store the forwardingPolicy before the reservation context
30✔
2757
        // is deleted. The policy will then be read and applied in
30✔
2758
        // newChanAnnouncement.
30✔
2759
        err = f.saveInitialForwardingPolicy(
30✔
2760
                permChanID, &resCtx.forwardingPolicy,
30✔
2761
        )
30✔
2762
        if err != nil {
30✔
2763
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2764
        }
×
2765

2766
        // For taproot channels, the commit signature is actually the partial
2767
        // signature. Otherwise, we can convert the ECDSA commit signature into
2768
        // our internal input.Signature type.
2769
        var commitSig input.Signature
30✔
2770
        if resCtx.reservation.IsTaproot() {
35✔
2771
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
5✔
2772
                if err != nil {
5✔
2773
                        f.failFundingFlow(peer, cid, err)
×
2774

×
2775
                        return
×
2776
                }
×
2777

2778
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
5✔
2779
                        &partialSig,
5✔
2780
                )
5✔
2781
        } else {
28✔
2782
                commitSig, err = msg.CommitSig.ToSignature()
28✔
2783
                if err != nil {
28✔
2784
                        log.Errorf("unable to parse signature: %v", err)
×
2785
                        f.failFundingFlow(peer, cid, err)
×
2786
                        return
×
2787
                }
×
2788
        }
2789

2790
        completeChan, err := resCtx.reservation.CompleteReservation(
30✔
2791
                nil, commitSig,
30✔
2792
        )
30✔
2793
        if err != nil {
30✔
2794
                log.Errorf("Unable to complete reservation sign "+
×
2795
                        "complete: %v", err)
×
2796
                f.failFundingFlow(peer, cid, err)
×
2797
                return
×
2798
        }
×
2799

2800
        // The channel is now marked IsPending in the database, and we can
2801
        // delete it from our set of active reservations.
2802
        f.deleteReservationCtx(peerKey, pendingChanID)
30✔
2803

30✔
2804
        // Broadcast the finalized funding transaction to the network, but only
30✔
2805
        // if we actually have the funding transaction.
30✔
2806
        if completeChan.ChanType.HasFundingTx() {
59✔
2807
                fundingTx := completeChan.FundingTxn
29✔
2808
                var fundingTxBuf bytes.Buffer
29✔
2809
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
29✔
2810
                        log.Errorf("Unable to serialize funding "+
×
2811
                                "transaction %v: %v", fundingTx.TxHash(), err)
×
2812

×
2813
                        // Clear the buffer of any bytes that were written
×
2814
                        // before the serialization error to prevent logging an
×
2815
                        // incomplete transaction.
×
2816
                        fundingTxBuf.Reset()
×
2817
                }
×
2818

2819
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
29✔
2820
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
29✔
2821

29✔
2822
                // Set a nil short channel ID at this stage because we do not
29✔
2823
                // know it until our funding tx confirms.
29✔
2824
                label := labels.MakeLabel(
29✔
2825
                        labels.LabelTypeChannelOpen, nil,
29✔
2826
                )
29✔
2827

29✔
2828
                err = f.cfg.PublishTransaction(fundingTx, label)
29✔
2829
                if err != nil {
29✔
2830
                        log.Errorf("Unable to broadcast funding tx %x for "+
×
2831
                                "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
2832
                                completeChan.FundingOutpoint, err)
×
2833

×
2834
                        // We failed to broadcast the funding transaction, but
×
2835
                        // watch the channel regardless, in case the
×
2836
                        // transaction made it to the network. We will retry
×
2837
                        // broadcast at startup.
×
2838
                        //
×
2839
                        // TODO(halseth): retry more often? Handle with CPFP?
×
2840
                        // Just delete from the DB?
×
2841
                }
×
2842
        }
2843

2844
        // Before we proceed, if we have a funding hook that wants a
2845
        // notification that it's safe to broadcast the funding transaction,
2846
        // then we'll send that now.
2847
        err = fn.MapOptionZ(
30✔
2848
                f.cfg.AuxFundingController,
30✔
2849
                func(controller AuxFundingController) error {
30✔
2850
                        return controller.ChannelFinalized(cid.tempChanID)
×
2851
                },
×
2852
        )
2853
        if err != nil {
30✔
2854
                log.Errorf("Failed to inform aux funding controller about "+
×
2855
                        "ChannelPoint(%v) being finalized: %v", fundingPoint,
×
2856
                        err)
×
2857
        }
×
2858

2859
        // Now that we have a finalized reservation for this funding flow,
2860
        // we'll send the to be active channel to the ChainArbitrator so it can
2861
        // watch for any on-chain actions before the channel has fully
2862
        // confirmed.
2863
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
30✔
2864
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2865
                        "arbitration: %v", fundingPoint, err)
×
2866
        }
×
2867

2868
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
30✔
2869
                "waiting for channel open on-chain", pendingChanID[:],
30✔
2870
                fundingPoint)
30✔
2871

30✔
2872
        // Send an update to the upstream client that the negotiation process
30✔
2873
        // is over.
30✔
2874
        upd := &lnrpc.OpenStatusUpdate{
30✔
2875
                Update: &lnrpc.OpenStatusUpdate_ChanPending{
30✔
2876
                        ChanPending: &lnrpc.PendingUpdate{
30✔
2877
                                Txid:        fundingPoint.Hash[:],
30✔
2878
                                OutputIndex: fundingPoint.Index,
30✔
2879
                        },
30✔
2880
                },
30✔
2881
                PendingChanId: pendingChanID[:],
30✔
2882
        }
30✔
2883

30✔
2884
        select {
30✔
2885
        case resCtx.updates <- upd:
30✔
2886
                // Inform the ChannelNotifier that the channel has entered
30✔
2887
                // pending open state.
30✔
2888
                f.cfg.NotifyPendingOpenChannelEvent(
30✔
2889
                        *fundingPoint, completeChan, completeChan.IdentityPub,
30✔
2890
                )
30✔
2891

2892
        case <-f.quit:
×
2893
                return
×
2894
        }
2895

2896
        // At this point we have broadcast the funding transaction and done all
2897
        // necessary processing.
2898
        f.wg.Add(1)
30✔
2899
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
30✔
2900
}
2901

2902
// confirmedChannel wraps a confirmed funding transaction, as well as the short
2903
// channel ID which identifies that channel into a single struct. We'll use
2904
// this to pass around the final state of a channel after it has been
2905
// confirmed.
2906
type confirmedChannel struct {
2907
        // shortChanID expresses where in the block the funding transaction was
2908
        // located.
2909
        shortChanID lnwire.ShortChannelID
2910

2911
        // fundingTx is the funding transaction that created the channel.
2912
        fundingTx *wire.MsgTx
2913
}
2914

2915
// fundingTimeout is called when callers of waitForFundingWithTimeout receive
2916
// an ErrConfirmationTimeout. It is used to clean-up channel state and mark the
2917
// channel as closed. The error is only returned for the responder of the
2918
// channel flow.
2919
func (f *Manager) fundingTimeout(c *channeldb.OpenChannel,
2920
        pendingID PendingChanID) error {
5✔
2921

5✔
2922
        // We'll get a timeout if the number of blocks mined since the channel
5✔
2923
        // was initiated reaches MaxWaitNumBlocksFundingConf and we are not the
5✔
2924
        // channel initiator.
5✔
2925
        localBalance := c.LocalCommitment.LocalBalance.ToSatoshis()
5✔
2926
        closeInfo := &channeldb.ChannelCloseSummary{
5✔
2927
                ChainHash:               c.ChainHash,
5✔
2928
                ChanPoint:               c.FundingOutpoint,
5✔
2929
                RemotePub:               c.IdentityPub,
5✔
2930
                Capacity:                c.Capacity,
5✔
2931
                SettledBalance:          localBalance,
5✔
2932
                CloseType:               channeldb.FundingCanceled,
5✔
2933
                RemoteCurrentRevocation: c.RemoteCurrentRevocation,
5✔
2934
                RemoteNextRevocation:    c.RemoteNextRevocation,
5✔
2935
                LocalChanConfig:         c.LocalChanCfg,
5✔
2936
        }
5✔
2937

5✔
2938
        // Close the channel with us as the initiator because we are timing the
5✔
2939
        // channel out.
5✔
2940
        if err := c.CloseChannel(
5✔
2941
                closeInfo, channeldb.ChanStatusLocalCloseInitiator,
5✔
2942
        ); err != nil {
5✔
2943
                return fmt.Errorf("failed closing channel %v: %w",
×
2944
                        c.FundingOutpoint, err)
×
2945
        }
×
2946

2947
        // Notify other subsystems about the funding timeout.
2948
        f.cfg.NotifyFundingTimeout(c.FundingOutpoint, c.IdentityPub)
5✔
2949

5✔
2950
        timeoutErr := fmt.Errorf("timeout waiting for funding tx (%v) to "+
5✔
2951
                "confirm", c.FundingOutpoint)
5✔
2952

5✔
2953
        // When the peer comes online, we'll notify it that we are now
5✔
2954
        // considering the channel flow canceled.
5✔
2955
        f.wg.Add(1)
5✔
2956
        go func() {
10✔
2957
                defer f.wg.Done()
5✔
2958

5✔
2959
                peer, err := f.waitForPeerOnline(c.IdentityPub)
5✔
2960
                switch err {
5✔
2961
                // We're already shutting down, so we can just return.
2962
                case ErrFundingManagerShuttingDown:
×
2963
                        return
×
2964

2965
                // nil error means we continue on.
2966
                case nil:
5✔
2967

2968
                // For unexpected errors, we print the error and still try to
2969
                // fail the funding flow.
2970
                default:
×
2971
                        log.Errorf("Unexpected error while waiting for peer "+
×
2972
                                "to come online: %v", err)
×
2973
                }
2974

2975
                // Create channel identifier and set the channel ID.
2976
                cid := newChanIdentifier(pendingID)
5✔
2977
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
5✔
2978

5✔
2979
                // TODO(halseth): should this send be made
5✔
2980
                // reliable?
5✔
2981

5✔
2982
                // The reservation won't exist at this point, but we'll send an
5✔
2983
                // Error message over anyways with ChanID set to pendingID.
5✔
2984
                f.failFundingFlow(peer, cid, timeoutErr)
5✔
2985
        }()
2986

2987
        return timeoutErr
5✔
2988
}
2989

2990
// waitForFundingWithTimeout is a wrapper around waitForFundingConfirmation and
2991
// waitForTimeout that will return ErrConfirmationTimeout if we are not the
2992
// channel initiator and the MaxWaitNumBlocksFundingConf has passed from the
2993
// funding broadcast height. In case of confirmation, the short channel ID of
2994
// the channel and the funding transaction will be returned.
2995
func (f *Manager) waitForFundingWithTimeout(
2996
        ch *channeldb.OpenChannel) (*confirmedChannel, error) {
60✔
2997

60✔
2998
        confChan := make(chan *confirmedChannel)
60✔
2999
        timeoutChan := make(chan error, 1)
60✔
3000
        cancelChan := make(chan struct{})
60✔
3001

60✔
3002
        f.wg.Add(1)
60✔
3003
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
60✔
3004

60✔
3005
        // If we are not the initiator, we have no money at stake and will
60✔
3006
        // timeout waiting for the funding transaction to confirm after a
60✔
3007
        // while.
60✔
3008
        if !ch.IsInitiator && !ch.IsZeroConf() {
88✔
3009
                f.wg.Add(1)
28✔
3010
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
28✔
3011
        }
28✔
3012
        defer close(cancelChan)
60✔
3013

60✔
3014
        select {
60✔
3015
        case err := <-timeoutChan:
5✔
3016
                if err != nil {
5✔
3017
                        return nil, err
×
3018
                }
×
3019
                return nil, ErrConfirmationTimeout
5✔
3020

3021
        case <-f.quit:
24✔
3022
                // The fundingManager is shutting down, and will resume wait on
24✔
3023
                // startup.
24✔
3024
                return nil, ErrFundingManagerShuttingDown
24✔
3025

3026
        case confirmedChannel, ok := <-confChan:
37✔
3027
                if !ok {
37✔
3028
                        return nil, fmt.Errorf("waiting for funding" +
×
3029
                                "confirmation failed")
×
3030
                }
×
3031
                return confirmedChannel, nil
37✔
3032
        }
3033
}
3034

3035
// makeFundingScript re-creates the funding script for the funding transaction
3036
// of the target channel.
3037
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
80✔
3038
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
80✔
3039
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
80✔
3040

80✔
3041
        if channel.ChanType.IsTaproot() {
88✔
3042
                pkScript, _, err := input.GenTaprootFundingScript(
8✔
3043
                        localKey, remoteKey, int64(channel.Capacity),
8✔
3044
                        channel.TapscriptRoot,
8✔
3045
                )
8✔
3046
                if err != nil {
8✔
3047
                        return nil, err
×
3048
                }
×
3049

3050
                return pkScript, nil
8✔
3051
        }
3052

3053
        multiSigScript, err := input.GenMultiSigScript(
75✔
3054
                localKey.SerializeCompressed(),
75✔
3055
                remoteKey.SerializeCompressed(),
75✔
3056
        )
75✔
3057
        if err != nil {
75✔
3058
                return nil, err
×
3059
        }
×
3060

3061
        return input.WitnessScriptHash(multiSigScript)
75✔
3062
}
3063

3064
// waitForFundingConfirmation handles the final stages of the channel funding
3065
// process once the funding transaction has been broadcast. The primary
3066
// function of waitForFundingConfirmation is to wait for blockchain
3067
// confirmation, and then to notify the other systems that must be notified
3068
// when a channel has become active for lightning transactions.
3069
// The wait can be canceled by closing the cancelChan. In case of success,
3070
// a *lnwire.ShortChannelID will be passed to confChan.
3071
//
3072
// NOTE: This MUST be run as a goroutine.
3073
func (f *Manager) waitForFundingConfirmation(
3074
        completeChan *channeldb.OpenChannel, cancelChan <-chan struct{},
3075
        confChan chan<- *confirmedChannel) {
60✔
3076

60✔
3077
        defer f.wg.Done()
60✔
3078
        defer close(confChan)
60✔
3079

60✔
3080
        // Register with the ChainNotifier for a notification once the funding
60✔
3081
        // transaction reaches `numConfs` confirmations.
60✔
3082
        txid := completeChan.FundingOutpoint.Hash
60✔
3083
        fundingScript, err := makeFundingScript(completeChan)
60✔
3084
        if err != nil {
60✔
3085
                log.Errorf("unable to create funding script for "+
×
3086
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3087
                        err)
×
3088
                return
×
3089
        }
×
3090
        numConfs := uint32(completeChan.NumConfsRequired)
60✔
3091

60✔
3092
        // If the underlying channel is a zero-conf channel, we'll set numConfs
60✔
3093
        // to 6, since it will be zero here.
60✔
3094
        if completeChan.IsZeroConf() {
69✔
3095
                numConfs = 6
9✔
3096
        }
9✔
3097

3098
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
60✔
3099
                &txid, fundingScript, numConfs,
60✔
3100
                completeChan.BroadcastHeight(),
60✔
3101
        )
60✔
3102
        if err != nil {
60✔
3103
                log.Errorf("Unable to register for confirmation of "+
×
3104
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3105
                        err)
×
3106
                return
×
3107
        }
×
3108

3109
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
60✔
3110
                txid, numConfs)
60✔
3111

60✔
3112
        var confDetails *chainntnfs.TxConfirmation
60✔
3113
        var ok bool
60✔
3114

60✔
3115
        // Wait until the specified number of confirmations has been reached,
60✔
3116
        // we get a cancel signal, or the wallet signals a shutdown.
60✔
3117
        select {
60✔
3118
        case confDetails, ok = <-confNtfn.Confirmed:
37✔
3119
                // fallthrough
3120

3121
        case <-cancelChan:
7✔
3122
                log.Warnf("canceled waiting for funding confirmation, "+
7✔
3123
                        "stopping funding flow for ChannelPoint(%v)",
7✔
3124
                        completeChan.FundingOutpoint)
7✔
3125
                return
7✔
3126

3127
        case <-f.quit:
22✔
3128
                log.Warnf("fundingManager shutting down, stopping funding "+
22✔
3129
                        "flow for ChannelPoint(%v)",
22✔
3130
                        completeChan.FundingOutpoint)
22✔
3131
                return
22✔
3132
        }
3133

3134
        if !ok {
37✔
3135
                log.Warnf("ChainNotifier shutting down, cannot complete "+
×
3136
                        "funding flow for ChannelPoint(%v)",
×
3137
                        completeChan.FundingOutpoint)
×
3138
                return
×
3139
        }
×
3140

3141
        fundingPoint := completeChan.FundingOutpoint
37✔
3142
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
37✔
3143
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
37✔
3144

37✔
3145
        // With the block height and the transaction index known, we can
37✔
3146
        // construct the compact chanID which is used on the network to unique
37✔
3147
        // identify channels.
37✔
3148
        shortChanID := lnwire.ShortChannelID{
37✔
3149
                BlockHeight: confDetails.BlockHeight,
37✔
3150
                TxIndex:     confDetails.TxIndex,
37✔
3151
                TxPosition:  uint16(fundingPoint.Index),
37✔
3152
        }
37✔
3153

37✔
3154
        select {
37✔
3155
        case confChan <- &confirmedChannel{
3156
                shortChanID: shortChanID,
3157
                fundingTx:   confDetails.Tx,
3158
        }:
37✔
3159
        case <-f.quit:
×
3160
                return
×
3161
        }
3162
}
3163

3164
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3165
// has passed from the broadcast height of the given channel. In case of error,
3166
// the error is sent on timeoutChan. The wait can be canceled by closing the
3167
// cancelChan.
3168
//
3169
// NOTE: timeoutChan MUST be buffered.
3170
// NOTE: This MUST be run as a goroutine.
3171
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3172
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
28✔
3173

28✔
3174
        defer f.wg.Done()
28✔
3175

28✔
3176
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
28✔
3177
        if err != nil {
28✔
3178
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3179
                        "notification: %v", err)
×
3180
                return
×
3181
        }
×
3182

3183
        defer epochClient.Cancel()
28✔
3184

28✔
3185
        // The value of waitBlocksForFundingConf is adjusted in a development
28✔
3186
        // environment to enhance test capabilities. Otherwise, it is set to
28✔
3187
        // DefaultMaxWaitNumBlocksFundingConf.
28✔
3188
        waitBlocksForFundingConf := uint32(
28✔
3189
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
28✔
3190
        )
28✔
3191

28✔
3192
        if lncfg.IsDevBuild() {
31✔
3193
                waitBlocksForFundingConf =
3✔
3194
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3195
        }
3✔
3196

3197
        // On block maxHeight we will cancel the funding confirmation wait.
3198
        broadcastHeight := completeChan.BroadcastHeight()
28✔
3199
        maxHeight := broadcastHeight + waitBlocksForFundingConf
28✔
3200
        for {
58✔
3201
                select {
30✔
3202
                case epoch, ok := <-epochClient.Epochs:
7✔
3203
                        if !ok {
7✔
3204
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3205
                                        "shutting down")
×
3206
                                return
×
3207
                        }
×
3208

3209
                        // Close the timeout channel and exit if the block is
3210
                        // above the max height.
3211
                        if uint32(epoch.Height) >= maxHeight {
12✔
3212
                                log.Warnf("Waited for %v blocks without "+
5✔
3213
                                        "seeing funding transaction confirmed,"+
5✔
3214
                                        " cancelling.",
5✔
3215
                                        waitBlocksForFundingConf)
5✔
3216

5✔
3217
                                // Notify the caller of the timeout.
5✔
3218
                                close(timeoutChan)
5✔
3219
                                return
5✔
3220
                        }
5✔
3221

3222
                        // TODO: If we are the channel initiator implement
3223
                        // a method for recovering the funds from the funding
3224
                        // transaction
3225

3226
                case <-cancelChan:
18✔
3227
                        return
18✔
3228

3229
                case <-f.quit:
11✔
3230
                        // The fundingManager is shutting down, will resume
11✔
3231
                        // waiting for the funding transaction on startup.
11✔
3232
                        return
11✔
3233
                }
3234
        }
3235
}
3236

3237
// makeLabelForTx updates the label for the confirmed funding transaction. If
3238
// we opened the channel, and lnd's wallet published our funding tx (which is
3239
// not the case for some channels) then we update our transaction label with
3240
// our short channel ID, which is known now that our funding transaction has
3241
// confirmed. We do not label transactions we did not publish, because our
3242
// wallet has no knowledge of them.
3243
func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
37✔
3244
        if c.IsInitiator && c.ChanType.HasFundingTx() {
56✔
3245
                shortChanID := c.ShortChanID()
19✔
3246

19✔
3247
                // For zero-conf channels, we'll use the actually-confirmed
19✔
3248
                // short channel id.
19✔
3249
                if c.IsZeroConf() {
24✔
3250
                        shortChanID = c.ZeroConfRealScid()
5✔
3251
                }
5✔
3252

3253
                label := labels.MakeLabel(
19✔
3254
                        labels.LabelTypeChannelOpen, &shortChanID,
19✔
3255
                )
19✔
3256

19✔
3257
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
19✔
3258
                if err != nil {
19✔
3259
                        log.Errorf("unable to update label: %v", err)
×
3260
                }
×
3261
        }
3262
}
3263

3264
// handleFundingConfirmation marks a channel as open in the database, and set
3265
// the channelOpeningState markedOpen. In addition it will report the now
3266
// decided short channel ID to the switch, and close the local discovery signal
3267
// for this channel.
3268
func (f *Manager) handleFundingConfirmation(
3269
        completeChan *channeldb.OpenChannel,
3270
        confChannel *confirmedChannel) error {
33✔
3271

33✔
3272
        fundingPoint := completeChan.FundingOutpoint
33✔
3273
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
33✔
3274

33✔
3275
        // TODO(roasbeef): ideally persistent state update for chan above
33✔
3276
        // should be abstracted
33✔
3277

33✔
3278
        // Now that that the channel has been fully confirmed, we'll request
33✔
3279
        // that the wallet fully verify this channel to ensure that it can be
33✔
3280
        // used.
33✔
3281
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
33✔
3282
        if err != nil {
33✔
3283
                // TODO(roasbeef): delete chan state?
×
3284
                return fmt.Errorf("unable to validate channel: %w", err)
×
3285
        }
×
3286

3287
        // Now that the channel has been validated, we'll persist an alias for
3288
        // this channel if the option-scid-alias feature-bit was negotiated.
3289
        if completeChan.NegotiatedAliasFeature() {
38✔
3290
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
3291
                if err != nil {
5✔
3292
                        return fmt.Errorf("unable to request alias: %w", err)
×
3293
                }
×
3294

3295
                err = f.cfg.AliasManager.AddLocalAlias(
5✔
3296
                        aliasScid, confChannel.shortChanID, true, false,
5✔
3297
                )
5✔
3298
                if err != nil {
5✔
3299
                        return fmt.Errorf("unable to request alias: %w", err)
×
3300
                }
×
3301
        }
3302

3303
        // The funding transaction now being confirmed, we add this channel to
3304
        // the fundingManager's internal persistent state machine that we use
3305
        // to track the remaining process of the channel opening. This is
3306
        // useful to resume the opening process in case of restarts. We set the
3307
        // opening state before we mark the channel opened in the database,
3308
        // such that we can receover from one of the db writes failing.
3309
        err = f.saveChannelOpeningState(
33✔
3310
                &fundingPoint, markedOpen, &confChannel.shortChanID,
33✔
3311
        )
33✔
3312
        if err != nil {
33✔
3313
                return fmt.Errorf("error setting channel state to "+
×
3314
                        "markedOpen: %v", err)
×
3315
        }
×
3316

3317
        // Now that the channel has been fully confirmed and we successfully
3318
        // saved the opening state, we'll mark it as open within the database.
3319
        err = completeChan.MarkAsOpen(confChannel.shortChanID)
33✔
3320
        if err != nil {
33✔
3321
                return fmt.Errorf("error setting channel pending flag to "+
×
3322
                        "false:        %v", err)
×
3323
        }
×
3324

3325
        // Update the confirmed funding transaction label.
3326
        f.makeLabelForTx(completeChan)
33✔
3327

33✔
3328
        // Inform the ChannelNotifier that the channel has transitioned from
33✔
3329
        // pending open to open.
33✔
3330
        f.cfg.NotifyOpenChannelEvent(
33✔
3331
                completeChan.FundingOutpoint, completeChan.IdentityPub,
33✔
3332
        )
33✔
3333

33✔
3334
        // Close the discoverySignal channel, indicating to a separate
33✔
3335
        // goroutine that the channel now is marked as open in the database
33✔
3336
        // and that it is acceptable to process channel_ready messages
33✔
3337
        // from the peer.
33✔
3338
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
66✔
3339
                close(discoverySignal)
33✔
3340
        }
33✔
3341

3342
        return nil
33✔
3343
}
3344

3345
// sendChannelReady creates and sends the channelReady message.
3346
// This should be called after the funding transaction has been confirmed,
3347
// and the channelState is 'markedOpen'.
3348
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3349
        channel *lnwallet.LightningChannel) error {
38✔
3350

38✔
3351
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
38✔
3352

38✔
3353
        var peerKey [33]byte
38✔
3354
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
38✔
3355

38✔
3356
        // Next, we'll send over the channel_ready message which marks that we
38✔
3357
        // consider the channel open by presenting the remote party with our
38✔
3358
        // next revocation key. Without the revocation key, the remote party
38✔
3359
        // will be unable to propose state transitions.
38✔
3360
        nextRevocation, err := channel.NextRevocationKey()
38✔
3361
        if err != nil {
38✔
3362
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3363
        }
×
3364
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
38✔
3365

38✔
3366
        // If this is a taproot channel, then we also need to send along our
38✔
3367
        // set of musig2 nonces as well.
38✔
3368
        if completeChan.ChanType.IsTaproot() {
45✔
3369
                log.Infof("ChanID(%v): generating musig2 nonces...",
7✔
3370
                        chanID)
7✔
3371

7✔
3372
                f.nonceMtx.Lock()
7✔
3373
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
3374
                if !ok {
14✔
3375
                        // If we don't have any nonces generated yet for this
7✔
3376
                        // first state, then we'll generate them now and stow
7✔
3377
                        // them away.  When we receive the funding locked
7✔
3378
                        // message, we'll then pass along this same set of
7✔
3379
                        // nonces.
7✔
3380
                        newNonce, err := channel.GenMusigNonces()
7✔
3381
                        if err != nil {
7✔
3382
                                f.nonceMtx.Unlock()
×
3383
                                return err
×
3384
                        }
×
3385

3386
                        // Now that we've generated the nonce for this channel,
3387
                        // we'll store it in the set of pending nonces.
3388
                        localNonce = newNonce
7✔
3389
                        f.pendingMusigNonces[chanID] = localNonce
7✔
3390
                }
3391
                f.nonceMtx.Unlock()
7✔
3392

7✔
3393
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
7✔
3394
                        localNonce.PubNonce,
7✔
3395
                )
7✔
3396
        }
3397

3398
        // If the channel negotiated the option-scid-alias feature bit, we'll
3399
        // send a TLV segment that includes an alias the peer can use in their
3400
        // invoice hop hints. We'll send the first alias we find for the
3401
        // channel since it does not matter which alias we send. We'll error
3402
        // out in the odd case that no aliases are found.
3403
        if completeChan.NegotiatedAliasFeature() {
47✔
3404
                aliases := f.cfg.AliasManager.GetAliases(
9✔
3405
                        completeChan.ShortChanID(),
9✔
3406
                )
9✔
3407
                if len(aliases) == 0 {
9✔
3408
                        return fmt.Errorf("no aliases found")
×
3409
                }
×
3410

3411
                // We can use a pointer to aliases since GetAliases returns a
3412
                // copy of the alias slice.
3413
                channelReadyMsg.AliasScid = &aliases[0]
9✔
3414
        }
3415

3416
        // If the peer has disconnected before we reach this point, we will need
3417
        // to wait for him to come back online before sending the channelReady
3418
        // message. This is special for channelReady, since failing to send any
3419
        // of the previous messages in the funding flow just cancels the flow.
3420
        // But now the funding transaction is confirmed, the channel is open
3421
        // and we have to make sure the peer gets the channelReady message when
3422
        // it comes back online. This is also crucial during restart of lnd,
3423
        // where we might try to resend the channelReady message before the
3424
        // server has had the time to connect to the peer. We keep trying to
3425
        // send channelReady until we succeed, or the fundingManager is shut
3426
        // down.
3427
        for {
76✔
3428
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
38✔
3429
                if err != nil {
39✔
3430
                        return err
1✔
3431
                }
1✔
3432

3433
                localAlias := peer.LocalFeatures().HasFeature(
37✔
3434
                        lnwire.ScidAliasOptional,
37✔
3435
                )
37✔
3436
                remoteAlias := peer.RemoteFeatures().HasFeature(
37✔
3437
                        lnwire.ScidAliasOptional,
37✔
3438
                )
37✔
3439

37✔
3440
                // We could also refresh the channel state instead of checking
37✔
3441
                // whether the feature was negotiated, but this saves us a
37✔
3442
                // database read.
37✔
3443
                if channelReadyMsg.AliasScid == nil && localAlias &&
37✔
3444
                        remoteAlias {
37✔
3445

×
3446
                        // If an alias was not assigned above and the scid
×
3447
                        // alias feature was negotiated, check if we already
×
3448
                        // have an alias stored in case handleChannelReady was
×
3449
                        // called before this. If an alias exists, use that in
×
3450
                        // channel_ready. Otherwise, request and store an
×
3451
                        // alias and use that.
×
3452
                        aliases := f.cfg.AliasManager.GetAliases(
×
3453
                                completeChan.ShortChannelID,
×
3454
                        )
×
3455
                        if len(aliases) == 0 {
×
3456
                                // No aliases were found.
×
3457
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3458
                                if err != nil {
×
3459
                                        return err
×
3460
                                }
×
3461

3462
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3463
                                        alias, completeChan.ShortChannelID,
×
3464
                                        false, false,
×
3465
                                )
×
3466
                                if err != nil {
×
3467
                                        return err
×
3468
                                }
×
3469

3470
                                channelReadyMsg.AliasScid = &alias
×
3471
                        } else {
×
3472
                                channelReadyMsg.AliasScid = &aliases[0]
×
3473
                        }
×
3474
                }
3475

3476
                log.Infof("Peer(%x) is online, sending ChannelReady "+
37✔
3477
                        "for ChannelID(%v)", peerKey, chanID)
37✔
3478

37✔
3479
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
74✔
3480
                        // Sending succeeded, we can break out and continue the
37✔
3481
                        // funding flow.
37✔
3482
                        break
37✔
3483
                }
3484

3485
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3486
                        "Will retry when online", peerKey, err)
×
3487
        }
3488

3489
        return nil
37✔
3490
}
3491

3492
// receivedChannelReady checks whether or not we've received a ChannelReady
3493
// from the remote peer. If we have, RemoteNextRevocation will be set.
3494
func (f *Manager) receivedChannelReady(node *btcec.PublicKey,
3495
        chanID lnwire.ChannelID) (bool, error) {
62✔
3496

62✔
3497
        // If the funding manager has exited, return an error to stop looping.
62✔
3498
        // Note that the peer may appear as online while the funding manager
62✔
3499
        // has stopped due to the shutdown order in the server.
62✔
3500
        select {
62✔
3501
        case <-f.quit:
×
3502
                return false, ErrFundingManagerShuttingDown
×
3503
        default:
62✔
3504
        }
3505

3506
        // Avoid a tight loop if peer is offline.
3507
        if _, err := f.waitForPeerOnline(node); err != nil {
62✔
3508
                log.Errorf("Wait for peer online failed: %v", err)
×
3509
                return false, err
×
3510
        }
×
3511

3512
        // If we cannot find the channel, then we haven't processed the
3513
        // remote's channelReady message.
3514
        channel, err := f.cfg.FindChannel(node, chanID)
62✔
3515
        if err != nil {
62✔
3516
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3517
                        "ChannelReady was received", chanID)
×
3518
                return false, err
×
3519
        }
×
3520

3521
        // If we haven't insert the next revocation point, we haven't finished
3522
        // processing the channel ready message.
3523
        if channel.RemoteNextRevocation == nil {
99✔
3524
                return false, nil
37✔
3525
        }
37✔
3526

3527
        // Finally, the barrier signal is removed once we finish
3528
        // `handleChannelReady`. If we can still find the signal, we haven't
3529
        // finished processing it yet.
3530
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
28✔
3531

28✔
3532
        return !loaded, nil
28✔
3533
}
3534

3535
// extractAnnounceParams extracts the various channel announcement and update
3536
// parameters that will be needed to construct a ChannelAnnouncement and a
3537
// ChannelUpdate.
3538
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3539
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
29✔
3540

29✔
3541
        // We'll obtain the min HTLC value we can forward in our direction, as
29✔
3542
        // we'll use this value within our ChannelUpdate. This constraint is
29✔
3543
        // originally set by the remote node, as it will be the one that will
29✔
3544
        // need to determine the smallest HTLC it deems economically relevant.
29✔
3545
        fwdMinHTLC := c.LocalChanCfg.MinHTLC
29✔
3546

29✔
3547
        // We don't necessarily want to go as low as the remote party allows.
29✔
3548
        // Check it against our default forwarding policy.
29✔
3549
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
32✔
3550
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3551
        }
3✔
3552

3553
        // We'll obtain the max HTLC value we can forward in our direction, as
3554
        // we'll use this value within our ChannelUpdate. This value must be <=
3555
        // channel capacity and <= the maximum in-flight msats set by the peer.
3556
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
29✔
3557
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
29✔
3558
        if fwdMaxHTLC > capacityMSat {
29✔
3559
                fwdMaxHTLC = capacityMSat
×
3560
        }
×
3561

3562
        return fwdMinHTLC, fwdMaxHTLC
29✔
3563
}
3564

3565
// addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
3566
// gossiper so that the channel is added to the graph builder's internal graph.
3567
// These announcement messages are NOT broadcasted to the greater network,
3568
// only to the channel counter party. The proofs required to announce the
3569
// channel to the greater network will be created and sent in annAfterSixConfs.
3570
// The peerAlias is used for zero-conf channels to give the counter-party a
3571
// ChannelUpdate they understand. ourPolicy may be set for various
3572
// option-scid-alias channels to re-use the same policy.
3573
func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
3574
        shortChanID *lnwire.ShortChannelID,
3575
        peerAlias *lnwire.ShortChannelID,
3576
        ourPolicy *models.ChannelEdgePolicy) error {
29✔
3577

29✔
3578
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
29✔
3579

29✔
3580
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
29✔
3581

29✔
3582
        ann, err := f.newChanAnnouncement(
29✔
3583
                f.cfg.IDKey, completeChan.IdentityPub,
29✔
3584
                &completeChan.LocalChanCfg.MultiSigKey,
29✔
3585
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
29✔
3586
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
29✔
3587
                completeChan.ChanType,
29✔
3588
        )
29✔
3589
        if err != nil {
29✔
3590
                return fmt.Errorf("error generating channel "+
×
3591
                        "announcement: %v", err)
×
3592
        }
×
3593

3594
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3595
        // to the Router's topology.
3596
        errChan := f.cfg.SendAnnouncement(
29✔
3597
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
29✔
3598
                discovery.ChannelPoint(completeChan.FundingOutpoint),
29✔
3599
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
29✔
3600
        )
29✔
3601
        select {
29✔
3602
        case err := <-errChan:
29✔
3603
                if err != nil {
29✔
3604
                        if graph.IsError(err, graph.ErrOutdated,
×
3605
                                graph.ErrIgnored) {
×
3606

×
3607
                                log.Debugf("Graph rejected "+
×
3608
                                        "ChannelAnnouncement: %v", err)
×
3609
                        } else {
×
3610
                                return fmt.Errorf("error sending channel "+
×
3611
                                        "announcement: %v", err)
×
3612
                        }
×
3613
                }
3614
        case <-f.quit:
×
3615
                return ErrFundingManagerShuttingDown
×
3616
        }
3617

3618
        errChan = f.cfg.SendAnnouncement(
29✔
3619
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
29✔
3620
        )
29✔
3621
        select {
29✔
3622
        case err := <-errChan:
29✔
3623
                if err != nil {
29✔
3624
                        if graph.IsError(err, graph.ErrOutdated,
×
3625
                                graph.ErrIgnored) {
×
3626

×
3627
                                log.Debugf("Graph rejected "+
×
3628
                                        "ChannelUpdate: %v", err)
×
3629
                        } else {
×
3630
                                return fmt.Errorf("error sending channel "+
×
3631
                                        "update: %v", err)
×
3632
                        }
×
3633
                }
3634
        case <-f.quit:
×
3635
                return ErrFundingManagerShuttingDown
×
3636
        }
3637

3638
        return nil
29✔
3639
}
3640

3641
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3642
// the network after 6 confs. Should be called after the channelReady message
3643
// is sent and the channel is added to the graph (channelState is
3644
// 'addedToGraph') and the channel is ready to be used. This is the last
3645
// step in the channel opening process, and the opening state will be deleted
3646
// from the database if successful.
3647
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3648
        shortChanID *lnwire.ShortChannelID) error {
29✔
3649

29✔
3650
        // If this channel is not meant to be announced to the greater network,
29✔
3651
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
29✔
3652
        // don't leak any of our information.
29✔
3653
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
29✔
3654
        if !announceChan {
40✔
3655
                log.Debugf("Will not announce private channel %v.",
11✔
3656
                        shortChanID.ToUint64())
11✔
3657

11✔
3658
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
11✔
3659
                if err != nil {
11✔
3660
                        return err
×
3661
                }
×
3662

3663
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
11✔
3664
                if err != nil {
11✔
3665
                        return fmt.Errorf("unable to retrieve current node "+
×
3666
                                "announcement: %v", err)
×
3667
                }
×
3668

3669
                chanID := lnwire.NewChanIDFromOutPoint(
11✔
3670
                        completeChan.FundingOutpoint,
11✔
3671
                )
11✔
3672
                pubKey := peer.PubKey()
11✔
3673
                log.Debugf("Sending our NodeAnnouncement for "+
11✔
3674
                        "ChannelID(%v) to %x", chanID, pubKey)
11✔
3675

11✔
3676
                // TODO(halseth): make reliable. If the peer is not online this
11✔
3677
                // will fail, and the opening process will stop. Should instead
11✔
3678
                // block here, waiting for the peer to come online.
11✔
3679
                if err := peer.SendMessage(true, &nodeAnn); err != nil {
11✔
3680
                        return fmt.Errorf("unable to send node announcement "+
×
3681
                                "to peer %x: %v", pubKey, err)
×
3682
                }
×
3683
        } else {
21✔
3684
                // Otherwise, we'll wait until the funding transaction has
21✔
3685
                // reached 6 confirmations before announcing it.
21✔
3686
                numConfs := uint32(completeChan.NumConfsRequired)
21✔
3687
                if numConfs < 6 {
42✔
3688
                        numConfs = 6
21✔
3689
                }
21✔
3690
                txid := completeChan.FundingOutpoint.Hash
21✔
3691
                log.Debugf("Will announce channel %v after ChannelPoint"+
21✔
3692
                        "(%v) has gotten %d confirmations",
21✔
3693
                        shortChanID.ToUint64(), completeChan.FundingOutpoint,
21✔
3694
                        numConfs)
21✔
3695

21✔
3696
                fundingScript, err := makeFundingScript(completeChan)
21✔
3697
                if err != nil {
21✔
3698
                        return fmt.Errorf("unable to create funding script "+
×
3699
                                "for ChannelPoint(%v): %v",
×
3700
                                completeChan.FundingOutpoint, err)
×
3701
                }
×
3702

3703
                // Register with the ChainNotifier for a notification once the
3704
                // funding transaction reaches at least 6 confirmations.
3705
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
21✔
3706
                        &txid, fundingScript, numConfs,
21✔
3707
                        completeChan.BroadcastHeight(),
21✔
3708
                )
21✔
3709
                if err != nil {
21✔
3710
                        return fmt.Errorf("unable to register for "+
×
3711
                                "confirmation of ChannelPoint(%v): %v",
×
3712
                                completeChan.FundingOutpoint, err)
×
3713
                }
×
3714

3715
                // Wait until 6 confirmations has been reached or the wallet
3716
                // signals a shutdown.
3717
                select {
21✔
3718
                case _, ok := <-confNtfn.Confirmed:
19✔
3719
                        if !ok {
19✔
3720
                                return fmt.Errorf("ChainNotifier shutting "+
×
3721
                                        "down, cannot complete funding flow "+
×
3722
                                        "for ChannelPoint(%v)",
×
3723
                                        completeChan.FundingOutpoint)
×
3724
                        }
×
3725
                        // Fallthrough.
3726

3727
                case <-f.quit:
5✔
3728
                        return fmt.Errorf("%v, stopping funding flow for "+
5✔
3729
                                "ChannelPoint(%v)",
5✔
3730
                                ErrFundingManagerShuttingDown,
5✔
3731
                                completeChan.FundingOutpoint)
5✔
3732
                }
3733

3734
                fundingPoint := completeChan.FundingOutpoint
19✔
3735
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
19✔
3736

19✔
3737
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
19✔
3738
                        &fundingPoint, shortChanID)
19✔
3739

19✔
3740
                // If this is a non-zero-conf option-scid-alias channel, we'll
19✔
3741
                // delete the mappings the gossiper uses so that ChannelUpdates
19✔
3742
                // with aliases won't be accepted. This is done elsewhere for
19✔
3743
                // zero-conf channels.
19✔
3744
                isScidFeature := completeChan.NegotiatedAliasFeature()
19✔
3745
                isZeroConf := completeChan.IsZeroConf()
19✔
3746
                if isScidFeature && !isZeroConf {
22✔
3747
                        baseScid := completeChan.ShortChanID()
3✔
3748
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
3✔
3749
                        if err != nil {
3✔
3750
                                return fmt.Errorf("failed deleting six confs "+
×
3751
                                        "maps: %v", err)
×
3752
                        }
×
3753

3754
                        // We'll delete the edge and add it again via
3755
                        // addToGraph. This is because the peer may have
3756
                        // sent us a ChannelUpdate with an alias and we don't
3757
                        // want to relay this.
3758
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
3✔
3759
                        if err != nil {
3✔
3760
                                return fmt.Errorf("failed deleting real edge "+
×
3761
                                        "for alias channel from graph: %v",
×
3762
                                        err)
×
3763
                        }
×
3764

3765
                        err = f.addToGraph(
3✔
3766
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3767
                        )
3✔
3768
                        if err != nil {
3✔
3769
                                return fmt.Errorf("failed to re-add to "+
×
3770
                                        "graph: %v", err)
×
3771
                        }
×
3772
                }
3773

3774
                // Create and broadcast the proofs required to make this channel
3775
                // public and usable for other nodes for routing.
3776
                err = f.announceChannel(
19✔
3777
                        f.cfg.IDKey, completeChan.IdentityPub,
19✔
3778
                        &completeChan.LocalChanCfg.MultiSigKey,
19✔
3779
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
19✔
3780
                        *shortChanID, chanID, completeChan.ChanType,
19✔
3781
                )
19✔
3782
                if err != nil {
22✔
3783
                        return fmt.Errorf("channel announcement failed: %w",
3✔
3784
                                err)
3✔
3785
                }
3✔
3786

3787
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
19✔
3788
                        "sent to gossiper", &fundingPoint, shortChanID)
19✔
3789
        }
3790

3791
        return nil
27✔
3792
}
3793

3794
// waitForZeroConfChannel is called when the state is addedToGraph with
3795
// a zero-conf channel. This will wait for the real confirmation, add the
3796
// confirmed SCID to the router graph, and then announce after six confs.
3797
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
9✔
3798
        // First we'll check whether the channel is confirmed on-chain. If it
9✔
3799
        // is already confirmed, the chainntnfs subsystem will return with the
9✔
3800
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
9✔
3801
        confChan, err := f.waitForFundingWithTimeout(c)
9✔
3802
        if err != nil {
14✔
3803
                return fmt.Errorf("error waiting for zero-conf funding "+
5✔
3804
                        "confirmation for ChannelPoint(%v): %v",
5✔
3805
                        c.FundingOutpoint, err)
5✔
3806
        }
5✔
3807

3808
        // We'll need to refresh the channel state so that things are properly
3809
        // populated when validating the channel state. Otherwise, a panic may
3810
        // occur due to inconsistency in the OpenChannel struct.
3811
        err = c.Refresh()
7✔
3812
        if err != nil {
10✔
3813
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3814
        }
3✔
3815

3816
        // Now that we have the confirmed transaction and the proper SCID,
3817
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3818
        // formatted.
3819
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
7✔
3820
        if err != nil {
7✔
3821
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3822
                        "%v", err)
×
3823
        }
×
3824

3825
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3826
        // the database and refresh the OpenChannel struct with it.
3827
        err = c.MarkRealScid(confChan.shortChanID)
7✔
3828
        if err != nil {
7✔
3829
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3830
                        "channel: %v", err)
×
3831
        }
×
3832

3833
        // Six confirmations have been reached. If this channel is public,
3834
        // we'll delete some of the alias mappings the gossiper uses.
3835
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
7✔
3836
        if isPublic {
12✔
3837
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
5✔
3838
                if err != nil {
5✔
3839
                        return fmt.Errorf("unable to delete base alias after "+
×
3840
                                "six confirmations: %v", err)
×
3841
                }
×
3842

3843
                // TODO: Make this atomic!
3844
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
5✔
3845
                if err != nil {
5✔
3846
                        return fmt.Errorf("unable to delete alias edge from "+
×
3847
                                "graph: %v", err)
×
3848
                }
×
3849

3850
                // We'll need to update the graph with the new ShortChannelID
3851
                // via an addToGraph call. We don't pass in the peer's
3852
                // alias since we'll be using the confirmed SCID from now on
3853
                // regardless if it's public or not.
3854
                err = f.addToGraph(
5✔
3855
                        c, &confChan.shortChanID, nil, ourPolicy,
5✔
3856
                )
5✔
3857
                if err != nil {
5✔
3858
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3859
                                "SCID to graph: %v", err)
×
3860
                }
×
3861
        }
3862

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

3876
        // Update the confirmed transaction's label.
3877
        f.makeLabelForTx(c)
7✔
3878

7✔
3879
        return nil
7✔
3880
}
3881

3882
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3883
// is the verification nonce for the state created for us after the initial
3884
// commitment transaction signed as part of the funding flow.
3885
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3886
) (*musig2.Nonces, error) {
7✔
3887

7✔
3888
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
7✔
3889
                channel.RevocationProducer,
7✔
3890
        )
7✔
3891
        if err != nil {
7✔
3892
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3893
                        "nonces: %v", err)
×
3894
        }
×
3895

3896
        // We use the _next_ commitment height here as we need to generate the
3897
        // nonce for the next state the remote party will sign for us.
3898
        verNonce, err := channeldb.NewMusigVerificationNonce(
7✔
3899
                channel.LocalChanCfg.MultiSigKey.PubKey,
7✔
3900
                channel.LocalCommitment.CommitHeight+1,
7✔
3901
                musig2ShaChain,
7✔
3902
        )
7✔
3903
        if err != nil {
7✔
3904
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3905
                        "nonces: %v", err)
×
3906
        }
×
3907

3908
        return verNonce, nil
7✔
3909
}
3910

3911
// handleChannelReady finalizes the channel funding process and enables the
3912
// channel to enter normal operating mode.
3913
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3914
        msg *lnwire.ChannelReady) {
31✔
3915

31✔
3916
        defer f.wg.Done()
31✔
3917

31✔
3918
        // If we are in development mode, we'll wait for specified duration
31✔
3919
        // before processing the channel ready message.
31✔
3920
        if f.cfg.Dev != nil {
34✔
3921
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
3922
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
3923
                        "channel_ready", msg.ChanID, duration)
3✔
3924

3✔
3925
                select {
3✔
3926
                case <-time.After(duration):
3✔
3927
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
3928
                                "channel_ready", msg.ChanID, duration)
3✔
3929
                case <-f.quit:
×
3930
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
3931
                        return
×
3932
                }
3933
        }
3934

3935
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
31✔
3936
                "peer %x", msg.ChanID,
31✔
3937
                peer.IdentityKey().SerializeCompressed())
31✔
3938

31✔
3939
        // We now load or create a new channel barrier for this channel.
31✔
3940
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
31✔
3941
                msg.ChanID, struct{}{},
31✔
3942
        )
31✔
3943

31✔
3944
        // If we are currently in the process of handling a channel_ready
31✔
3945
        // message for this channel, ignore.
31✔
3946
        if loaded {
35✔
3947
                log.Infof("Already handling channelReady for "+
4✔
3948
                        "ChannelID(%v), ignoring.", msg.ChanID)
4✔
3949
                return
4✔
3950
        }
4✔
3951

3952
        // If not already handling channelReady for this channel, then the
3953
        // `LoadOrStore` has set up a barrier, and it will be removed once this
3954
        // function exits.
3955
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
30✔
3956

30✔
3957
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
30✔
3958
        if ok {
58✔
3959
                // Before we proceed with processing the channel_ready
28✔
3960
                // message, we'll wait for the local waitForFundingConfirmation
28✔
3961
                // goroutine to signal that it has the necessary state in
28✔
3962
                // place. Otherwise, we may be missing critical information
28✔
3963
                // required to handle forwarded HTLC's.
28✔
3964
                select {
28✔
3965
                case <-localDiscoverySignal:
28✔
3966
                        // Fallthrough
3967
                case <-f.quit:
3✔
3968
                        return
3✔
3969
                }
3970

3971
                // With the signal received, we can now safely delete the entry
3972
                // from the map.
3973
                f.localDiscoverySignals.Delete(msg.ChanID)
28✔
3974
        }
3975

3976
        // First, we'll attempt to locate the channel whose funding workflow is
3977
        // being finalized by this message. We go to the database rather than
3978
        // our reservation map as we may have restarted, mid funding flow. Also
3979
        // provide the node's public key to make the search faster.
3980
        chanID := msg.ChanID
30✔
3981
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
30✔
3982
        if err != nil {
30✔
3983
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
3984
                        "funding", chanID)
×
3985
                return
×
3986
        }
×
3987

3988
        // If this is a taproot channel, then we can generate the set of nonces
3989
        // the remote party needs to send the next remote commitment here.
3990
        var firstVerNonce *musig2.Nonces
30✔
3991
        if channel.ChanType.IsTaproot() {
37✔
3992
                firstVerNonce, err = genFirstStateMusigNonce(channel)
7✔
3993
                if err != nil {
7✔
3994
                        log.Error(err)
×
3995
                        return
×
3996
                }
×
3997
        }
3998

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

4016
                // We'll store the AliasScid so that invoice creation can use
4017
                // it.
4018
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
9✔
4019
                if err != nil {
9✔
4020
                        log.Errorf("unable to store peer's alias: %v", err)
×
4021
                        return
×
4022
                }
×
4023

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

4041
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4042
                                alias, channel.ShortChannelID, false, false,
×
4043
                        )
×
4044
                        if err != nil {
×
4045
                                log.Errorf("unable to add local alias: %v",
×
4046
                                        err)
×
4047
                                return
×
4048
                        }
×
4049

4050
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4051
                        if err != nil {
×
4052
                                log.Errorf("unable to fetch second "+
×
4053
                                        "commitment point: %v", err)
×
4054
                                return
×
4055
                        }
×
4056

4057
                        channelReadyMsg := lnwire.NewChannelReady(
×
4058
                                chanID, secondPoint,
×
4059
                        )
×
4060
                        channelReadyMsg.AliasScid = &alias
×
4061

×
4062
                        if firstVerNonce != nil {
×
4063
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4064
                                        firstVerNonce.PubNonce,
×
4065
                                )
×
4066
                        }
×
4067

4068
                        err = peer.SendMessage(true, channelReadyMsg)
×
4069
                        if err != nil {
×
4070
                                log.Errorf("unable to send channel_ready: %v",
×
4071
                                        err)
×
4072
                                return
×
4073
                        }
×
4074
                }
4075
        }
4076

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

4092
        // If this is a taproot channel, then we'll need to map the received
4093
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4094
        // required in order to make the channel whole.
4095
        var chanOpts []lnwallet.ChannelOpt
29✔
4096
        if channel.ChanType.IsTaproot() {
36✔
4097
                f.nonceMtx.Lock()
7✔
4098
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
4099
                if !ok {
10✔
4100
                        // If there's no pending nonce for this channel ID,
3✔
4101
                        // we'll use the one generated above.
3✔
4102
                        localNonce = firstVerNonce
3✔
4103
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4104
                }
3✔
4105
                f.nonceMtx.Unlock()
7✔
4106

7✔
4107
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
7✔
4108
                        chanID)
7✔
4109

7✔
4110
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
7✔
4111
                        errNoLocalNonce,
7✔
4112
                )
7✔
4113
                if err != nil {
7✔
4114
                        cid := newChanIdentifier(msg.ChanID)
×
4115
                        f.sendWarning(peer, cid, err)
×
4116

×
4117
                        return
×
4118
                }
×
4119

4120
                chanOpts = append(
7✔
4121
                        chanOpts,
7✔
4122
                        lnwallet.WithLocalMusigNonces(localNonce),
7✔
4123
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
7✔
4124
                                PubNonce: remoteNonce,
7✔
4125
                        }),
7✔
4126
                )
7✔
4127

7✔
4128
                // Inform the aux funding controller that the liquidity in the
7✔
4129
                // custom channel is now ready to be advertised. We potentially
7✔
4130
                // haven't sent our own channel ready message yet, but other
7✔
4131
                // than that the channel is ready to count toward available
7✔
4132
                // liquidity.
7✔
4133
                err = fn.MapOptionZ(
7✔
4134
                        f.cfg.AuxFundingController,
7✔
4135
                        func(controller AuxFundingController) error {
7✔
4136
                                return controller.ChannelReady(
×
4137
                                        lnwallet.NewAuxChanState(channel),
×
4138
                                )
×
4139
                        },
×
4140
                )
4141
                if err != nil {
7✔
4142
                        cid := newChanIdentifier(msg.ChanID)
×
4143
                        f.sendWarning(peer, cid, err)
×
4144

×
4145
                        return
×
4146
                }
×
4147
        }
4148

4149
        // The channel_ready message contains the next commitment point we'll
4150
        // need to create the next commitment state for the remote party. So
4151
        // we'll insert that into the channel now before passing it along to
4152
        // other sub-systems.
4153
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
29✔
4154
        if err != nil {
29✔
4155
                log.Errorf("unable to insert next commitment point: %v", err)
×
4156
                return
×
4157
        }
×
4158

4159
        // Before we can add the channel to the peer, we'll need to ensure that
4160
        // we have an initial forwarding policy set.
4161
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
29✔
4162
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4163
                        err)
×
4164
        }
×
4165

4166
        err = peer.AddNewChannel(&lnpeer.NewChannel{
29✔
4167
                OpenChannel: channel,
29✔
4168
                ChanOpts:    chanOpts,
29✔
4169
        }, f.quit)
29✔
4170
        if err != nil {
29✔
4171
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4172
                        channel.FundingOutpoint,
×
4173
                        peer.IdentityKey().SerializeCompressed(), err,
×
4174
                )
×
4175
        }
×
4176
}
4177

4178
// handleChannelReadyReceived is called once the remote's channelReady message
4179
// is received and processed. At this stage, we must have sent out our
4180
// channelReady message, once the remote's channelReady is processed, the
4181
// channel is now active, thus we change its state to `addedToGraph` to
4182
// let the channel start handling routing.
4183
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4184
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4185
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
27✔
4186

27✔
4187
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
27✔
4188

27✔
4189
        // Since we've sent+received funding locked at this point, we
27✔
4190
        // can clean up the pending musig2 nonce state.
27✔
4191
        f.nonceMtx.Lock()
27✔
4192
        delete(f.pendingMusigNonces, chanID)
27✔
4193
        f.nonceMtx.Unlock()
27✔
4194

27✔
4195
        var peerAlias *lnwire.ShortChannelID
27✔
4196
        if channel.IsZeroConf() {
34✔
4197
                // We'll need to wait until channel_ready has been received and
7✔
4198
                // the peer lets us know the alias they want to use for the
7✔
4199
                // channel. With this information, we can then construct a
7✔
4200
                // ChannelUpdate for them.  If an alias does not yet exist,
7✔
4201
                // we'll just return, letting the next iteration of the loop
7✔
4202
                // check again.
7✔
4203
                var defaultAlias lnwire.ShortChannelID
7✔
4204
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
7✔
4205
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
7✔
4206
                if foundAlias == defaultAlias {
7✔
4207
                        return nil
×
4208
                }
×
4209

4210
                peerAlias = &foundAlias
7✔
4211
        }
4212

4213
        err := f.addToGraph(channel, scid, peerAlias, nil)
27✔
4214
        if err != nil {
27✔
4215
                return fmt.Errorf("failed adding to graph: %w", err)
×
4216
        }
×
4217

4218
        // As the channel is now added to the ChannelRouter's topology, the
4219
        // channel is moved to the next state of the state machine. It will be
4220
        // moved to the last state (actually deleted from the database) after
4221
        // the channel is finally announced.
4222
        err = f.saveChannelOpeningState(
27✔
4223
                &channel.FundingOutpoint, addedToGraph, scid,
27✔
4224
        )
27✔
4225
        if err != nil {
27✔
4226
                return fmt.Errorf("error setting channel state to"+
×
4227
                        " addedToGraph: %w", err)
×
4228
        }
×
4229

4230
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
4231
                "added to graph", chanID, scid)
27✔
4232

27✔
4233
        err = fn.MapOptionZ(
27✔
4234
                f.cfg.AuxFundingController,
27✔
4235
                func(controller AuxFundingController) error {
27✔
4236
                        return controller.ChannelReady(
×
4237
                                lnwallet.NewAuxChanState(channel),
×
4238
                        )
×
4239
                },
×
4240
        )
4241
        if err != nil {
27✔
4242
                return fmt.Errorf("failed notifying aux funding controller "+
×
4243
                        "about channel ready: %w", err)
×
4244
        }
×
4245

4246
        // Give the caller a final update notifying them that the channel is
4247
        fundingPoint := channel.FundingOutpoint
27✔
4248
        cp := &lnrpc.ChannelPoint{
27✔
4249
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
27✔
4250
                        FundingTxidBytes: fundingPoint.Hash[:],
27✔
4251
                },
27✔
4252
                OutputIndex: fundingPoint.Index,
27✔
4253
        }
27✔
4254

27✔
4255
        if updateChan != nil {
40✔
4256
                upd := &lnrpc.OpenStatusUpdate{
13✔
4257
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
13✔
4258
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
13✔
4259
                                        ChannelPoint: cp,
13✔
4260
                                },
13✔
4261
                        },
13✔
4262
                        PendingChanId: pendingChanID[:],
13✔
4263
                }
13✔
4264

13✔
4265
                select {
13✔
4266
                case updateChan <- upd:
13✔
4267
                case <-f.quit:
×
4268
                        return ErrFundingManagerShuttingDown
×
4269
                }
4270
        }
4271

4272
        return nil
27✔
4273
}
4274

4275
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4276
// policy set for the given channel. If we don't, we'll fall back to the default
4277
// values.
4278
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4279
        channel *channeldb.OpenChannel) error {
29✔
4280

29✔
4281
        // Before we can add the channel to the peer, we'll need to ensure that
29✔
4282
        // we have an initial forwarding policy set. This should always be the
29✔
4283
        // case except for a channel that was created with lnd <= 0.15.5 and
29✔
4284
        // is still pending while updating to this version.
29✔
4285
        var needDBUpdate bool
29✔
4286
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
29✔
4287
        if err != nil {
29✔
4288
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4289
                        "falling back to default values: %v", err)
×
4290

×
4291
                forwardingPolicy = f.defaultForwardingPolicy(
×
4292
                        channel.LocalChanCfg.ChannelStateBounds,
×
4293
                )
×
4294
                needDBUpdate = true
×
4295
        }
×
4296

4297
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4298
        // after 0.16.x, so if a channel was opened with such a version and is
4299
        // still pending while updating to this version, we'll need to set the
4300
        // values to the default values.
4301
        if forwardingPolicy.MinHTLCOut == 0 {
45✔
4302
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
16✔
4303
                needDBUpdate = true
16✔
4304
        }
16✔
4305
        if forwardingPolicy.MaxHTLC == 0 {
45✔
4306
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
16✔
4307
                needDBUpdate = true
16✔
4308
        }
16✔
4309

4310
        // And finally, if we found that the values currently stored aren't
4311
        // sufficient for the link, we'll update the database.
4312
        if needDBUpdate {
45✔
4313
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
16✔
4314
                if err != nil {
16✔
4315
                        return fmt.Errorf("unable to update initial "+
×
4316
                                "forwarding policy: %v", err)
×
4317
                }
×
4318
        }
4319

4320
        return nil
29✔
4321
}
4322

4323
// chanAnnouncement encapsulates the two authenticated announcements that we
4324
// send out to the network after a new channel has been created locally.
4325
type chanAnnouncement struct {
4326
        chanAnn       *lnwire.ChannelAnnouncement1
4327
        chanUpdateAnn *lnwire.ChannelUpdate1
4328
        chanProof     *lnwire.AnnounceSignatures1
4329
}
4330

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

45✔
4346
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
45✔
4347

45✔
4348
        // The unconditional section of the announcement is the ShortChannelID
45✔
4349
        // itself which compactly encodes the location of the funding output
45✔
4350
        // within the blockchain.
45✔
4351
        chanAnn := &lnwire.ChannelAnnouncement1{
45✔
4352
                ShortChannelID: shortChanID,
45✔
4353
                Features:       lnwire.NewRawFeatureVector(),
45✔
4354
                ChainHash:      chainHash,
45✔
4355
        }
45✔
4356

45✔
4357
        // If this is a taproot channel, then we'll set a special bit in the
45✔
4358
        // feature vector to indicate to the routing layer that this needs a
45✔
4359
        // slightly different type of validation.
45✔
4360
        //
45✔
4361
        // TODO(roasbeef): temp, remove after gossip 1.5
45✔
4362
        if chanType.IsTaproot() {
52✔
4363
                log.Debugf("Applying taproot feature bit to "+
7✔
4364
                        "ChannelAnnouncement for %v", chanID)
7✔
4365

7✔
4366
                chanAnn.Features.Set(
7✔
4367
                        lnwire.SimpleTaprootChannelsRequiredStaging,
7✔
4368
                )
7✔
4369
        }
7✔
4370

4371
        // The chanFlags field indicates which directed edge of the channel is
4372
        // being updated within the ChannelUpdateAnnouncement announcement
4373
        // below. A value of zero means it's the edge of the "first" node and 1
4374
        // being the other node.
4375
        var chanFlags lnwire.ChanUpdateChanFlags
45✔
4376

45✔
4377
        // The lexicographical ordering of the two identity public keys of the
45✔
4378
        // nodes indicates which of the nodes is "first". If our serialized
45✔
4379
        // identity key is lower than theirs then we're the "first" node and
45✔
4380
        // second otherwise.
45✔
4381
        selfBytes := localPubKey.SerializeCompressed()
45✔
4382
        remoteBytes := remotePubKey.SerializeCompressed()
45✔
4383
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
69✔
4384
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
24✔
4385
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
24✔
4386
                copy(
24✔
4387
                        chanAnn.BitcoinKey1[:],
24✔
4388
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4389
                )
24✔
4390
                copy(
24✔
4391
                        chanAnn.BitcoinKey2[:],
24✔
4392
                        remoteFundingKey.SerializeCompressed(),
24✔
4393
                )
24✔
4394

24✔
4395
                // If we're the first node then update the chanFlags to
24✔
4396
                // indicate the "direction" of the update.
24✔
4397
                chanFlags = 0
24✔
4398
        } else {
48✔
4399
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
24✔
4400
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
24✔
4401
                copy(
24✔
4402
                        chanAnn.BitcoinKey1[:],
24✔
4403
                        remoteFundingKey.SerializeCompressed(),
24✔
4404
                )
24✔
4405
                copy(
24✔
4406
                        chanAnn.BitcoinKey2[:],
24✔
4407
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4408
                )
24✔
4409

24✔
4410
                // If we're the second node then update the chanFlags to
24✔
4411
                // indicate the "direction" of the update.
24✔
4412
                chanFlags = 1
24✔
4413
        }
24✔
4414

4415
        // Our channel update message flags will signal that we support the
4416
        // max_htlc field.
4417
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
45✔
4418

45✔
4419
        // We announce the channel with the default values. Some of
45✔
4420
        // these values can later be changed by crafting a new ChannelUpdate.
45✔
4421
        chanUpdateAnn := &lnwire.ChannelUpdate1{
45✔
4422
                ShortChannelID: shortChanID,
45✔
4423
                ChainHash:      chainHash,
45✔
4424
                Timestamp:      uint32(time.Now().Unix()),
45✔
4425
                MessageFlags:   msgFlags,
45✔
4426
                ChannelFlags:   chanFlags,
45✔
4427
                TimeLockDelta: uint16(
45✔
4428
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
45✔
4429
                ),
45✔
4430
                HtlcMinimumMsat: fwdMinHTLC,
45✔
4431
                HtlcMaximumMsat: fwdMaxHTLC,
45✔
4432
        }
45✔
4433

45✔
4434
        // The caller of newChanAnnouncement is expected to provide the initial
45✔
4435
        // forwarding policy to be announced. If no persisted initial policy
45✔
4436
        // values are found, then we will use the default policy values in the
45✔
4437
        // channel announcement.
45✔
4438
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
45✔
4439
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
45✔
4440
                return nil, fmt.Errorf("unable to generate channel "+
×
4441
                        "update announcement: %w", err)
×
4442
        }
×
4443

4444
        switch {
45✔
4445
        case ourPolicy != nil:
3✔
4446
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4447
                // ChannelUpdate.
3✔
4448
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4449
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4450
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4451
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4452
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4453
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4454
                chanUpdateAnn.FeeRate = uint32(
3✔
4455
                        ourPolicy.FeeProportionalMillionths,
3✔
4456
                )
3✔
4457

4458
        case storedFwdingPolicy != nil:
45✔
4459
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
45✔
4460
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
45✔
4461

4462
        default:
×
4463
                log.Infof("No channel forwarding policy specified for channel "+
×
4464
                        "announcement of ChannelID(%v). "+
×
4465
                        "Assuming default fee parameters.", chanID)
×
4466
                chanUpdateAnn.BaseFee = uint32(
×
4467
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4468
                )
×
4469
                chanUpdateAnn.FeeRate = uint32(
×
4470
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4471
                )
×
4472
        }
4473

4474
        // With the channel update announcement constructed, we'll generate a
4475
        // signature that signs a double-sha digest of the announcement.
4476
        // This'll serve to authenticate this announcement and any other future
4477
        // updates we may send.
4478
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
45✔
4479
        if err != nil {
45✔
4480
                return nil, err
×
4481
        }
×
4482
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
45✔
4483
        if err != nil {
45✔
4484
                return nil, fmt.Errorf("unable to generate channel "+
×
4485
                        "update announcement signature: %w", err)
×
4486
        }
×
4487
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
45✔
4488
        if err != nil {
45✔
4489
                return nil, fmt.Errorf("unable to generate channel "+
×
4490
                        "update announcement signature: %w", err)
×
4491
        }
×
4492

4493
        // The channel existence proofs itself is currently announced in
4494
        // distinct message. In order to properly authenticate this message, we
4495
        // need two signatures: one under the identity public key used which
4496
        // signs the message itself and another signature of the identity
4497
        // public key under the funding key itself.
4498
        //
4499
        // TODO(roasbeef): use SignAnnouncement here instead?
4500
        chanAnnMsg, err := chanAnn.DataToSign()
45✔
4501
        if err != nil {
45✔
4502
                return nil, err
×
4503
        }
×
4504
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
45✔
4505
        if err != nil {
45✔
4506
                return nil, fmt.Errorf("unable to generate node "+
×
4507
                        "signature for channel announcement: %w", err)
×
4508
        }
×
4509
        bitcoinSig, err := f.cfg.SignMessage(
45✔
4510
                localFundingKey.KeyLocator, chanAnnMsg, true,
45✔
4511
        )
45✔
4512
        if err != nil {
45✔
4513
                return nil, fmt.Errorf("unable to generate bitcoin "+
×
4514
                        "signature for node public key: %w", err)
×
4515
        }
×
4516

4517
        // Finally, we'll generate the announcement proof which we'll use to
4518
        // provide the other side with the necessary signatures required to
4519
        // allow them to reconstruct the full channel announcement.
4520
        proof := &lnwire.AnnounceSignatures1{
45✔
4521
                ChannelID:      chanID,
45✔
4522
                ShortChannelID: shortChanID,
45✔
4523
        }
45✔
4524
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
45✔
4525
        if err != nil {
45✔
4526
                return nil, err
×
4527
        }
×
4528
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
45✔
4529
        if err != nil {
45✔
4530
                return nil, err
×
4531
        }
×
4532

4533
        return &chanAnnouncement{
45✔
4534
                chanAnn:       chanAnn,
45✔
4535
                chanUpdateAnn: chanUpdateAnn,
45✔
4536
                chanProof:     proof,
45✔
4537
        }, nil
45✔
4538
}
4539

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

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

4568
        // We only send the channel proof announcement and the node announcement
4569
        // because addToGraph previously sent the ChannelAnnouncement and
4570
        // the ChannelUpdate announcement messages. The channel proof and node
4571
        // announcements are broadcast to the greater network.
4572
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
19✔
4573
        select {
19✔
4574
        case err := <-errChan:
19✔
4575
                if err != nil {
22✔
4576
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4577
                                graph.ErrIgnored) {
3✔
4578

×
4579
                                log.Debugf("Graph rejected "+
×
4580
                                        "AnnounceSignatures: %v", err)
×
4581
                        } else {
3✔
4582
                                log.Errorf("Unable to send channel "+
3✔
4583
                                        "proof: %v", err)
3✔
4584
                                return err
3✔
4585
                        }
3✔
4586
                }
4587

4588
        case <-f.quit:
×
4589
                return ErrFundingManagerShuttingDown
×
4590
        }
4591

4592
        // Now that the channel is announced to the network, we will also
4593
        // obtain and send a node announcement. This is done since a node
4594
        // announcement is only accepted after a channel is known for that
4595
        // particular node, and this might be our first channel.
4596
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
19✔
4597
        if err != nil {
19✔
4598
                log.Errorf("can't generate node announcement: %v", err)
×
4599
                return err
×
4600
        }
×
4601

4602
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
19✔
4603
        select {
19✔
4604
        case err := <-errChan:
19✔
4605
                if err != nil {
22✔
4606
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4607
                                graph.ErrIgnored) {
6✔
4608

3✔
4609
                                log.Debugf("Graph rejected "+
3✔
4610
                                        "NodeAnnouncement: %v", err)
3✔
4611
                        } else {
3✔
4612
                                log.Errorf("Unable to send node "+
×
4613
                                        "announcement: %v", err)
×
4614
                                return err
×
4615
                        }
×
4616
                }
4617

4618
        case <-f.quit:
×
4619
                return ErrFundingManagerShuttingDown
×
4620
        }
4621

4622
        return nil
19✔
4623
}
4624

4625
// InitFundingWorkflow sends a message to the funding manager instructing it
4626
// to initiate a single funder workflow with the source peer.
4627
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
59✔
4628
        f.fundingRequests <- msg
59✔
4629
}
59✔
4630

4631
// getUpfrontShutdownScript takes a user provided script and a getScript
4632
// function which can be used to generate an upfront shutdown script. If our
4633
// peer does not support the feature, this function will error if a non-zero
4634
// script was provided by the user, and return an empty script otherwise. If
4635
// our peer does support the feature, we will return the user provided script
4636
// if non-zero, or a freshly generated script if our node is configured to set
4637
// upfront shutdown scripts automatically.
4638
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4639
        script lnwire.DeliveryAddress,
4640
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4641
        error) {
111✔
4642

111✔
4643
        // Check whether the remote peer supports upfront shutdown scripts.
111✔
4644
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
111✔
4645
                lnwire.UpfrontShutdownScriptOptional,
111✔
4646
        )
111✔
4647

111✔
4648
        // If the peer does not support upfront shutdown scripts, and one has been
111✔
4649
        // provided, return an error because the feature is not supported.
111✔
4650
        if !remoteUpfrontShutdown && len(script) != 0 {
112✔
4651
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4652
        }
1✔
4653

4654
        // If the peer does not support upfront shutdown, return an empty address.
4655
        if !remoteUpfrontShutdown {
213✔
4656
                return nil, nil
103✔
4657
        }
103✔
4658

4659
        // If the user has provided an script and the peer supports the feature,
4660
        // return it. Note that user set scripts override the enable upfront
4661
        // shutdown flag.
4662
        if len(script) > 0 {
12✔
4663
                return script, nil
5✔
4664
        }
5✔
4665

4666
        // If we do not have setting of upfront shutdown script enabled, return
4667
        // an empty script.
4668
        if !enableUpfrontShutdown {
9✔
4669
                return nil, nil
4✔
4670
        }
4✔
4671

4672
        // We can safely send a taproot address iff, both sides have negotiated
4673
        // the shutdown-any-segwit feature.
4674
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4675
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4676

1✔
4677
        return getScript(taprootOK)
1✔
4678
}
4679

4680
// handleInitFundingMsg creates a channel reservation within the daemon's
4681
// wallet, then sends a funding request to the remote peer kicking off the
4682
// funding workflow.
4683
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
59✔
4684
        var (
59✔
4685
                peerKey        = msg.Peer.IdentityKey()
59✔
4686
                localAmt       = msg.LocalFundingAmt
59✔
4687
                baseFee        = msg.BaseFee
59✔
4688
                feeRate        = msg.FeeRate
59✔
4689
                minHtlcIn      = msg.MinHtlcIn
59✔
4690
                remoteCsvDelay = msg.RemoteCsvDelay
59✔
4691
                maxValue       = msg.MaxValueInFlight
59✔
4692
                maxHtlcs       = msg.MaxHtlcs
59✔
4693
                maxCSV         = msg.MaxLocalCsv
59✔
4694
                chanReserve    = msg.RemoteChanReserve
59✔
4695
                outpoints      = msg.Outpoints
59✔
4696
        )
59✔
4697

59✔
4698
        // If no maximum CSV delay was set for this channel, we use our default
59✔
4699
        // value.
59✔
4700
        if maxCSV == 0 {
118✔
4701
                maxCSV = f.cfg.MaxLocalCSVDelay
59✔
4702
        }
59✔
4703

4704
        log.Infof("Initiating fundingRequest(local_amt=%v "+
59✔
4705
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
59✔
4706
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
59✔
4707
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
59✔
4708

59✔
4709
        // We set the channel flags to indicate whether we want this channel to
59✔
4710
        // be announced to the network.
59✔
4711
        var channelFlags lnwire.FundingFlag
59✔
4712
        if !msg.Private {
113✔
4713
                // This channel will be announced.
54✔
4714
                channelFlags = lnwire.FFAnnounceChannel
54✔
4715
        }
54✔
4716

4717
        // If the caller specified their own channel ID, then we'll use that.
4718
        // Otherwise we'll generate a fresh one as normal.  This will be used
4719
        // to track this reservation throughout its lifetime.
4720
        var chanID PendingChanID
59✔
4721
        if msg.PendingChanID == zeroID {
118✔
4722
                chanID = f.nextPendingChanID()
59✔
4723
        } else {
62✔
4724
                // If the user specified their own pending channel ID, then
3✔
4725
                // we'll ensure it doesn't collide with any existing pending
3✔
4726
                // channel ID.
3✔
4727
                chanID = msg.PendingChanID
3✔
4728
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
3✔
4729
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4730
                                "already present", chanID[:])
×
4731
                        return
×
4732
                }
×
4733
        }
4734

4735
        // Check whether the peer supports upfront shutdown, and get an address
4736
        // which should be used (either a user specified address or a new
4737
        // address from the wallet if our node is configured to set shutdown
4738
        // address by default).
4739
        shutdown, err := getUpfrontShutdownScript(
59✔
4740
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
59✔
4741
                f.selectShutdownScript,
59✔
4742
        )
59✔
4743
        if err != nil {
59✔
4744
                msg.Err <- err
×
4745
                return
×
4746
        }
×
4747

4748
        // Initialize a funding reservation with the local wallet. If the
4749
        // wallet doesn't have enough funds to commit to this channel, then the
4750
        // request will fail, and be aborted.
4751
        //
4752
        // Before we init the channel, we'll also check to see what commitment
4753
        // format we can use with this peer. This is dependent on *both* us and
4754
        // the remote peer are signaling the proper feature bit.
4755
        chanType, commitType, err := negotiateCommitmentType(
59✔
4756
                msg.ChannelType, msg.Peer.LocalFeatures(),
59✔
4757
                msg.Peer.RemoteFeatures(),
59✔
4758
        )
59✔
4759
        if err != nil {
62✔
4760
                log.Errorf("channel type negotiation failed: %v", err)
3✔
4761
                msg.Err <- err
3✔
4762
                return
3✔
4763
        }
3✔
4764

4765
        var (
59✔
4766
                zeroConf bool
59✔
4767
                scid     bool
59✔
4768
        )
59✔
4769

59✔
4770
        if chanType != nil {
66✔
4771
                // Check if the returned chanType includes either the zero-conf
7✔
4772
                // or scid-alias bits.
7✔
4773
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
4774
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
4775
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
4776

7✔
4777
                // The option-scid-alias channel type for a public channel is
7✔
4778
                // disallowed.
7✔
4779
                if scid && !msg.Private {
7✔
4780
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4781
                                "public channel")
×
4782
                        log.Error(err)
×
4783
                        msg.Err <- err
×
4784

×
4785
                        return
×
4786
                }
×
4787
        }
4788

4789
        // First, we'll query the fee estimator for a fee that should get the
4790
        // commitment transaction confirmed by the next few blocks (conf target
4791
        // of 3). We target the near blocks here to ensure that we'll be able
4792
        // to execute a timely unilateral channel closure if needed.
4793
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
59✔
4794
        if err != nil {
59✔
4795
                msg.Err <- err
×
4796
                return
×
4797
        }
×
4798

4799
        // For anchor channels cap the initial commit fee rate at our defined
4800
        // maximum.
4801
        if commitType.HasAnchors() &&
59✔
4802
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
66✔
4803

7✔
4804
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
7✔
4805
        }
7✔
4806

4807
        var scidFeatureVal bool
59✔
4808
        if hasFeatures(
59✔
4809
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
59✔
4810
                lnwire.ScidAliasOptional,
59✔
4811
        ) {
65✔
4812

6✔
4813
                scidFeatureVal = true
6✔
4814
        }
6✔
4815

4816
        // At this point, if we have an AuxFundingController active, we'll check
4817
        // to see if we have a special tapscript root to use in our MuSig2
4818
        // funding output.
4819
        tapscriptRoot, err := fn.MapOptionZ(
59✔
4820
                f.cfg.AuxFundingController,
59✔
4821
                func(c AuxFundingController) AuxTapscriptResult {
59✔
4822
                        return c.DeriveTapscriptRoot(chanID)
×
4823
                },
×
4824
        ).Unpack()
4825
        if err != nil {
59✔
4826
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4827
                log.Error(err)
×
4828
                msg.Err <- err
×
4829

×
4830
                return
×
4831
        }
×
4832

4833
        req := &lnwallet.InitFundingReserveMsg{
59✔
4834
                ChainHash:         &msg.ChainHash,
59✔
4835
                PendingChanID:     chanID,
59✔
4836
                NodeID:            peerKey,
59✔
4837
                NodeAddr:          msg.Peer.Address(),
59✔
4838
                SubtractFees:      msg.SubtractFees,
59✔
4839
                LocalFundingAmt:   localAmt,
59✔
4840
                RemoteFundingAmt:  0,
59✔
4841
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
59✔
4842
                MinFundAmt:        msg.MinFundAmt,
59✔
4843
                RemoteChanReserve: chanReserve,
59✔
4844
                Outpoints:         outpoints,
59✔
4845
                CommitFeePerKw:    commitFeePerKw,
59✔
4846
                FundingFeePerKw:   msg.FundingFeePerKw,
59✔
4847
                PushMSat:          msg.PushAmt,
59✔
4848
                Flags:             channelFlags,
59✔
4849
                MinConfs:          msg.MinConfs,
59✔
4850
                CommitType:        commitType,
59✔
4851
                ChanFunder:        msg.ChanFunder,
59✔
4852
                // Unconfirmed Utxos which are marked by the sweeper subsystem
59✔
4853
                // are excluded from the coin selection because they are not
59✔
4854
                // final and can be RBFed by the sweeper subsystem.
59✔
4855
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
119✔
4856
                        // Utxos with at least 1 confirmation are safe to use
60✔
4857
                        // for channel openings because they don't bare the risk
60✔
4858
                        // of being replaced (BIP 125 RBF).
60✔
4859
                        if u.Confirmations > 0 {
63✔
4860
                                return true
3✔
4861
                        }
3✔
4862

4863
                        // Query the sweeper storage to make sure we don't use
4864
                        // an unconfirmed utxo still in use by the sweeper
4865
                        // subsystem.
4866
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
60✔
4867
                },
4868
                ZeroConf:         zeroConf,
4869
                OptionScidAlias:  scid,
4870
                ScidAliasFeature: scidFeatureVal,
4871
                Memo:             msg.Memo,
4872
                TapscriptRoot:    tapscriptRoot,
4873
        }
4874

4875
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
59✔
4876
        if err != nil {
62✔
4877
                msg.Err <- err
3✔
4878
                return
3✔
4879
        }
3✔
4880

4881
        if zeroConf {
64✔
4882
                // Store the alias for zero-conf channels in the underlying
5✔
4883
                // partial channel state.
5✔
4884
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
4885
                if err != nil {
5✔
4886
                        msg.Err <- err
×
4887
                        return
×
4888
                }
×
4889

4890
                reservation.AddAlias(aliasScid)
5✔
4891
        }
4892

4893
        // Set our upfront shutdown address in the existing reservation.
4894
        reservation.SetOurUpfrontShutdown(shutdown)
59✔
4895

59✔
4896
        // Now that we have successfully reserved funds for this channel in the
59✔
4897
        // wallet, we can fetch the final channel capacity. This is done at
59✔
4898
        // this point since the final capacity might change in case of
59✔
4899
        // SubtractFees=true.
59✔
4900
        capacity := reservation.Capacity()
59✔
4901

59✔
4902
        log.Infof("Target commit tx sat/kw for pendingID(%x): %v", chanID,
59✔
4903
                int64(commitFeePerKw))
59✔
4904

59✔
4905
        // If the remote CSV delay was not set in the open channel request,
59✔
4906
        // we'll use the RequiredRemoteDelay closure to compute the delay we
59✔
4907
        // require given the total amount of funds within the channel.
59✔
4908
        if remoteCsvDelay == 0 {
117✔
4909
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
58✔
4910
        }
58✔
4911

4912
        // If no minimum HTLC value was specified, use the default one.
4913
        if minHtlcIn == 0 {
117✔
4914
                minHtlcIn = f.cfg.DefaultMinHtlcIn
58✔
4915
        }
58✔
4916

4917
        // If no max value was specified, use the default one.
4918
        if maxValue == 0 {
117✔
4919
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
58✔
4920
        }
58✔
4921

4922
        if maxHtlcs == 0 {
118✔
4923
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
59✔
4924
        }
59✔
4925

4926
        // Once the reservation has been created, and indexed, queue a funding
4927
        // request to the remote peer, kicking off the funding workflow.
4928
        ourContribution := reservation.OurContribution()
59✔
4929

59✔
4930
        // Prepare the optional channel fee values from the initFundingMsg. If
59✔
4931
        // useBaseFee or useFeeRate are false the client did not provide fee
59✔
4932
        // values hence we assume default fee settings from the config.
59✔
4933
        forwardingPolicy := f.defaultForwardingPolicy(
59✔
4934
                ourContribution.ChannelStateBounds,
59✔
4935
        )
59✔
4936
        if baseFee != nil {
63✔
4937
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
4✔
4938
        }
4✔
4939

4940
        if feeRate != nil {
63✔
4941
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
4✔
4942
        }
4✔
4943

4944
        // Fetch our dust limit which is part of the default channel
4945
        // constraints, and log it.
4946
        ourDustLimit := ourContribution.DustLimit
59✔
4947

59✔
4948
        log.Infof("Dust limit for pendingID(%x): %v", chanID, ourDustLimit)
59✔
4949

59✔
4950
        // If the channel reserve is not specified, then we calculate an
59✔
4951
        // appropriate amount here.
59✔
4952
        if chanReserve == 0 {
114✔
4953
                chanReserve = f.cfg.RequiredRemoteChanReserve(
55✔
4954
                        capacity, ourDustLimit,
55✔
4955
                )
55✔
4956
        }
55✔
4957

4958
        // If a pending channel map for this peer isn't already created, then
4959
        // we create one, ultimately allowing us to track this pending
4960
        // reservation within the target peer.
4961
        peerIDKey := newSerializedKey(peerKey)
59✔
4962
        f.resMtx.Lock()
59✔
4963
        if _, ok := f.activeReservations[peerIDKey]; !ok {
111✔
4964
                f.activeReservations[peerIDKey] = make(pendingChannels)
52✔
4965
        }
52✔
4966

4967
        resCtx := &reservationWithCtx{
59✔
4968
                chanAmt:           capacity,
59✔
4969
                forwardingPolicy:  *forwardingPolicy,
59✔
4970
                remoteCsvDelay:    remoteCsvDelay,
59✔
4971
                remoteMinHtlc:     minHtlcIn,
59✔
4972
                remoteMaxValue:    maxValue,
59✔
4973
                remoteMaxHtlcs:    maxHtlcs,
59✔
4974
                remoteChanReserve: chanReserve,
59✔
4975
                maxLocalCsv:       maxCSV,
59✔
4976
                channelType:       chanType,
59✔
4977
                reservation:       reservation,
59✔
4978
                peer:              msg.Peer,
59✔
4979
                updates:           msg.Updates,
59✔
4980
                err:               msg.Err,
59✔
4981
        }
59✔
4982
        f.activeReservations[peerIDKey][chanID] = resCtx
59✔
4983
        f.resMtx.Unlock()
59✔
4984

59✔
4985
        // Update the timestamp once the InitFundingMsg has been handled.
59✔
4986
        defer resCtx.updateTimestamp()
59✔
4987

59✔
4988
        // Check the sanity of the selected channel constraints.
59✔
4989
        bounds := &channeldb.ChannelStateBounds{
59✔
4990
                ChanReserve:      chanReserve,
59✔
4991
                MaxPendingAmount: maxValue,
59✔
4992
                MinHTLC:          minHtlcIn,
59✔
4993
                MaxAcceptedHtlcs: maxHtlcs,
59✔
4994
        }
59✔
4995
        commitParams := &channeldb.CommitmentParams{
59✔
4996
                DustLimit: ourDustLimit,
59✔
4997
                CsvDelay:  remoteCsvDelay,
59✔
4998
        }
59✔
4999
        err = lnwallet.VerifyConstraints(
59✔
5000
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
59✔
5001
        )
59✔
5002
        if err != nil {
61✔
5003
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
2✔
5004
                if reserveErr != nil {
2✔
5005
                        log.Errorf("unable to cancel reservation: %v",
×
5006
                                reserveErr)
×
5007
                }
×
5008

5009
                msg.Err <- err
2✔
5010
                return
2✔
5011
        }
5012

5013
        // When opening a script enforced channel lease, include the required
5014
        // expiry TLV record in our proposal.
5015
        var leaseExpiry *lnwire.LeaseExpiry
57✔
5016
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
60✔
5017
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5018
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5019
        }
3✔
5020

5021
        log.Infof("Starting funding workflow with %v for pending_id(%x), "+
57✔
5022
                "committype=%v", msg.Peer.Address(), chanID, commitType)
57✔
5023

57✔
5024
        reservation.SetState(lnwallet.SentOpenChannel)
57✔
5025

57✔
5026
        fundingOpen := lnwire.OpenChannel{
57✔
5027
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
57✔
5028
                PendingChannelID:      chanID,
57✔
5029
                FundingAmount:         capacity,
57✔
5030
                PushAmount:            msg.PushAmt,
57✔
5031
                DustLimit:             ourDustLimit,
57✔
5032
                MaxValueInFlight:      maxValue,
57✔
5033
                ChannelReserve:        chanReserve,
57✔
5034
                HtlcMinimum:           minHtlcIn,
57✔
5035
                FeePerKiloWeight:      uint32(commitFeePerKw),
57✔
5036
                CsvDelay:              remoteCsvDelay,
57✔
5037
                MaxAcceptedHTLCs:      maxHtlcs,
57✔
5038
                FundingKey:            ourContribution.MultiSigKey.PubKey,
57✔
5039
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
57✔
5040
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
57✔
5041
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
57✔
5042
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
57✔
5043
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
57✔
5044
                ChannelFlags:          channelFlags,
57✔
5045
                UpfrontShutdownScript: shutdown,
57✔
5046
                ChannelType:           chanType,
57✔
5047
                LeaseExpiry:           leaseExpiry,
57✔
5048
        }
57✔
5049

57✔
5050
        if commitType.IsTaproot() {
62✔
5051
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
5052
                        ourContribution.LocalNonce.PubNonce,
5✔
5053
                )
5✔
5054
        }
5✔
5055

5056
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
57✔
5057
                e := fmt.Errorf("unable to send funding request message: %w",
×
5058
                        err)
×
5059
                log.Errorf(e.Error())
×
5060

×
5061
                // Since we were unable to send the initial message to the peer
×
5062
                // and start the funding flow, we'll cancel this reservation.
×
5063
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5064
                if err != nil {
×
5065
                        log.Errorf("unable to cancel reservation: %v", err)
×
5066
                }
×
5067

5068
                msg.Err <- e
×
5069
                return
×
5070
        }
5071
}
5072

5073
// handleWarningMsg processes the warning which was received from remote peer.
5074
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
42✔
5075
        log.Warnf("received warning message from peer %x: %v",
42✔
5076
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
42✔
5077
}
42✔
5078

5079
// handleErrorMsg processes the error which was received from remote peer,
5080
// depending on the type of error we should do different clean up steps and
5081
// inform the user about it.
5082
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
3✔
5083
        chanID := msg.ChanID
3✔
5084
        peerKey := peer.IdentityKey()
3✔
5085

3✔
5086
        // First, we'll attempt to retrieve and cancel the funding workflow
3✔
5087
        // that this error was tied to. If we're unable to do so, then we'll
3✔
5088
        // exit early as this was an unwarranted error.
3✔
5089
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
3✔
5090
        if err != nil {
3✔
5091
                log.Warnf("Received error for non-existent funding "+
×
5092
                        "flow: %v (%v)", err, msg.Error())
×
5093
                return
×
5094
        }
×
5095

5096
        // If we did indeed find the funding workflow, then we'll return the
5097
        // error back to the caller (if any), and cancel the workflow itself.
5098
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5099
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5100
        )
3✔
5101
        log.Errorf(fundingErr.Error())
3✔
5102

3✔
5103
        // If this was a PSBT funding flow, the remote likely timed out because
3✔
5104
        // we waited too long. Return a nice error message to the user in that
3✔
5105
        // case so the user knows what's the problem.
3✔
5106
        if resCtx.reservation.IsPsbt() {
6✔
5107
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
3✔
5108
                        fundingErr)
3✔
5109
        }
3✔
5110

5111
        resCtx.err <- fundingErr
3✔
5112
}
5113

5114
// pruneZombieReservations loops through all pending reservations and fails the
5115
// funding flow for any reservations that have not been updated since the
5116
// ReservationTimeout and are not locked waiting for the funding transaction.
5117
func (f *Manager) pruneZombieReservations() {
6✔
5118
        zombieReservations := make(pendingChannels)
6✔
5119

6✔
5120
        f.resMtx.RLock()
6✔
5121
        for _, pendingReservations := range f.activeReservations {
12✔
5122
                for pendingChanID, resCtx := range pendingReservations {
12✔
5123
                        if resCtx.isLocked() {
6✔
5124
                                continue
×
5125
                        }
5126

5127
                        // We don't want to expire PSBT funding reservations.
5128
                        // These reservations are always initiated by us and the
5129
                        // remote peer is likely going to cancel them after some
5130
                        // idle time anyway. So no need for us to also prune
5131
                        // them.
5132
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
6✔
5133
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
6✔
5134
                        if !resCtx.reservation.IsPsbt() && isExpired {
12✔
5135
                                zombieReservations[pendingChanID] = resCtx
6✔
5136
                        }
6✔
5137
                }
5138
        }
5139
        f.resMtx.RUnlock()
6✔
5140

6✔
5141
        for pendingChanID, resCtx := range zombieReservations {
12✔
5142
                err := fmt.Errorf("reservation timed out waiting for peer "+
6✔
5143
                        "(peer_id:%x, chan_id:%x)",
6✔
5144
                        resCtx.peer.IdentityKey().SerializeCompressed(),
6✔
5145
                        pendingChanID[:])
6✔
5146
                log.Warnf(err.Error())
6✔
5147

6✔
5148
                chanID := lnwire.NewChanIDFromOutPoint(
6✔
5149
                        *resCtx.reservation.FundingOutpoint(),
6✔
5150
                )
6✔
5151

6✔
5152
                // Create channel identifier and set the channel ID.
6✔
5153
                cid := newChanIdentifier(pendingChanID)
6✔
5154
                cid.setChanID(chanID)
6✔
5155

6✔
5156
                f.failFundingFlow(resCtx.peer, cid, err)
6✔
5157
        }
6✔
5158
}
5159

5160
// cancelReservationCtx does all needed work in order to securely cancel the
5161
// reservation.
5162
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5163
        pendingChanID PendingChanID,
5164
        byRemote bool) (*reservationWithCtx, error) {
27✔
5165

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

27✔
5169
        peerIDKey := newSerializedKey(peerKey)
27✔
5170
        f.resMtx.Lock()
27✔
5171
        defer f.resMtx.Unlock()
27✔
5172

27✔
5173
        nodeReservations, ok := f.activeReservations[peerIDKey]
27✔
5174
        if !ok {
38✔
5175
                // No reservations for this node.
11✔
5176
                return nil, fmt.Errorf("no active reservations for peer(%x)",
11✔
5177
                        peerIDKey[:])
11✔
5178
        }
11✔
5179

5180
        ctx, ok := nodeReservations[pendingChanID]
19✔
5181
        if !ok {
21✔
5182
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
2✔
5183
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5184
        }
2✔
5185

5186
        // If the reservation was a PSBT funding flow and it was canceled by the
5187
        // remote peer, then we need to thread through a different error message
5188
        // to the subroutine that's waiting for the user input so it can return
5189
        // a nice error message to the user.
5190
        if ctx.reservation.IsPsbt() && byRemote {
20✔
5191
                ctx.reservation.RemoteCanceled()
3✔
5192
        }
3✔
5193

5194
        if err := ctx.reservation.Cancel(); err != nil {
17✔
5195
                return nil, fmt.Errorf("unable to cancel reservation: %w", err)
×
5196
        }
×
5197

5198
        delete(nodeReservations, pendingChanID)
17✔
5199

17✔
5200
        // If this was the last active reservation for this peer, delete the
17✔
5201
        // peer's entry altogether.
17✔
5202
        if len(nodeReservations) == 0 {
34✔
5203
                delete(f.activeReservations, peerIDKey)
17✔
5204
        }
17✔
5205
        return ctx, nil
17✔
5206
}
5207

5208
// deleteReservationCtx deletes the reservation uniquely identified by the
5209
// target public key of the peer, and the specified pending channel ID.
5210
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5211
        pendingChanID PendingChanID) {
57✔
5212

57✔
5213
        peerIDKey := newSerializedKey(peerKey)
57✔
5214
        f.resMtx.Lock()
57✔
5215
        defer f.resMtx.Unlock()
57✔
5216

57✔
5217
        nodeReservations, ok := f.activeReservations[peerIDKey]
57✔
5218
        if !ok {
57✔
5219
                // No reservations for this node.
×
5220
                return
×
5221
        }
×
5222
        delete(nodeReservations, pendingChanID)
57✔
5223

57✔
5224
        // If this was the last active reservation for this peer, delete the
57✔
5225
        // peer's entry altogether.
57✔
5226
        if len(nodeReservations) == 0 {
107✔
5227
                delete(f.activeReservations, peerIDKey)
50✔
5228
        }
50✔
5229
}
5230

5231
// getReservationCtx returns the reservation context for a particular pending
5232
// channel ID for a target peer.
5233
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5234
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
91✔
5235

91✔
5236
        peerIDKey := newSerializedKey(peerKey)
91✔
5237
        f.resMtx.RLock()
91✔
5238
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
91✔
5239
        f.resMtx.RUnlock()
91✔
5240

91✔
5241
        if !ok {
94✔
5242
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
3✔
5243
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5244
        }
3✔
5245

5246
        return resCtx, nil
91✔
5247
}
5248

5249
// IsPendingChannel returns a boolean indicating whether the channel identified
5250
// by the pendingChanID and given peer is pending, meaning it is in the process
5251
// of being funded. After the funding transaction has been confirmed, the
5252
// channel will receive a new, permanent channel ID, and will no longer be
5253
// considered pending.
5254
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5255
        peer lnpeer.Peer) bool {
3✔
5256

3✔
5257
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5258
        f.resMtx.RLock()
3✔
5259
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5260
        f.resMtx.RUnlock()
3✔
5261

3✔
5262
        return ok
3✔
5263
}
3✔
5264

5265
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
378✔
5266
        var tmp btcec.JacobianPoint
378✔
5267
        pub.AsJacobian(&tmp)
378✔
5268
        tmp.ToAffine()
378✔
5269
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
378✔
5270
}
378✔
5271

5272
// defaultForwardingPolicy returns the default forwarding policy based on the
5273
// default routing policy and our local channel constraints.
5274
func (f *Manager) defaultForwardingPolicy(
5275
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
105✔
5276

105✔
5277
        return &models.ForwardingPolicy{
105✔
5278
                MinHTLCOut:    bounds.MinHTLC,
105✔
5279
                MaxHTLC:       bounds.MaxPendingAmount,
105✔
5280
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
105✔
5281
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
105✔
5282
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
105✔
5283
        }
105✔
5284
}
105✔
5285

5286
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5287
// chanPoint in the channelOpeningStateBucket.
5288
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5289
        forwardingPolicy *models.ForwardingPolicy) error {
70✔
5290

70✔
5291
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
70✔
5292
                chanID, forwardingPolicy,
70✔
5293
        )
70✔
5294
}
70✔
5295

5296
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5297
// channel id from the database which will be applied during the channel
5298
// announcement phase.
5299
func (f *Manager) getInitialForwardingPolicy(
5300
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
97✔
5301

97✔
5302
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
97✔
5303
}
97✔
5304

5305
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5306
// the database.
5307
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
27✔
5308
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
27✔
5309
}
27✔
5310

5311
// saveChannelOpeningState saves the channelOpeningState for the provided
5312
// chanPoint to the channelOpeningStateBucket.
5313
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5314
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
95✔
5315

95✔
5316
        var outpointBytes bytes.Buffer
95✔
5317
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
95✔
5318
                return err
×
5319
        }
×
5320

5321
        // Save state and the uint64 representation of the shortChanID
5322
        // for later use.
5323
        scratch := make([]byte, 10)
95✔
5324
        byteOrder.PutUint16(scratch[:2], uint16(state))
95✔
5325
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
95✔
5326

95✔
5327
        return f.cfg.ChannelDB.SaveChannelOpeningState(
95✔
5328
                outpointBytes.Bytes(), scratch,
95✔
5329
        )
95✔
5330
}
5331

5332
// getChannelOpeningState fetches the channelOpeningState for the provided
5333
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5334
// is not found.
5335
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5336
        channelOpeningState, *lnwire.ShortChannelID, error) {
253✔
5337

253✔
5338
        var outpointBytes bytes.Buffer
253✔
5339
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
253✔
5340
                return 0, nil, err
×
5341
        }
×
5342

5343
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
253✔
5344
                outpointBytes.Bytes(),
253✔
5345
        )
253✔
5346
        if err != nil {
303✔
5347
                return 0, nil, err
50✔
5348
        }
50✔
5349

5350
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
206✔
5351
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
206✔
5352
        return state, &shortChanID, nil
206✔
5353
}
5354

5355
// deleteChannelOpeningState removes any state for chanPoint from the database.
5356
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
27✔
5357
        var outpointBytes bytes.Buffer
27✔
5358
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
27✔
5359
                return err
×
5360
        }
×
5361

5362
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
27✔
5363
                outpointBytes.Bytes(),
27✔
5364
        )
27✔
5365
}
5366

5367
// selectShutdownScript selects the shutdown script we should send to the peer.
5368
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5369
// script.
5370
func (f *Manager) selectShutdownScript(taprootOK bool,
5371
) (lnwire.DeliveryAddress, error) {
×
5372

×
5373
        addrType := lnwallet.WitnessPubKey
×
5374
        if taprootOK {
×
5375
                addrType = lnwallet.TaprootPubkey
×
5376
        }
×
5377

5378
        addr, err := f.cfg.Wallet.NewAddress(
×
5379
                addrType, false, lnwallet.DefaultAccountName,
×
5380
        )
×
5381
        if err != nil {
×
5382
                return nil, err
×
5383
        }
×
5384

5385
        return txscript.PayToAddrScript(addr)
×
5386
}
5387

5388
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5389
// and then returns the online peer.
5390
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5391
        error) {
107✔
5392

107✔
5393
        peerChan := make(chan lnpeer.Peer, 1)
107✔
5394

107✔
5395
        var peerKey [33]byte
107✔
5396
        copy(peerKey[:], peerPubkey.SerializeCompressed())
107✔
5397

107✔
5398
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
107✔
5399

107✔
5400
        var peer lnpeer.Peer
107✔
5401
        select {
107✔
5402
        case peer = <-peerChan:
106✔
5403
        case <-f.quit:
1✔
5404
                return peer, ErrFundingManagerShuttingDown
1✔
5405
        }
5406
        return peer, nil
106✔
5407
}
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