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

lightningnetwork / lnd / 19616403112

23 Nov 2025 07:49PM UTC coverage: 65.173% (-0.06%) from 65.229%
19616403112

Pull #10390

github

web-flow
Merge bf85a3dc9 into 8c8662c86
Pull Request #10390: Defer Channel Cleanup after a channel is closed to avoid kv-sql stress

53 of 206 new or added lines in 4 files covered. (25.73%)

127 existing lines in 27 files now uncovered.

137610 of 211145 relevant lines covered (65.17%)

20759.97 hits per line

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

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

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

72
        byteOrder.PutUint32(scratch, o.Index)
373✔
73
        _, err := w.Write(scratch)
373✔
74
        return err
373✔
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() {
140✔
183
        r.updateMtx.Lock()
140✔
184
        defer r.updateMtx.Unlock()
140✔
185

140✔
186
        r.lastUpdated = time.Now()
140✔
187
}
140✔
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 {
394✔
326
        var s serializedPubKey
394✔
327
        copy(s[:], pubKey.SerializeCompressed())
394✔
328
        return s
394✔
329
}
394✔
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.NodeAnnouncement1, 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
        // AuxChannelNegotiator is an optional interface that allows aux channel
573
        // implementations to inject and process custom records over channel
574
        // related wire messages.
575
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
576

577
        // ShutdownScript is an optional upfront-shutdown script to which our
578
        // funds should be paid on a cooperative close.
579
        ShutdownScript fn.Option[lnwire.DeliveryAddress]
580
}
581

582
// Manager acts as an orchestrator/bridge between the wallet's
583
// 'ChannelReservation' workflow, and the wire protocol's funding initiation
584
// messages. Any requests to initiate the funding workflow for a channel,
585
// either kicked-off locally or remotely are handled by the funding manager.
586
// Once a channel's funding workflow has been completed, any local callers, the
587
// local peer, and possibly the remote peer are notified of the completion of
588
// the channel workflow. Additionally, any temporary or permanent access
589
// controls between the wallet and remote peers are enforced via the funding
590
// manager.
591
type Manager struct {
592
        started sync.Once
593
        stopped sync.Once
594

595
        // cfg is a copy of the configuration struct that the FundingManager
596
        // was initialized with.
597
        cfg *Config
598

599
        // chanIDKey is a cryptographically random key that's used to generate
600
        // temporary channel ID's.
601
        chanIDKey [32]byte
602

603
        // chanIDNonce is a nonce that's incremented for each new funding
604
        // reservation created.
605
        chanIDNonce atomic.Uint64
606

607
        // nonceMtx is a mutex that guards the pendingMusigNonces.
608
        nonceMtx sync.RWMutex
609

610
        // pendingMusigNonces is used to store the musig2 nonce we generate to
611
        // send funding locked until we receive a funding locked message from
612
        // the remote party. We'll use this to keep track of the nonce we
613
        // generated, so we send the local+remote nonces to the peer state
614
        // machine.
615
        //
616
        // NOTE: This map is protected by the nonceMtx above.
617
        //
618
        // TODO(roasbeef): replace w/ generic concurrent map
619
        pendingMusigNonces map[lnwire.ChannelID]*musig2.Nonces
620

621
        // activeReservations is a map which houses the state of all pending
622
        // funding workflows.
623
        activeReservations map[serializedPubKey]pendingChannels
624

625
        // signedReservations is a utility map that maps the permanent channel
626
        // ID of a funding reservation to its temporary channel ID. This is
627
        // required as mid funding flow, we switch to referencing the channel
628
        // by its full channel ID once the commitment transactions have been
629
        // signed by both parties.
630
        signedReservations map[lnwire.ChannelID]PendingChanID
631

632
        // resMtx guards both of the maps above to ensure that all access is
633
        // goroutine safe.
634
        resMtx sync.RWMutex
635

636
        // fundingMsgs is a channel that relays fundingMsg structs from
637
        // external sub-systems using the ProcessFundingMsg call.
638
        fundingMsgs chan *fundingMsg
639

640
        // fundingRequests is a channel used to receive channel initiation
641
        // requests from a local subsystem within the daemon.
642
        fundingRequests chan *InitFundingMsg
643

644
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
645

646
        handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
647

648
        quit chan struct{}
649
        wg   sync.WaitGroup
650
}
651

652
// channelOpeningState represents the different states a channel can be in
653
// between the funding transaction has been confirmed and the channel is
654
// announced to the network and ready to be used.
655
type channelOpeningState uint8
656

657
const (
658
        // markedOpen is the opening state of a channel if the funding
659
        // transaction is confirmed on-chain, but channelReady is not yet
660
        // successfully sent to the other peer.
661
        markedOpen channelOpeningState = iota
662

663
        // channelReadySent is the opening state of a channel if the
664
        // channelReady message has successfully been sent to the other peer,
665
        // but we still haven't announced the channel to the network.
666
        channelReadySent
667

668
        // addedToGraph is the opening state of a channel if the channel has
669
        // been successfully added to the graph immediately after the
670
        // channelReady message has been sent, but we still haven't announced
671
        // the channel to the network.
672
        addedToGraph
673
)
674

675
func (c channelOpeningState) String() string {
3✔
676
        switch c {
3✔
677
        case markedOpen:
3✔
678
                return "markedOpen"
3✔
679
        case channelReadySent:
3✔
680
                return "channelReadySent"
3✔
681
        case addedToGraph:
3✔
682
                return "addedToGraph"
3✔
683
        default:
×
684
                return "unknown"
×
685
        }
686
}
687

688
// NewFundingManager creates and initializes a new instance of the
689
// fundingManager.
690
func NewFundingManager(cfg Config) (*Manager, error) {
112✔
691
        return &Manager{
112✔
692
                cfg:       &cfg,
112✔
693
                chanIDKey: cfg.TempChanIDSeed,
112✔
694
                activeReservations: make(
112✔
695
                        map[serializedPubKey]pendingChannels,
112✔
696
                ),
112✔
697
                signedReservations: make(
112✔
698
                        map[lnwire.ChannelID][32]byte,
112✔
699
                ),
112✔
700
                fundingMsgs: make(
112✔
701
                        chan *fundingMsg, msgBufferSize,
112✔
702
                ),
112✔
703
                fundingRequests: make(
112✔
704
                        chan *InitFundingMsg, msgBufferSize,
112✔
705
                ),
112✔
706
                localDiscoverySignals: &lnutils.SyncMap[
112✔
707
                        lnwire.ChannelID, chan struct{},
112✔
708
                ]{},
112✔
709
                handleChannelReadyBarriers: &lnutils.SyncMap[
112✔
710
                        lnwire.ChannelID, struct{},
112✔
711
                ]{},
112✔
712
                pendingMusigNonces: make(
112✔
713
                        map[lnwire.ChannelID]*musig2.Nonces,
112✔
714
                ),
112✔
715
                quit: make(chan struct{}),
112✔
716
        }, nil
112✔
717
}
112✔
718

719
// Start launches all helper goroutines required for handling requests sent
720
// to the funding manager.
721
func (f *Manager) Start() error {
112✔
722
        var err error
112✔
723
        f.started.Do(func() {
224✔
724
                log.Info("Funding manager starting")
112✔
725
                err = f.start()
112✔
726
        })
112✔
727
        return err
112✔
728
}
729

730
func (f *Manager) start() error {
112✔
731
        // Upon restart, the Funding Manager will check the database to load any
112✔
732
        // channels that were  waiting for their funding transactions to be
112✔
733
        // confirmed on the blockchain at the time when the daemon last went
112✔
734
        // down.
112✔
735
        // TODO(roasbeef): store height that funding finished?
112✔
736
        //  * would then replace call below
112✔
737
        allChannels, err := f.cfg.ChannelDB.FetchAllChannels()
112✔
738
        if err != nil {
112✔
739
                return err
×
740
        }
×
741

742
        for _, channel := range allChannels {
124✔
743
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
12✔
744

12✔
745
                // For any channels that were in a pending state when the
12✔
746
                // daemon was last connected, the Funding Manager will
12✔
747
                // re-initialize the channel barriers, and republish the
12✔
748
                // funding transaction if we're the initiator.
12✔
749
                if channel.IsPending {
16✔
750
                        log.Tracef("Loading pending ChannelPoint(%v), "+
4✔
751
                                "creating chan barrier",
4✔
752
                                channel.FundingOutpoint)
4✔
753

4✔
754
                        f.localDiscoverySignals.Store(
4✔
755
                                chanID, make(chan struct{}),
4✔
756
                        )
4✔
757

4✔
758
                        // Rebroadcast the funding transaction for any pending
4✔
759
                        // channel that we initiated. No error will be returned
4✔
760
                        // if the transaction already has been broadcast.
4✔
761
                        chanType := channel.ChanType
4✔
762
                        if chanType.IsSingleFunder() &&
4✔
763
                                chanType.HasFundingTx() &&
4✔
764
                                channel.IsInitiator {
8✔
765

4✔
766
                                f.rebroadcastFundingTx(channel)
4✔
767
                        }
4✔
768
                } else if channel.ChanType.IsSingleFunder() &&
11✔
769
                        channel.ChanType.HasFundingTx() &&
11✔
770
                        channel.IsZeroConf() && channel.IsInitiator &&
11✔
771
                        !channel.ZeroConfConfirmed() {
13✔
772

2✔
773
                        // Rebroadcast the funding transaction for unconfirmed
2✔
774
                        // zero-conf channels if we have the funding tx and are
2✔
775
                        // also the initiator.
2✔
776
                        f.rebroadcastFundingTx(channel)
2✔
777
                }
2✔
778

779
                // We will restart the funding state machine for all channels,
780
                // which will wait for the channel's funding transaction to be
781
                // confirmed on the blockchain, and transmit the messages
782
                // necessary for the channel to be operational.
783
                f.wg.Add(1)
12✔
784
                go f.advanceFundingState(channel, chanID, nil)
12✔
785
        }
786

787
        f.wg.Add(1) // TODO(roasbeef): tune
112✔
788
        go f.reservationCoordinator()
112✔
789

112✔
790
        return nil
112✔
791
}
792

793
// Stop signals all helper goroutines to execute a graceful shutdown. This
794
// method will block until all goroutines have exited.
795
func (f *Manager) Stop() error {
109✔
796
        f.stopped.Do(func() {
217✔
797
                log.Info("Funding manager shutting down...")
108✔
798
                defer log.Debug("Funding manager shutdown complete")
108✔
799

108✔
800
                close(f.quit)
108✔
801
                f.wg.Wait()
108✔
802
        })
108✔
803

804
        return nil
109✔
805
}
806

807
// rebroadcastFundingTx publishes the funding tx on startup for each
808
// unconfirmed channel.
809
func (f *Manager) rebroadcastFundingTx(c *channeldb.OpenChannel) {
6✔
810
        var fundingTxBuf bytes.Buffer
6✔
811
        err := c.FundingTxn.Serialize(&fundingTxBuf)
6✔
812
        if err != nil {
6✔
813
                log.Errorf("Unable to serialize funding transaction %v: %v",
×
814
                        c.FundingTxn.TxHash(), err)
×
815

×
816
                // Clear the buffer of any bytes that were written before the
×
817
                // serialization error to prevent logging an incomplete
×
818
                // transaction.
×
819
                fundingTxBuf.Reset()
×
820
        } else {
6✔
821
                log.Debugf("Rebroadcasting funding tx for ChannelPoint(%v): "+
6✔
822
                        "%x", c.FundingOutpoint, fundingTxBuf.Bytes())
6✔
823
        }
6✔
824

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

6✔
829
        err = f.cfg.PublishTransaction(c.FundingTxn, label)
6✔
830
        if err != nil {
6✔
831
                log.Errorf("Unable to rebroadcast funding tx %x for "+
×
832
                        "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
833
                        c.FundingOutpoint, err)
×
834
        }
×
835
}
836

837
// PendingChanID is a type that represents a pending channel ID. This might be
838
// selected by the caller, but if not, will be automatically selected.
839
type PendingChanID = [32]byte
840

841
// nextPendingChanID returns the next free pending channel ID to be used to
842
// identify a particular future channel funding workflow.
843
func (f *Manager) nextPendingChanID() PendingChanID {
60✔
844
        // Obtain a fresh nonce. We do this by encoding the incremented nonce.
60✔
845
        nextNonce := f.chanIDNonce.Add(1)
60✔
846

60✔
847
        var nonceBytes [8]byte
60✔
848
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
60✔
849

60✔
850
        // We'll generate the next pending channelID by "encrypting" 32-bytes
60✔
851
        // of zeroes which'll extract 32 random bytes from our stream cipher.
60✔
852
        var (
60✔
853
                nextChanID PendingChanID
60✔
854
                zeroes     [32]byte
60✔
855
        )
60✔
856
        salsa20.XORKeyStream(
60✔
857
                nextChanID[:], zeroes[:], nonceBytes[:], &f.chanIDKey,
60✔
858
        )
60✔
859

60✔
860
        return nextChanID
60✔
861
}
60✔
862

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

3✔
869
        f.resMtx.Lock()
3✔
870
        defer f.resMtx.Unlock()
3✔
871

3✔
872
        // We'll attempt to look up this node in the set of active
3✔
873
        // reservations.  If they don't have any, then there's no further work
3✔
874
        // to be done.
3✔
875
        nodeReservations, ok := f.activeReservations[nodePub]
3✔
876
        if !ok {
6✔
877
                log.Debugf("No active reservations for node: %x", nodePub[:])
3✔
878
                return
3✔
879
        }
3✔
880

881
        // If they do have any active reservations, then we'll cancel all of
882
        // them (which releases any locked UTXO's), and also delete it from the
883
        // reservation map.
884
        for pendingID, resCtx := range nodeReservations {
×
885
                if err := resCtx.reservation.Cancel(); err != nil {
×
886
                        log.Errorf("unable to cancel reservation for "+
×
887
                                "node=%x: %v", nodePub[:], err)
×
888
                }
×
889

890
                resCtx.err <- fmt.Errorf("peer disconnected")
×
891
                delete(nodeReservations, pendingID)
×
892
        }
893

894
        // Finally, we'll delete the node itself from the set of reservations.
895
        delete(f.activeReservations, nodePub)
×
896
}
897

898
// chanIdentifier wraps pending channel ID and channel ID into one struct so
899
// it's easier to identify a specific channel.
900
//
901
// TODO(yy): move to a different package to hide the private fields so direct
902
// access is disabled.
903
type chanIdentifier struct {
904
        // tempChanID is the pending channel ID created by the funder when
905
        // initializing the funding flow. For fundee, it's received from the
906
        // `open_channel` message.
907
        tempChanID lnwire.ChannelID
908

909
        // chanID is the channel ID created by the funder once the
910
        // `accept_channel` message is received. For fundee, it's received from
911
        // the `funding_created` message.
912
        chanID lnwire.ChannelID
913

914
        // chanIDSet is a boolean indicates whether the active channel ID is
915
        // set for this identifier. For zero conf channels, the `chanID` can be
916
        // all-zero, which is the same as the empty value of `ChannelID`. To
917
        // avoid the confusion, we use this boolean to explicitly signal
918
        // whether the `chanID` is set or not.
919
        chanIDSet bool
920
}
921

922
// newChanIdentifier creates a new chanIdentifier.
923
func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
152✔
924
        return &chanIdentifier{
152✔
925
                tempChanID: tempChanID,
152✔
926
        }
152✔
927
}
152✔
928

929
// setChanID updates the `chanIdentifier` with the active channel ID.
930
func (c *chanIdentifier) setChanID(chanID lnwire.ChannelID) {
94✔
931
        c.chanID = chanID
94✔
932
        c.chanIDSet = true
94✔
933
}
94✔
934

935
// hasChanID returns true if the active channel ID has been set.
936
func (c *chanIdentifier) hasChanID() bool {
25✔
937
        return c.chanIDSet
25✔
938
}
25✔
939

940
// failFundingFlow will fail the active funding flow with the target peer,
941
// identified by its unique temporary channel ID. This method will send an
942
// error to the remote peer, and also remove the reservation from our set of
943
// pending reservations.
944
//
945
// TODO(roasbeef): if peer disconnects, and haven't yet broadcast funding
946
// transaction, then all reservations should be cleared.
947
func (f *Manager) failFundingFlow(peer lnpeer.Peer, cid *chanIdentifier,
948
        fundingErr error) {
25✔
949

25✔
950
        log.Debugf("Failing funding flow for pending_id=%v: %v",
25✔
951
                cid.tempChanID, fundingErr)
25✔
952

25✔
953
        // First, notify Brontide to remove the pending channel.
25✔
954
        //
25✔
955
        // NOTE: depending on where we fail the flow, we may not have the
25✔
956
        // active channel ID yet.
25✔
957
        if cid.hasChanID() {
33✔
958
                err := peer.RemovePendingChannel(cid.chanID)
8✔
959
                if err != nil {
8✔
960
                        log.Errorf("Unable to remove channel %v with peer %x: "+
×
961
                                "%v", cid,
×
962
                                peer.IdentityKey().SerializeCompressed(), err)
×
963
                }
×
964
        }
965

966
        ctx, err := f.cancelReservationCtx(
25✔
967
                peer.IdentityKey(), cid.tempChanID, false,
25✔
968
        )
25✔
969
        if err != nil {
38✔
970
                log.Errorf("unable to cancel reservation: %v", err)
13✔
971
        }
13✔
972

973
        // In case the case where the reservation existed, send the funding
974
        // error on the error channel.
975
        if ctx != nil {
40✔
976
                ctx.err <- fundingErr
15✔
977
        }
15✔
978

979
        // We only send the exact error if it is part of out whitelisted set of
980
        // errors (lnwire.FundingError or lnwallet.ReservationError).
981
        var msg lnwire.ErrorData
25✔
982
        switch e := fundingErr.(type) {
25✔
983
        // Let the actual error message be sent to the remote for the
984
        // whitelisted types.
985
        case lnwallet.ReservationError:
9✔
986
                msg = lnwire.ErrorData(e.Error())
9✔
987
        case lnwire.FundingError:
7✔
988
                msg = lnwire.ErrorData(e.Error())
7✔
989
        case chanacceptor.ChanAcceptError:
3✔
990
                msg = lnwire.ErrorData(e.Error())
3✔
991

992
        // For all other error types we just send a generic error.
993
        default:
15✔
994
                msg = lnwire.ErrorData("funding failed due to internal error")
15✔
995
        }
996

997
        errMsg := &lnwire.Error{
25✔
998
                ChanID: cid.tempChanID,
25✔
999
                Data:   msg,
25✔
1000
        }
25✔
1001

25✔
1002
        log.Debugf("Sending funding error to peer (%x): %v",
25✔
1003
                peer.IdentityKey().SerializeCompressed(),
25✔
1004
                lnutils.SpewLogClosure(errMsg))
25✔
1005

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

1011
// sendWarning sends a new warning message to the target peer, targeting the
1012
// specified cid with the passed funding error.
1013
func (f *Manager) sendWarning(peer lnpeer.Peer, cid *chanIdentifier,
1014
        fundingErr error) {
×
1015

×
1016
        msg := fundingErr.Error()
×
1017

×
1018
        errMsg := &lnwire.Warning{
×
1019
                ChanID: cid.tempChanID,
×
1020
                Data:   lnwire.WarningData(msg),
×
1021
        }
×
1022

×
1023
        log.Debugf("Sending funding warning to peer (%x): %v",
×
1024
                peer.IdentityKey().SerializeCompressed(),
×
1025
                lnutils.SpewLogClosure(errMsg),
×
1026
        )
×
1027

×
1028
        if err := peer.SendMessage(false, errMsg); err != nil {
×
1029
                log.Errorf("unable to send error message to peer %v", err)
×
1030
        }
×
1031
}
1032

1033
// reservationCoordinator is the primary goroutine tasked with progressing the
1034
// funding workflow between the wallet, and any outside peers or local callers.
1035
//
1036
// NOTE: This MUST be run as a goroutine.
1037
func (f *Manager) reservationCoordinator() {
112✔
1038
        defer f.wg.Done()
112✔
1039

112✔
1040
        zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
112✔
1041
        defer zombieSweepTicker.Stop()
112✔
1042

112✔
1043
        for {
497✔
1044
                select {
385✔
1045
                case fmsg := <-f.fundingMsgs:
219✔
1046
                        switch msg := fmsg.msg.(type) {
219✔
1047
                        case *lnwire.OpenChannel:
58✔
1048
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
58✔
1049

1050
                        case *lnwire.AcceptChannel:
36✔
1051
                                f.funderProcessAcceptChannel(fmsg.peer, msg)
36✔
1052

1053
                        case *lnwire.FundingCreated:
31✔
1054
                                f.fundeeProcessFundingCreated(fmsg.peer, msg)
31✔
1055

1056
                        case *lnwire.FundingSigned:
31✔
1057
                                f.funderProcessFundingSigned(fmsg.peer, msg)
31✔
1058

1059
                        case *lnwire.ChannelReady:
31✔
1060
                                f.wg.Add(1)
31✔
1061
                                go f.handleChannelReady(fmsg.peer, msg)
31✔
1062

1063
                        case *lnwire.Warning:
44✔
1064
                                f.handleWarningMsg(fmsg.peer, msg)
44✔
1065

1066
                        case *lnwire.Error:
3✔
1067
                                f.handleErrorMsg(fmsg.peer, msg)
3✔
1068
                        }
1069
                case req := <-f.fundingRequests:
60✔
1070
                        f.handleInitFundingMsg(req)
60✔
1071

1072
                case <-zombieSweepTicker.C:
3✔
1073
                        f.pruneZombieReservations()
3✔
1074

1075
                case <-f.quit:
108✔
1076
                        return
108✔
1077
                }
1078
        }
1079
}
1080

1081
// advanceFundingState will advance the channel through the steps after the
1082
// funding transaction is broadcasted, up until the point where the channel is
1083
// ready for operation. This includes waiting for the funding transaction to
1084
// confirm, sending channel_ready to the peer, adding the channel to the graph,
1085
// and announcing the channel. The updateChan can be set non-nil to get
1086
// OpenStatusUpdates.
1087
//
1088
// NOTE: This MUST be run as a goroutine.
1089
func (f *Manager) advanceFundingState(channel *channeldb.OpenChannel,
1090
        pendingChanID PendingChanID,
1091
        updateChan chan<- *lnrpc.OpenStatusUpdate) {
68✔
1092

68✔
1093
        defer f.wg.Done()
68✔
1094

68✔
1095
        // If the channel is still pending we must wait for the funding
68✔
1096
        // transaction to confirm.
68✔
1097
        if channel.IsPending {
128✔
1098
                err := f.advancePendingChannelState(channel, pendingChanID)
60✔
1099
                if err != nil {
86✔
1100
                        log.Errorf("Unable to advance pending state of "+
26✔
1101
                                "ChannelPoint(%v): %v",
26✔
1102
                                channel.FundingOutpoint, err)
26✔
1103
                        return
26✔
1104
                }
26✔
1105
        }
1106

1107
        var chanOpts []lnwallet.ChannelOpt
45✔
1108
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
87✔
1109
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
42✔
1110
        })
42✔
1111
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
87✔
1112
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
42✔
1113
        })
42✔
1114
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
45✔
1115
                chanOpts = append(chanOpts, lnwallet.WithAuxResolver(s))
×
1116
        })
×
1117

1118
        // We create the state-machine object which wraps the database state.
1119
        lnChannel, err := lnwallet.NewLightningChannel(
45✔
1120
                nil, channel, nil, chanOpts...,
45✔
1121
        )
45✔
1122
        if err != nil {
45✔
1123
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1124
                        channel.FundingOutpoint, err)
×
1125
                return
×
1126
        }
×
1127

1128
        for {
196✔
1129
                channelState, shortChanID, err := f.getChannelOpeningState(
151✔
1130
                        &channel.FundingOutpoint,
151✔
1131
                )
151✔
1132
                if err == channeldb.ErrChannelNotFound {
179✔
1133
                        // Channel not in fundingManager's opening database,
28✔
1134
                        // meaning it was successfully announced to the
28✔
1135
                        // network.
28✔
1136
                        // TODO(halseth): could do graph consistency check
28✔
1137
                        // here, and re-add the edge if missing.
28✔
1138
                        log.Debugf("ChannelPoint(%v) with chan_id=%x not "+
28✔
1139
                                "found in opening database, assuming already "+
28✔
1140
                                "announced to the network",
28✔
1141
                                channel.FundingOutpoint, pendingChanID)
28✔
1142
                        return
28✔
1143
                } else if err != nil {
154✔
1144
                        log.Errorf("Unable to query database for "+
×
1145
                                "channel opening state(%v): %v",
×
1146
                                channel.FundingOutpoint, err)
×
1147
                        return
×
1148
                }
×
1149

1150
                // If we did find the channel in the opening state database, we
1151
                // have seen the funding transaction being confirmed, but there
1152
                // are still steps left of the setup procedure. We continue the
1153
                // procedure where we left off.
1154
                err = f.stateStep(
126✔
1155
                        channel, lnChannel, shortChanID, pendingChanID,
126✔
1156
                        channelState, updateChan,
126✔
1157
                )
126✔
1158
                if err != nil {
146✔
1159
                        log.Errorf("Unable to advance state(%v): %v",
20✔
1160
                                channel.FundingOutpoint, err)
20✔
1161
                        return
20✔
1162
                }
20✔
1163
        }
1164
}
1165

1166
// stateStep advances the confirmed channel one step in the funding state
1167
// machine. This method is synchronous and the new channel opening state will
1168
// have been written to the database when it successfully returns. The
1169
// updateChan can be set non-nil to get OpenStatusUpdates.
1170
func (f *Manager) stateStep(channel *channeldb.OpenChannel,
1171
        lnChannel *lnwallet.LightningChannel,
1172
        shortChanID *lnwire.ShortChannelID, pendingChanID PendingChanID,
1173
        channelState channelOpeningState,
1174
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
126✔
1175

126✔
1176
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
126✔
1177
        log.Debugf("Channel(%v) with ShortChanID %v has opening state %v",
126✔
1178
                chanID, shortChanID, channelState)
126✔
1179

126✔
1180
        switch channelState {
126✔
1181
        // The funding transaction was confirmed, but we did not successfully
1182
        // send the channelReady message to the peer, so let's do that now.
1183
        case markedOpen:
38✔
1184
                err := f.sendChannelReady(channel, lnChannel)
38✔
1185
                if err != nil {
39✔
1186
                        return fmt.Errorf("failed sending channelReady: %w",
1✔
1187
                                err)
1✔
1188
                }
1✔
1189

1190
                // As the channelReady message is now sent to the peer, the
1191
                // channel is moved to the next state of the state machine. It
1192
                // will be moved to the last state (actually deleted from the
1193
                // database) after the channel is finally announced.
1194
                err = f.saveChannelOpeningState(
37✔
1195
                        &channel.FundingOutpoint, channelReadySent,
37✔
1196
                        shortChanID,
37✔
1197
                )
37✔
1198
                if err != nil {
37✔
1199
                        return fmt.Errorf("error setting channel state to"+
×
1200
                                " channelReadySent: %w", err)
×
1201
                }
×
1202

1203
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
37✔
1204
                        "sent ChannelReady", chanID, shortChanID)
37✔
1205

37✔
1206
                return nil
37✔
1207

1208
        // channelReady was sent to peer, but the channel was not added to the
1209
        // graph and the channel announcement was not sent.
1210
        case channelReadySent:
63✔
1211
                // We must wait until we've received the peer's channel_ready
63✔
1212
                // before sending a channel_update according to BOLT#07.
63✔
1213
                received, err := f.receivedChannelReady(
63✔
1214
                        channel.IdentityPub, chanID,
63✔
1215
                )
63✔
1216
                if err != nil {
63✔
UNCOV
1217
                        return fmt.Errorf("failed to check if channel_ready "+
×
UNCOV
1218
                                "was received: %v", err)
×
UNCOV
1219
                }
×
1220

1221
                if !received {
102✔
1222
                        // We haven't received ChannelReady, so we'll continue
39✔
1223
                        // to the next iteration of the loop after sleeping for
39✔
1224
                        // checkPeerChannelReadyInterval.
39✔
1225
                        select {
39✔
1226
                        case <-time.After(checkPeerChannelReadyInterval):
27✔
1227
                        case <-f.quit:
15✔
1228
                                return ErrFundingManagerShuttingDown
15✔
1229
                        }
1230

1231
                        return nil
27✔
1232
                }
1233

1234
                return f.handleChannelReadyReceived(
27✔
1235
                        channel, shortChanID, pendingChanID, updateChan,
27✔
1236
                )
27✔
1237

1238
        // The channel was added to the Router's topology, but the channel
1239
        // announcement was not sent.
1240
        case addedToGraph:
31✔
1241
                if channel.IsZeroConf() {
40✔
1242
                        // If this is a zero-conf channel, then we will wait
9✔
1243
                        // for it to be confirmed before announcing it to the
9✔
1244
                        // greater network.
9✔
1245
                        err := f.waitForZeroConfChannel(channel)
9✔
1246
                        if err != nil {
14✔
1247
                                return fmt.Errorf("failed waiting for zero "+
5✔
1248
                                        "channel: %v", err)
5✔
1249
                        }
5✔
1250

1251
                        // Update the local shortChanID variable such that
1252
                        // annAfterSixConfs uses the confirmed SCID.
1253
                        confirmedScid := channel.ZeroConfRealScid()
7✔
1254
                        shortChanID = &confirmedScid
7✔
1255
                }
1256

1257
                err := f.annAfterSixConfs(channel, shortChanID)
29✔
1258
                if err != nil {
34✔
1259
                        return fmt.Errorf("error sending channel "+
5✔
1260
                                "announcement: %v", err)
5✔
1261
                }
5✔
1262

1263
                // We delete the channel opening state from our internal
1264
                // database as the opening process has succeeded. We can do
1265
                // this because we assume the AuthenticatedGossiper queues the
1266
                // announcement messages, and persists them in case of a daemon
1267
                // shutdown.
1268
                err = f.deleteChannelOpeningState(&channel.FundingOutpoint)
27✔
1269
                if err != nil {
27✔
1270
                        return fmt.Errorf("error deleting channel state: %w",
×
1271
                                err)
×
1272
                }
×
1273

1274
                // After the fee parameters have been stored in the
1275
                // announcement we can delete them from the database. For
1276
                // private channels we do not announce the channel policy to
1277
                // the network but still need to delete them from the database.
1278
                err = f.deleteInitialForwardingPolicy(chanID)
27✔
1279
                if err != nil {
27✔
1280
                        log.Infof("Could not delete initial policy for chanId "+
×
1281
                                "%x", chanID)
×
1282
                }
×
1283

1284
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
1285
                        "announced", chanID, shortChanID)
27✔
1286

27✔
1287
                return nil
27✔
1288
        }
1289

1290
        return fmt.Errorf("undefined channelState: %v", channelState)
×
1291
}
1292

1293
// advancePendingChannelState waits for a pending channel's funding tx to
1294
// confirm, and marks it open in the database when that happens.
1295
func (f *Manager) advancePendingChannelState(channel *channeldb.OpenChannel,
1296
        pendingChanID PendingChanID) error {
60✔
1297

60✔
1298
        if channel.IsZeroConf() {
67✔
1299
                // Persist the alias to the alias database.
7✔
1300
                baseScid := channel.ShortChannelID
7✔
1301
                err := f.cfg.AliasManager.AddLocalAlias(
7✔
1302
                        baseScid, baseScid, true, false,
7✔
1303
                )
7✔
1304
                if err != nil {
7✔
1305
                        return fmt.Errorf("error adding local alias to "+
×
1306
                                "store: %v", err)
×
1307
                }
×
1308

1309
                // We don't wait for zero-conf channels to be confirmed and
1310
                // instead immediately proceed with the rest of the funding
1311
                // flow. The channel opening state is stored under the alias
1312
                // SCID.
1313
                err = f.saveChannelOpeningState(
7✔
1314
                        &channel.FundingOutpoint, markedOpen,
7✔
1315
                        &channel.ShortChannelID,
7✔
1316
                )
7✔
1317
                if err != nil {
7✔
1318
                        return fmt.Errorf("error setting zero-conf channel "+
×
1319
                                "state to markedOpen: %v", err)
×
1320
                }
×
1321

1322
                // The ShortChannelID is already set since it's an alias, but
1323
                // we still need to mark the channel as no longer pending.
1324
                err = channel.MarkAsOpen(channel.ShortChannelID)
7✔
1325
                if err != nil {
7✔
1326
                        return fmt.Errorf("error setting zero-conf channel's "+
×
1327
                                "pending flag to false: %v", err)
×
1328
                }
×
1329

1330
                // Inform the ChannelNotifier that the channel has transitioned
1331
                // from pending open to open.
1332
                f.cfg.NotifyOpenChannelEvent(
7✔
1333
                        channel.FundingOutpoint, channel.IdentityPub,
7✔
1334
                )
7✔
1335

7✔
1336
                // Find and close the discoverySignal for this channel such
7✔
1337
                // that ChannelReady messages will be processed.
7✔
1338
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
7✔
1339
                discoverySignal, ok := f.localDiscoverySignals.Load(chanID)
7✔
1340
                if ok {
14✔
1341
                        close(discoverySignal)
7✔
1342
                }
7✔
1343

1344
                return nil
7✔
1345
        }
1346

1347
        confChannel, err := f.waitForFundingWithTimeout(channel)
56✔
1348
        if err == ErrConfirmationTimeout {
61✔
1349
                return f.fundingTimeout(channel, pendingChanID)
5✔
1350
        } else if err != nil {
83✔
1351
                return fmt.Errorf("error waiting for funding "+
24✔
1352
                        "confirmation for ChannelPoint(%v): %v",
24✔
1353
                        channel.FundingOutpoint, err)
24✔
1354
        }
24✔
1355

1356
        if blockchain.IsCoinBaseTx(confChannel.fundingTx) {
35✔
1357
                // If it's a coinbase transaction, we need to wait for it to
2✔
1358
                // mature. We wait out an additional MinAcceptDepth on top of
2✔
1359
                // the coinbase maturity as an extra margin of safety.
2✔
1360
                maturity := f.cfg.Wallet.Cfg.NetParams.CoinbaseMaturity
2✔
1361
                numCoinbaseConfs := uint32(maturity)
2✔
1362

2✔
1363
                if channel.NumConfsRequired > maturity {
2✔
1364
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1365
                }
×
1366

1367
                txid := &channel.FundingOutpoint.Hash
2✔
1368
                fundingScript, err := makeFundingScript(channel)
2✔
1369
                if err != nil {
2✔
1370
                        log.Errorf("unable to create funding script for "+
×
1371
                                "ChannelPoint(%v): %v",
×
1372
                                channel.FundingOutpoint, err)
×
1373

×
1374
                        return err
×
1375
                }
×
1376

1377
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
2✔
1378
                        txid, fundingScript, numCoinbaseConfs,
2✔
1379
                        channel.BroadcastHeight(),
2✔
1380
                )
2✔
1381
                if err != nil {
2✔
1382
                        log.Errorf("Unable to register for confirmation of "+
×
1383
                                "ChannelPoint(%v): %v",
×
1384
                                channel.FundingOutpoint, err)
×
1385

×
1386
                        return err
×
1387
                }
×
1388

1389
                select {
2✔
1390
                case _, ok := <-confNtfn.Confirmed:
2✔
1391
                        if !ok {
2✔
1392
                                return fmt.Errorf("ChainNotifier shutting "+
×
1393
                                        "down, can't complete funding flow "+
×
1394
                                        "for ChannelPoint(%v)",
×
1395
                                        channel.FundingOutpoint)
×
1396
                        }
×
1397

1398
                case <-f.quit:
×
1399
                        return ErrFundingManagerShuttingDown
×
1400
                }
1401
        }
1402

1403
        // Success, funding transaction was confirmed.
1404
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
33✔
1405
        log.Debugf("ChannelID(%v) is now fully confirmed! "+
33✔
1406
                "(shortChanID=%v)", chanID, confChannel.shortChanID)
33✔
1407

33✔
1408
        err = f.handleFundingConfirmation(channel, confChannel)
33✔
1409
        if err != nil {
33✔
1410
                return fmt.Errorf("unable to handle funding "+
×
1411
                        "confirmation for ChannelPoint(%v): %v",
×
1412
                        channel.FundingOutpoint, err)
×
1413
        }
×
1414

1415
        return nil
33✔
1416
}
1417

1418
// ProcessFundingMsg sends a message to the internal fundingManager goroutine,
1419
// allowing it to handle the lnwire.Message.
1420
func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer) {
219✔
1421
        select {
219✔
1422
        case f.fundingMsgs <- &fundingMsg{msg, peer}:
219✔
1423
        case <-f.quit:
×
1424
                return
×
1425
        }
1426
}
1427

1428
// fundeeProcessOpenChannel creates an initial 'ChannelReservation' within the
1429
// wallet, then responds to the source peer with an accept channel message
1430
// progressing the funding workflow.
1431
//
1432
// TODO(roasbeef): add error chan to all, let channelManager handle
1433
// error+propagate.
1434
//
1435
//nolint:funlen
1436
func (f *Manager) fundeeProcessOpenChannel(peer lnpeer.Peer,
1437
        msg *lnwire.OpenChannel) {
58✔
1438

58✔
1439
        // Check number of pending channels to be smaller than maximum allowed
58✔
1440
        // number and send ErrorGeneric to remote peer if condition is
58✔
1441
        // violated.
58✔
1442
        peerPubKey := peer.IdentityKey()
58✔
1443
        peerIDKey := newSerializedKey(peerPubKey)
58✔
1444

58✔
1445
        amt := msg.FundingAmount
58✔
1446

58✔
1447
        // We get all pending channels for this peer. This is the list of the
58✔
1448
        // active reservations and the channels pending open in the database.
58✔
1449
        f.resMtx.RLock()
58✔
1450
        reservations := f.activeReservations[peerIDKey]
58✔
1451

58✔
1452
        // We don't count reservations that were created from a canned funding
58✔
1453
        // shim. The user has registered the shim and therefore expects this
58✔
1454
        // channel to arrive.
58✔
1455
        numPending := 0
58✔
1456
        for _, res := range reservations {
70✔
1457
                if !res.reservation.IsCannedShim() {
24✔
1458
                        numPending++
12✔
1459
                }
12✔
1460
        }
1461
        f.resMtx.RUnlock()
58✔
1462

58✔
1463
        // Create the channel identifier.
58✔
1464
        cid := newChanIdentifier(msg.PendingChannelID)
58✔
1465

58✔
1466
        // Also count the channels that are already pending. There we don't know
58✔
1467
        // the underlying intent anymore, unfortunately.
58✔
1468
        channels, err := f.cfg.ChannelDB.FetchOpenChannels(peerPubKey)
58✔
1469
        if err != nil {
58✔
1470
                f.failFundingFlow(peer, cid, err)
×
1471
                return
×
1472
        }
×
1473

1474
        for _, c := range channels {
73✔
1475
                // Pending channels that have a non-zero thaw height were also
15✔
1476
                // created through a canned funding shim. Those also don't
15✔
1477
                // count towards the DoS protection limit.
15✔
1478
                //
15✔
1479
                // TODO(guggero): Properly store the funding type (wallet, shim,
15✔
1480
                // PSBT) on the channel so we don't need to use the thaw height.
15✔
1481
                if c.IsPending && c.ThawHeight == 0 {
26✔
1482
                        numPending++
11✔
1483
                }
11✔
1484
        }
1485

1486
        // TODO(roasbeef): modify to only accept a _single_ pending channel per
1487
        // block unless white listed
1488
        if numPending >= f.cfg.MaxPendingChannels {
65✔
1489
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
7✔
1490

7✔
1491
                return
7✔
1492
        }
7✔
1493

1494
        // Ensure that the pendingChansLimit is respected.
1495
        pendingChans, err := f.cfg.ChannelDB.FetchPendingChannels()
54✔
1496
        if err != nil {
54✔
1497
                f.failFundingFlow(peer, cid, err)
×
1498
                return
×
1499
        }
×
1500

1501
        if len(pendingChans) > pendingChansLimit {
54✔
1502
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1503
                return
×
1504
        }
×
1505

1506
        // We'll also reject any requests to create channels until we're fully
1507
        // synced to the network as we won't be able to properly validate the
1508
        // confirmation of the funding transaction.
1509
        isSynced, _, err := f.cfg.Wallet.IsSynced()
54✔
1510
        if err != nil || !isSynced {
54✔
1511
                if err != nil {
×
1512
                        log.Errorf("unable to query wallet: %v", err)
×
1513
                }
×
1514
                err := errors.New("Synchronizing blockchain")
×
1515
                f.failFundingFlow(peer, cid, err)
×
1516
                return
×
1517
        }
1518

1519
        // Ensure that the remote party respects our maximum channel size.
1520
        if amt > f.cfg.MaxChanSize {
59✔
1521
                f.failFundingFlow(
5✔
1522
                        peer, cid,
5✔
1523
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
5✔
1524
                )
5✔
1525
                return
5✔
1526
        }
5✔
1527

1528
        // We'll, also ensure that the remote party isn't attempting to propose
1529
        // a channel that's below our current min channel size.
1530
        if amt < f.cfg.MinChanSize {
55✔
1531
                f.failFundingFlow(
3✔
1532
                        peer, cid,
3✔
1533
                        lnwallet.ErrChanTooSmall(amt, f.cfg.MinChanSize),
3✔
1534
                )
3✔
1535
                return
3✔
1536
        }
3✔
1537

1538
        // If request specifies non-zero push amount and 'rejectpush' is set,
1539
        // signal an error.
1540
        if f.cfg.RejectPush && msg.PushAmount > 0 {
53✔
1541
                f.failFundingFlow(peer, cid, lnwallet.ErrNonZeroPushAmount())
1✔
1542
                return
1✔
1543
        }
1✔
1544

1545
        // Send the OpenChannel request to the ChannelAcceptor to determine
1546
        // whether this node will accept the channel.
1547
        chanReq := &chanacceptor.ChannelAcceptRequest{
51✔
1548
                Node:        peer.IdentityKey(),
51✔
1549
                OpenChanMsg: msg,
51✔
1550
        }
51✔
1551

51✔
1552
        // Query our channel acceptor to determine whether we should reject
51✔
1553
        // the channel.
51✔
1554
        acceptorResp := f.cfg.OpenChannelPredicate.Accept(chanReq)
51✔
1555
        if acceptorResp.RejectChannel() {
54✔
1556
                f.failFundingFlow(peer, cid, acceptorResp.ChanAcceptError)
3✔
1557
                return
3✔
1558
        }
3✔
1559

1560
        log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
51✔
1561
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
51✔
1562
                msg.CsvDelay, msg.PendingChannelID,
51✔
1563
                peer.IdentityKey().SerializeCompressed())
51✔
1564

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

1586
        var scidFeatureVal bool
51✔
1587
        if hasFeatures(
51✔
1588
                peer.LocalFeatures(), peer.RemoteFeatures(),
51✔
1589
                lnwire.ScidAliasOptional,
51✔
1590
        ) {
57✔
1591

6✔
1592
                scidFeatureVal = true
6✔
1593
        }
6✔
1594

1595
        var (
51✔
1596
                zeroConf bool
51✔
1597
                scid     bool
51✔
1598
        )
51✔
1599

51✔
1600
        // Only echo back a channel type in AcceptChannel if we actually used
51✔
1601
        // explicit negotiation above.
51✔
1602
        if chanType != nil {
58✔
1603
                // Check if the channel type includes the zero-conf or
7✔
1604
                // scid-alias bits.
7✔
1605
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
1606
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
1607
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
1608

7✔
1609
                // If the zero-conf channel type was negotiated, ensure that
7✔
1610
                // the acceptor allows it.
7✔
1611
                if zeroConf && !acceptorResp.ZeroConf {
7✔
1612
                        // Fail the funding flow.
×
1613
                        flowErr := fmt.Errorf("channel acceptor blocked " +
×
1614
                                "zero-conf channel negotiation")
×
1615
                        log.Errorf("Cancelling funding flow for %v based on "+
×
1616
                                "channel acceptor response: %v", cid, flowErr)
×
1617
                        f.failFundingFlow(peer, cid, flowErr)
×
1618
                        return
×
1619
                }
×
1620

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

1638
                        // Set zeroConf to true to enable the zero-conf flow.
1639
                        zeroConf = true
×
1640
                }
1641
        }
1642

1643
        public := msg.ChannelFlags&lnwire.FFAnnounceChannel != 0
51✔
1644
        switch {
51✔
1645
        // Sending the option-scid-alias channel type for a public channel is
1646
        // disallowed.
1647
        case public && scid:
×
1648
                err = fmt.Errorf("option-scid-alias chantype for public " +
×
1649
                        "channel")
×
1650
                log.Errorf("Cancelling funding flow for public channel %v "+
×
1651
                        "with scid-alias: %v", cid, err)
×
1652
                f.failFundingFlow(peer, cid, err)
×
1653

×
1654
                return
×
1655

1656
        // The current variant of taproot channels can only be used with
1657
        // unadvertised channels for now.
1658
        case commitType.IsTaproot() && public:
×
1659
                err = fmt.Errorf("taproot channel type for public channel")
×
1660
                log.Errorf("Cancelling funding flow for public taproot "+
×
1661
                        "channel %v: %v", cid, err)
×
1662
                f.failFundingFlow(peer, cid, err)
×
1663

×
1664
                return
×
1665
        }
1666

1667
        // At this point, if we have an AuxFundingController active, we'll
1668
        // check to see if we have a special tapscript root to use in our
1669
        // MuSig funding output.
1670
        tapscriptRoot, err := fn.MapOptionZ(
51✔
1671
                f.cfg.AuxFundingController,
51✔
1672
                func(c AuxFundingController) AuxTapscriptResult {
51✔
1673
                        return c.DeriveTapscriptRoot(msg.PendingChannelID)
×
1674
                },
×
1675
        ).Unpack()
1676
        if err != nil {
51✔
1677
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
1678
                log.Error(err)
×
1679
                f.failFundingFlow(peer, cid, err)
×
1680

×
1681
                return
×
1682
        }
×
1683

1684
        req := &lnwallet.InitFundingReserveMsg{
51✔
1685
                ChainHash:        &msg.ChainHash,
51✔
1686
                PendingChanID:    msg.PendingChannelID,
51✔
1687
                NodeID:           peer.IdentityKey(),
51✔
1688
                NodeAddr:         peer.Address(),
51✔
1689
                LocalFundingAmt:  0,
51✔
1690
                RemoteFundingAmt: amt,
51✔
1691
                CommitFeePerKw:   chainfee.SatPerKWeight(msg.FeePerKiloWeight),
51✔
1692
                FundingFeePerKw:  0,
51✔
1693
                PushMSat:         msg.PushAmount,
51✔
1694
                Flags:            msg.ChannelFlags,
51✔
1695
                MinConfs:         1,
51✔
1696
                CommitType:       commitType,
51✔
1697
                ZeroConf:         zeroConf,
51✔
1698
                OptionScidAlias:  scid,
51✔
1699
                ScidAliasFeature: scidFeatureVal,
51✔
1700
                TapscriptRoot:    tapscriptRoot,
51✔
1701
        }
51✔
1702

51✔
1703
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
51✔
1704
        if err != nil {
51✔
1705
                log.Errorf("Unable to initialize reservation: %v", err)
×
1706
                f.failFundingFlow(peer, cid, err)
×
1707
                return
×
1708
        }
×
1709

1710
        log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
51✔
1711
                "cannedShim=%v", reservation.IsZeroConf(),
51✔
1712
                reservation.IsPsbt(), reservation.IsCannedShim())
51✔
1713

51✔
1714
        if zeroConf {
56✔
1715
                // Store an alias for zero-conf channels. Other option-scid
5✔
1716
                // channels will do this at a later point.
5✔
1717
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
1718
                if err != nil {
5✔
1719
                        log.Errorf("Unable to request alias: %v", err)
×
1720
                        f.failFundingFlow(peer, cid, err)
×
1721
                        return
×
1722
                }
×
1723

1724
                reservation.AddAlias(aliasScid)
5✔
1725
        }
1726

1727
        // As we're the responder, we get to specify the number of confirmations
1728
        // that we require before both of us consider the channel open. We'll
1729
        // use our mapping to derive the proper number of confirmations based on
1730
        // the amount of the channel, and also if any funds are being pushed to
1731
        // us. If a depth value was set by our channel acceptor, we will use
1732
        // that value instead.
1733
        numConfsReq := f.cfg.NumRequiredConfs(msg.FundingAmount, msg.PushAmount)
51✔
1734
        if acceptorResp.MinAcceptDepth != 0 {
51✔
1735
                numConfsReq = acceptorResp.MinAcceptDepth
×
1736
        }
×
1737

1738
        // We'll ignore the min_depth calculated above if this is a zero-conf
1739
        // channel.
1740
        if zeroConf {
56✔
1741
                numConfsReq = 0
5✔
1742
        }
5✔
1743

1744
        reservation.SetNumConfsRequired(numConfsReq)
51✔
1745

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

1767
        // If the fundee didn't provide an upfront-shutdown address via
1768
        // the channel acceptor, fall back to the configured shutdown
1769
        // script (if any).
1770
        shutdownScript := acceptorResp.UpfrontShutdown
50✔
1771
        if len(shutdownScript) == 0 {
100✔
1772
                f.cfg.ShutdownScript.WhenSome(
50✔
1773
                        func(script lnwire.DeliveryAddress) {
53✔
1774
                                shutdownScript = script
3✔
1775
                        },
3✔
1776
                )
1777
        }
1778

1779
        // Check whether the peer supports upfront shutdown, and get a new
1780
        // wallet address if our node is configured to set shutdown addresses by
1781
        // default. We use the upfront shutdown script provided by our channel
1782
        // acceptor (if any) in lieu of user input.
1783
        shutdown, err := getUpfrontShutdownScript(
50✔
1784
                f.cfg.EnableUpfrontShutdown, peer, shutdownScript,
50✔
1785
                f.selectShutdownScript,
50✔
1786
        )
50✔
1787
        if err != nil {
50✔
1788
                f.failFundingFlow(
×
1789
                        peer, cid,
×
1790
                        fmt.Errorf("getUpfrontShutdownScript error: %w", err),
×
1791
                )
×
1792
                return
×
1793
        }
×
1794
        reservation.SetOurUpfrontShutdown(shutdown)
50✔
1795

50✔
1796
        // If a script enforced channel lease is being proposed, we'll need to
50✔
1797
        // validate its custom TLV records.
50✔
1798
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
53✔
1799
                if msg.LeaseExpiry == nil {
3✔
1800
                        err := errors.New("missing lease expiry")
×
1801
                        f.failFundingFlow(peer, cid, err)
×
1802
                        return
×
1803
                }
×
1804

1805
                // If we had a shim registered for this channel prior to
1806
                // receiving its corresponding OpenChannel message, then we'll
1807
                // validate the proposed LeaseExpiry against what was registered
1808
                // in our shim.
1809
                if reservation.LeaseExpiry() != 0 {
6✔
1810
                        if uint32(*msg.LeaseExpiry) !=
3✔
1811
                                reservation.LeaseExpiry() {
3✔
1812

×
1813
                                err := errors.New("lease expiry mismatch")
×
1814
                                f.failFundingFlow(peer, cid, err)
×
1815
                                return
×
1816
                        }
×
1817
                }
1818
        }
1819

1820
        log.Infof("Requiring %v confirmations for pendingChan(%x): "+
50✔
1821
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
50✔
1822
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
50✔
1823
                commitType, msg.UpfrontShutdownScript)
50✔
1824

50✔
1825
        // Generate our required constraints for the remote party, using the
50✔
1826
        // values provided by the channel acceptor if they are non-zero.
50✔
1827
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
50✔
1828
        if acceptorResp.CSVDelay != 0 {
50✔
1829
                remoteCsvDelay = acceptorResp.CSVDelay
×
1830
        }
×
1831

1832
        // If our default dust limit was above their ChannelReserve, we change
1833
        // it to the ChannelReserve. We must make sure the ChannelReserve we
1834
        // send in the AcceptChannel message is above both dust limits.
1835
        // Therefore, take the maximum of msg.DustLimit and our dust limit.
1836
        //
1837
        // NOTE: Even with this bounding, the ChannelAcceptor may return an
1838
        // BOLT#02-invalid ChannelReserve.
1839
        maxDustLimit := reservation.OurContribution().DustLimit
50✔
1840
        if msg.DustLimit > maxDustLimit {
50✔
1841
                maxDustLimit = msg.DustLimit
×
1842
        }
×
1843

1844
        chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
50✔
1845
        if acceptorResp.Reserve != 0 {
50✔
1846
                chanReserve = acceptorResp.Reserve
×
1847
        }
×
1848

1849
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
50✔
1850
        if acceptorResp.InFlightTotal != 0 {
50✔
1851
                remoteMaxValue = acceptorResp.InFlightTotal
×
1852
        }
×
1853

1854
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
50✔
1855
        if acceptorResp.HtlcLimit != 0 {
50✔
1856
                maxHtlcs = acceptorResp.HtlcLimit
×
1857
        }
×
1858

1859
        // Default to our default minimum hltc value, replacing it with the
1860
        // channel acceptor's value if it is set.
1861
        minHtlc := f.cfg.DefaultMinHtlcIn
50✔
1862
        if acceptorResp.MinHtlcIn != 0 {
50✔
1863
                minHtlc = acceptorResp.MinHtlcIn
×
1864
        }
×
1865

1866
        // If we are handling a FundingOpen request then we need to specify the
1867
        // default channel fees since they are not provided by the responder
1868
        // interactively.
1869
        ourContribution := reservation.OurContribution()
50✔
1870
        forwardingPolicy := f.defaultForwardingPolicy(
50✔
1871
                ourContribution.ChannelStateBounds,
50✔
1872
        )
50✔
1873

50✔
1874
        // Once the reservation has been created successfully, we add it to
50✔
1875
        // this peer's map of pending reservations to track this particular
50✔
1876
        // reservation until either abort or completion.
50✔
1877
        f.resMtx.Lock()
50✔
1878
        if _, ok := f.activeReservations[peerIDKey]; !ok {
96✔
1879
                f.activeReservations[peerIDKey] = make(pendingChannels)
46✔
1880
        }
46✔
1881
        resCtx := &reservationWithCtx{
50✔
1882
                reservation:       reservation,
50✔
1883
                chanAmt:           amt,
50✔
1884
                forwardingPolicy:  *forwardingPolicy,
50✔
1885
                remoteCsvDelay:    remoteCsvDelay,
50✔
1886
                remoteMinHtlc:     minHtlc,
50✔
1887
                remoteMaxValue:    remoteMaxValue,
50✔
1888
                remoteMaxHtlcs:    maxHtlcs,
50✔
1889
                remoteChanReserve: chanReserve,
50✔
1890
                maxLocalCsv:       f.cfg.MaxLocalCSVDelay,
50✔
1891
                channelType:       chanType,
50✔
1892
                err:               make(chan error, 1),
50✔
1893
                peer:              peer,
50✔
1894
        }
50✔
1895
        f.activeReservations[peerIDKey][msg.PendingChannelID] = resCtx
50✔
1896
        f.resMtx.Unlock()
50✔
1897

50✔
1898
        // Update the timestamp once the fundingOpenMsg has been handled.
50✔
1899
        defer resCtx.updateTimestamp()
50✔
1900

50✔
1901
        cfg := channeldb.ChannelConfig{
50✔
1902
                ChannelStateBounds: channeldb.ChannelStateBounds{
50✔
1903
                        MaxPendingAmount: remoteMaxValue,
50✔
1904
                        ChanReserve:      chanReserve,
50✔
1905
                        MinHTLC:          minHtlc,
50✔
1906
                        MaxAcceptedHtlcs: maxHtlcs,
50✔
1907
                },
50✔
1908
                CommitmentParams: channeldb.CommitmentParams{
50✔
1909
                        DustLimit: msg.DustLimit,
50✔
1910
                        CsvDelay:  remoteCsvDelay,
50✔
1911
                },
50✔
1912
                MultiSigKey: keychain.KeyDescriptor{
50✔
1913
                        PubKey: copyPubKey(msg.FundingKey),
50✔
1914
                },
50✔
1915
                RevocationBasePoint: keychain.KeyDescriptor{
50✔
1916
                        PubKey: copyPubKey(msg.RevocationPoint),
50✔
1917
                },
50✔
1918
                PaymentBasePoint: keychain.KeyDescriptor{
50✔
1919
                        PubKey: copyPubKey(msg.PaymentPoint),
50✔
1920
                },
50✔
1921
                DelayBasePoint: keychain.KeyDescriptor{
50✔
1922
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
50✔
1923
                },
50✔
1924
                HtlcBasePoint: keychain.KeyDescriptor{
50✔
1925
                        PubKey: copyPubKey(msg.HtlcPoint),
50✔
1926
                },
50✔
1927
        }
50✔
1928

50✔
1929
        // With our parameters set, we'll now process their contribution so we
50✔
1930
        // can move the funding workflow ahead.
50✔
1931
        remoteContribution := &lnwallet.ChannelContribution{
50✔
1932
                FundingAmount:        amt,
50✔
1933
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
50✔
1934
                ChannelConfig:        &cfg,
50✔
1935
                UpfrontShutdown:      msg.UpfrontShutdownScript,
50✔
1936
        }
50✔
1937

50✔
1938
        if resCtx.reservation.IsTaproot() {
55✔
1939
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
1940
                if err != nil {
5✔
1941
                        log.Error(errNoLocalNonce)
×
1942

×
1943
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1944

×
1945
                        return
×
1946
                }
×
1947

1948
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
1949
                        PubNonce: localNonce,
5✔
1950
                }
5✔
1951
        }
1952

1953
        err = reservation.ProcessSingleContribution(remoteContribution)
50✔
1954
        if err != nil {
56✔
1955
                log.Errorf("unable to add contribution reservation: %v", err)
6✔
1956
                f.failFundingFlow(peer, cid, err)
6✔
1957
                return
6✔
1958
        }
6✔
1959

1960
        log.Infof("Sending fundingResp for pending_id(%x)",
44✔
1961
                msg.PendingChannelID)
44✔
1962
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
44✔
1963
        log.Debugf("Remote party accepted channel state space bounds: %v",
44✔
1964
                lnutils.SpewLogClosure(bounds))
44✔
1965
        params := remoteContribution.ChannelConfig.CommitmentParams
44✔
1966
        log.Debugf("Remote party accepted commitment rendering params: %v",
44✔
1967
                lnutils.SpewLogClosure(params))
44✔
1968

44✔
1969
        reservation.SetState(lnwallet.SentAcceptChannel)
44✔
1970

44✔
1971
        // With the initiator's contribution recorded, respond with our
44✔
1972
        // contribution in the next message of the workflow.
44✔
1973
        fundingAccept := lnwire.AcceptChannel{
44✔
1974
                PendingChannelID:      msg.PendingChannelID,
44✔
1975
                DustLimit:             ourContribution.DustLimit,
44✔
1976
                MaxValueInFlight:      remoteMaxValue,
44✔
1977
                ChannelReserve:        chanReserve,
44✔
1978
                MinAcceptDepth:        uint32(numConfsReq),
44✔
1979
                HtlcMinimum:           minHtlc,
44✔
1980
                CsvDelay:              remoteCsvDelay,
44✔
1981
                MaxAcceptedHTLCs:      maxHtlcs,
44✔
1982
                FundingKey:            ourContribution.MultiSigKey.PubKey,
44✔
1983
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
44✔
1984
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
44✔
1985
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
44✔
1986
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
44✔
1987
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
44✔
1988
                UpfrontShutdownScript: ourContribution.UpfrontShutdown,
44✔
1989
                ChannelType:           chanType,
44✔
1990
                LeaseExpiry:           msg.LeaseExpiry,
44✔
1991
        }
44✔
1992

44✔
1993
        if commitType.IsTaproot() {
49✔
1994
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
1995
                        ourContribution.LocalNonce.PubNonce,
5✔
1996
                )
5✔
1997
        }
5✔
1998

1999
        if err := peer.SendMessage(true, &fundingAccept); err != nil {
44✔
2000
                log.Errorf("unable to send funding response to peer: %v", err)
×
2001
                f.failFundingFlow(peer, cid, err)
×
2002
                return
×
2003
        }
×
2004
}
2005

2006
// funderProcessAcceptChannel processes a response to the workflow initiation
2007
// sent by the remote peer. This message then queues a message with the funding
2008
// outpoint, and a commitment signature to the remote peer.
2009
//
2010
//nolint:funlen
2011
func (f *Manager) funderProcessAcceptChannel(peer lnpeer.Peer,
2012
        msg *lnwire.AcceptChannel) {
36✔
2013

36✔
2014
        pendingChanID := msg.PendingChannelID
36✔
2015
        peerKey := peer.IdentityKey()
36✔
2016
        var peerKeyBytes []byte
36✔
2017
        if peerKey != nil {
72✔
2018
                peerKeyBytes = peerKey.SerializeCompressed()
36✔
2019
        }
36✔
2020

2021
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
36✔
2022
        if err != nil {
36✔
2023
                log.Warnf("Can't find reservation (peerKey:%x, chan_id:%v)",
×
2024
                        peerKeyBytes, pendingChanID)
×
2025
                return
×
2026
        }
×
2027

2028
        // Update the timestamp once the fundingAcceptMsg has been handled.
2029
        defer resCtx.updateTimestamp()
36✔
2030

36✔
2031
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
36✔
2032
                return
×
2033
        }
×
2034

2035
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
36✔
2036
                pendingChanID[:])
36✔
2037

36✔
2038
        // Create the channel identifier.
36✔
2039
        cid := newChanIdentifier(msg.PendingChannelID)
36✔
2040

36✔
2041
        // Perform some basic validation of any custom TLV records included.
36✔
2042
        //
36✔
2043
        // TODO: Return errors as funding.Error to give context to remote peer?
36✔
2044
        if resCtx.channelType != nil {
43✔
2045
                // We'll want to quickly check that the ChannelType echoed by
7✔
2046
                // the channel request recipient matches what we proposed.
7✔
2047
                if msg.ChannelType == nil {
8✔
2048
                        err := errors.New("explicit channel type not echoed " +
1✔
2049
                                "back")
1✔
2050
                        f.failFundingFlow(peer, cid, err)
1✔
2051
                        return
1✔
2052
                }
1✔
2053
                proposedFeatures := lnwire.RawFeatureVector(*resCtx.channelType)
6✔
2054
                ackedFeatures := lnwire.RawFeatureVector(*msg.ChannelType)
6✔
2055
                if !proposedFeatures.Equals(&ackedFeatures) {
6✔
2056
                        err := errors.New("channel type mismatch")
×
2057
                        f.failFundingFlow(peer, cid, err)
×
2058
                        return
×
2059
                }
×
2060

2061
                // We'll want to do the same with the LeaseExpiry if one should
2062
                // be set.
2063
                if resCtx.reservation.LeaseExpiry() != 0 {
9✔
2064
                        if msg.LeaseExpiry == nil {
3✔
2065
                                err := errors.New("lease expiry not echoed " +
×
2066
                                        "back")
×
2067
                                f.failFundingFlow(peer, cid, err)
×
2068
                                return
×
2069
                        }
×
2070
                        if uint32(*msg.LeaseExpiry) !=
3✔
2071
                                resCtx.reservation.LeaseExpiry() {
3✔
2072

×
2073
                                err := errors.New("lease expiry mismatch")
×
2074
                                f.failFundingFlow(peer, cid, err)
×
2075
                                return
×
2076
                        }
×
2077
                }
2078
        } else if msg.ChannelType != nil {
29✔
2079
                // The spec isn't too clear about whether it's okay to set the
×
2080
                // channel type in the accept_channel response if we didn't
×
2081
                // explicitly set it in the open_channel message. For now, we
×
2082
                // check that it's the same type we'd have arrived through
×
2083
                // implicit negotiation. If it's another type, we fail the flow.
×
2084
                _, implicitCommitType := implicitNegotiateCommitmentType(
×
2085
                        peer.LocalFeatures(), peer.RemoteFeatures(),
×
2086
                )
×
2087

×
2088
                _, negotiatedCommitType, err := negotiateCommitmentType(
×
2089
                        msg.ChannelType, peer.LocalFeatures(),
×
2090
                        peer.RemoteFeatures(),
×
2091
                )
×
2092
                if err != nil {
×
2093
                        err := errors.New("received unexpected channel type")
×
2094
                        f.failFundingFlow(peer, cid, err)
×
2095
                        return
×
2096
                }
×
2097

2098
                if implicitCommitType != negotiatedCommitType {
×
2099
                        err := errors.New("negotiated unexpected channel type")
×
2100
                        f.failFundingFlow(peer, cid, err)
×
2101
                        return
×
2102
                }
×
2103
        }
2104

2105
        // The required number of confirmations should not be greater than the
2106
        // maximum number of confirmations required by the ChainNotifier to
2107
        // properly dispatch confirmations.
2108
        if msg.MinAcceptDepth > chainntnfs.MaxNumConfs {
36✔
2109
                err := lnwallet.ErrNumConfsTooLarge(
1✔
2110
                        msg.MinAcceptDepth, chainntnfs.MaxNumConfs,
1✔
2111
                )
1✔
2112
                log.Warnf("Unacceptable channel constraints: %v", err)
1✔
2113
                f.failFundingFlow(peer, cid, err)
1✔
2114
                return
1✔
2115
        }
1✔
2116

2117
        // Check that zero-conf channels have minimum depth set to 0.
2118
        if resCtx.reservation.IsZeroConf() && msg.MinAcceptDepth != 0 {
34✔
2119
                err = fmt.Errorf("zero-conf channel has min_depth non-zero")
×
2120
                log.Warn(err)
×
2121
                f.failFundingFlow(peer, cid, err)
×
2122
                return
×
2123
        }
×
2124

2125
        // If this is not a zero-conf channel but the peer responded with a
2126
        // min-depth of zero, we will use our minimum of 1 instead.
2127
        minDepth := msg.MinAcceptDepth
34✔
2128
        if !resCtx.reservation.IsZeroConf() && minDepth == 0 {
34✔
2129
                log.Infof("Responder to pending_id=%v sent a minimum "+
×
2130
                        "confirmation depth of 0 for non-zero-conf channel. "+
×
2131
                        "We will use a minimum depth of 1 instead.",
×
2132
                        cid.tempChanID)
×
2133

×
2134
                minDepth = 1
×
2135
        }
×
2136

2137
        // We'll also specify the responder's preference for the number of
2138
        // required confirmations, and also the set of channel constraints
2139
        // they've specified for commitment states we can create.
2140
        resCtx.reservation.SetNumConfsRequired(uint16(minDepth))
34✔
2141
        bounds := channeldb.ChannelStateBounds{
34✔
2142
                ChanReserve:      msg.ChannelReserve,
34✔
2143
                MaxPendingAmount: msg.MaxValueInFlight,
34✔
2144
                MinHTLC:          msg.HtlcMinimum,
34✔
2145
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
34✔
2146
        }
34✔
2147
        commitParams := channeldb.CommitmentParams{
34✔
2148
                DustLimit: msg.DustLimit,
34✔
2149
                CsvDelay:  msg.CsvDelay,
34✔
2150
        }
34✔
2151
        err = resCtx.reservation.CommitConstraints(
34✔
2152
                &bounds, &commitParams, resCtx.maxLocalCsv, false,
34✔
2153
        )
34✔
2154
        if err != nil {
35✔
2155
                log.Warnf("Unacceptable channel constraints: %v", err)
1✔
2156
                f.failFundingFlow(peer, cid, err)
1✔
2157
                return
1✔
2158
        }
1✔
2159

2160
        cfg := channeldb.ChannelConfig{
33✔
2161
                ChannelStateBounds: channeldb.ChannelStateBounds{
33✔
2162
                        MaxPendingAmount: resCtx.remoteMaxValue,
33✔
2163
                        ChanReserve:      resCtx.remoteChanReserve,
33✔
2164
                        MinHTLC:          resCtx.remoteMinHtlc,
33✔
2165
                        MaxAcceptedHtlcs: resCtx.remoteMaxHtlcs,
33✔
2166
                },
33✔
2167
                CommitmentParams: channeldb.CommitmentParams{
33✔
2168
                        DustLimit: msg.DustLimit,
33✔
2169
                        CsvDelay:  resCtx.remoteCsvDelay,
33✔
2170
                },
33✔
2171
                MultiSigKey: keychain.KeyDescriptor{
33✔
2172
                        PubKey: copyPubKey(msg.FundingKey),
33✔
2173
                },
33✔
2174
                RevocationBasePoint: keychain.KeyDescriptor{
33✔
2175
                        PubKey: copyPubKey(msg.RevocationPoint),
33✔
2176
                },
33✔
2177
                PaymentBasePoint: keychain.KeyDescriptor{
33✔
2178
                        PubKey: copyPubKey(msg.PaymentPoint),
33✔
2179
                },
33✔
2180
                DelayBasePoint: keychain.KeyDescriptor{
33✔
2181
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
33✔
2182
                },
33✔
2183
                HtlcBasePoint: keychain.KeyDescriptor{
33✔
2184
                        PubKey: copyPubKey(msg.HtlcPoint),
33✔
2185
                },
33✔
2186
        }
33✔
2187

33✔
2188
        // The remote node has responded with their portion of the channel
33✔
2189
        // contribution. At this point, we can process their contribution which
33✔
2190
        // allows us to construct and sign both the commitment transaction, and
33✔
2191
        // the funding transaction.
33✔
2192
        remoteContribution := &lnwallet.ChannelContribution{
33✔
2193
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
33✔
2194
                ChannelConfig:        &cfg,
33✔
2195
                UpfrontShutdown:      msg.UpfrontShutdownScript,
33✔
2196
        }
33✔
2197

33✔
2198
        if resCtx.reservation.IsTaproot() {
38✔
2199
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
2200
                if err != nil {
5✔
2201
                        log.Error(errNoLocalNonce)
×
2202

×
2203
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2204

×
2205
                        return
×
2206
                }
×
2207

2208
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
2209
                        PubNonce: localNonce,
5✔
2210
                }
5✔
2211
        }
2212

2213
        err = resCtx.reservation.ProcessContribution(remoteContribution)
33✔
2214

33✔
2215
        // The wallet has detected that a PSBT funding process was requested by
33✔
2216
        // the user and has halted the funding process after negotiating the
33✔
2217
        // multisig keys. We now have everything that is needed for the user to
33✔
2218
        // start constructing a PSBT that sends to the multisig funding address.
33✔
2219
        var psbtIntent *chanfunding.PsbtIntent
33✔
2220
        if psbtErr, ok := err.(*lnwallet.PsbtFundingRequired); ok {
36✔
2221
                // Return the information that is needed by the user to
3✔
2222
                // construct the PSBT back to the caller.
3✔
2223
                addr, amt, packet, err := psbtErr.Intent.FundingParams()
3✔
2224
                if err != nil {
3✔
2225
                        log.Errorf("Unable to process PSBT funding params "+
×
2226
                                "for contribution from %x: %v", peerKeyBytes,
×
2227
                                err)
×
2228
                        f.failFundingFlow(peer, cid, err)
×
2229
                        return
×
2230
                }
×
2231
                var buf bytes.Buffer
3✔
2232
                err = packet.Serialize(&buf)
3✔
2233
                if err != nil {
3✔
2234
                        log.Errorf("Unable to serialize PSBT for "+
×
2235
                                "contribution from %x: %v", peerKeyBytes, err)
×
2236
                        f.failFundingFlow(peer, cid, err)
×
2237
                        return
×
2238
                }
×
2239
                resCtx.updates <- &lnrpc.OpenStatusUpdate{
3✔
2240
                        PendingChanId: pendingChanID[:],
3✔
2241
                        Update: &lnrpc.OpenStatusUpdate_PsbtFund{
3✔
2242
                                PsbtFund: &lnrpc.ReadyForPsbtFunding{
3✔
2243
                                        FundingAddress: addr.EncodeAddress(),
3✔
2244
                                        FundingAmount:  amt,
3✔
2245
                                        Psbt:           buf.Bytes(),
3✔
2246
                                },
3✔
2247
                        },
3✔
2248
                }
3✔
2249
                psbtIntent = psbtErr.Intent
3✔
2250
        } else if err != nil {
33✔
2251
                log.Errorf("Unable to process contribution from %x: %v",
×
2252
                        peerKeyBytes, err)
×
2253
                f.failFundingFlow(peer, cid, err)
×
2254
                return
×
2255
        }
×
2256

2257
        log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+
33✔
2258
                "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
33✔
2259
                msg.CsvDelay)
33✔
2260
        bounds = remoteContribution.ChannelConfig.ChannelStateBounds
33✔
2261
        log.Debugf("Remote party accepted channel state space bounds: %v",
33✔
2262
                lnutils.SpewLogClosure(bounds))
33✔
2263
        commitParams = remoteContribution.ChannelConfig.CommitmentParams
33✔
2264
        log.Debugf("Remote party accepted commitment rendering params: %v",
33✔
2265
                lnutils.SpewLogClosure(commitParams))
33✔
2266

33✔
2267
        // If the user requested funding through a PSBT, we cannot directly
33✔
2268
        // continue now and need to wait for the fully funded and signed PSBT
33✔
2269
        // to arrive. To not block any other channels from opening, we wait in
33✔
2270
        // a separate goroutine.
33✔
2271
        if psbtIntent != nil {
36✔
2272
                f.wg.Add(1)
3✔
2273
                go func() {
6✔
2274
                        defer f.wg.Done()
3✔
2275

3✔
2276
                        f.waitForPsbt(psbtIntent, resCtx, cid)
3✔
2277
                }()
3✔
2278

2279
                // With the new goroutine spawned, we can now exit to unblock
2280
                // the main event loop.
2281
                return
3✔
2282
        }
2283

2284
        // In a normal, non-PSBT funding flow, we can jump directly to the next
2285
        // step where we expect our contribution to be finalized.
2286
        f.continueFundingAccept(resCtx, cid)
33✔
2287
}
2288

2289
// waitForPsbt blocks until either a signed PSBT arrives, an error occurs or
2290
// the funding manager shuts down. In the case of a valid PSBT, the funding flow
2291
// is continued.
2292
//
2293
// NOTE: This method must be called as a goroutine.
2294
func (f *Manager) waitForPsbt(intent *chanfunding.PsbtIntent,
2295
        resCtx *reservationWithCtx, cid *chanIdentifier) {
3✔
2296

3✔
2297
        // failFlow is a helper that logs an error message with the current
3✔
2298
        // context and then fails the funding flow.
3✔
2299
        peerKey := resCtx.peer.IdentityKey()
3✔
2300
        failFlow := func(errMsg string, cause error) {
6✔
2301
                log.Errorf("Unable to handle funding accept message "+
3✔
2302
                        "for peer_key=%x, pending_chan_id=%x: %s: %v",
3✔
2303
                        peerKey.SerializeCompressed(), cid.tempChanID, errMsg,
3✔
2304
                        cause)
3✔
2305
                f.failFundingFlow(resCtx.peer, cid, cause)
3✔
2306
        }
3✔
2307

2308
        // We'll now wait until the intent has received the final and complete
2309
        // funding transaction. If the channel is closed without any error being
2310
        // sent, we know everything's going as expected.
2311
        select {
3✔
2312
        case err := <-intent.PsbtReady:
3✔
2313
                switch err {
3✔
2314
                // If the user canceled the funding reservation, we need to
2315
                // inform the other peer about us canceling the reservation.
2316
                case chanfunding.ErrUserCanceled:
3✔
2317
                        failFlow("aborting PSBT flow", err)
3✔
2318
                        return
3✔
2319

2320
                // If the remote canceled the funding reservation, we don't need
2321
                // to send another fail message. But we want to inform the user
2322
                // about what happened.
2323
                case chanfunding.ErrRemoteCanceled:
3✔
2324
                        log.Infof("Remote canceled, aborting PSBT flow "+
3✔
2325
                                "for peer_key=%x, pending_chan_id=%x",
3✔
2326
                                peerKey.SerializeCompressed(), cid.tempChanID)
3✔
2327
                        return
3✔
2328

2329
                // Nil error means the flow continues normally now.
2330
                case nil:
3✔
2331

2332
                // For any other error, we'll fail the funding flow.
2333
                default:
×
2334
                        failFlow("error waiting for PSBT flow", err)
×
2335
                        return
×
2336
                }
2337

2338
                // At this point, we'll see if there's an AuxFundingDesc we
2339
                // need to deliver so the funding process can continue
2340
                // properly.
2341
                auxFundingDesc, err := fn.MapOptionZ(
3✔
2342
                        f.cfg.AuxFundingController,
3✔
2343
                        func(c AuxFundingController) AuxFundingDescResult {
3✔
2344
                                return c.DescFromPendingChanID(
×
2345
                                        cid.tempChanID,
×
2346
                                        lnwallet.NewAuxChanState(
×
2347
                                                resCtx.reservation.ChanState(),
×
2348
                                        ),
×
2349
                                        resCtx.reservation.CommitmentKeyRings(),
×
2350
                                        true,
×
2351
                                )
×
2352
                        },
×
2353
                ).Unpack()
2354
                if err != nil {
3✔
2355
                        failFlow("error continuing PSBT flow", err)
×
2356
                        return
×
2357
                }
×
2358

2359
                // A non-nil error means we can continue the funding flow.
2360
                // Notify the wallet so it can prepare everything we need to
2361
                // continue.
2362
                //
2363
                // We'll also pass along the aux funding controller as well,
2364
                // which may be used to help process the finalized PSBT.
2365
                err = resCtx.reservation.ProcessPsbt(auxFundingDesc)
3✔
2366
                if err != nil {
3✔
2367
                        failFlow("error continuing PSBT flow", err)
×
2368
                        return
×
2369
                }
×
2370

2371
                // We are now ready to continue the funding flow.
2372
                f.continueFundingAccept(resCtx, cid)
3✔
2373

2374
        // Handle a server shutdown as well because the reservation won't
2375
        // survive a restart as it's in memory only.
2376
        case <-f.quit:
×
2377
                log.Errorf("Unable to handle funding accept message "+
×
2378
                        "for peer_key=%x, pending_chan_id=%x: funding manager "+
×
2379
                        "shutting down", peerKey.SerializeCompressed(),
×
2380
                        cid.tempChanID)
×
2381
                return
×
2382
        }
2383
}
2384

2385
// continueFundingAccept continues the channel funding flow once our
2386
// contribution is finalized, the channel output is known and the funding
2387
// transaction is signed.
2388
func (f *Manager) continueFundingAccept(resCtx *reservationWithCtx,
2389
        cid *chanIdentifier) {
33✔
2390

33✔
2391
        // Now that we have their contribution, we can extract, then send over
33✔
2392
        // both the funding out point and our signature for their version of
33✔
2393
        // the commitment transaction to the remote peer.
33✔
2394
        outPoint := resCtx.reservation.FundingOutpoint()
33✔
2395
        _, sig := resCtx.reservation.OurSignatures()
33✔
2396

33✔
2397
        // A new channel has almost finished the funding process. In order to
33✔
2398
        // properly synchronize with the writeHandler goroutine, we add a new
33✔
2399
        // channel to the barriers map which will be closed once the channel is
33✔
2400
        // fully open.
33✔
2401
        channelID := lnwire.NewChanIDFromOutPoint(*outPoint)
33✔
2402
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
33✔
2403

33✔
2404
        // The next message that advances the funding flow will reference the
33✔
2405
        // channel via its permanent channel ID, so we'll set up this mapping
33✔
2406
        // so we can retrieve the reservation context once we get the
33✔
2407
        // FundingSigned message.
33✔
2408
        f.resMtx.Lock()
33✔
2409
        f.signedReservations[channelID] = cid.tempChanID
33✔
2410
        f.resMtx.Unlock()
33✔
2411

33✔
2412
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
33✔
2413
                cid.tempChanID[:])
33✔
2414

33✔
2415
        // Before sending FundingCreated sent, we notify Brontide to keep track
33✔
2416
        // of this pending open channel.
33✔
2417
        err := resCtx.peer.AddPendingChannel(channelID, f.quit)
33✔
2418
        if err != nil {
33✔
2419
                pubKey := resCtx.peer.IdentityKey().SerializeCompressed()
×
2420
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2421
                        channelID, pubKey, err)
×
2422
        }
×
2423

2424
        // Once Brontide is aware of this channel, we need to set it in
2425
        // chanIdentifier so this channel will be removed from Brontide if the
2426
        // funding flow fails.
2427
        cid.setChanID(channelID)
33✔
2428

33✔
2429
        // Send the FundingCreated msg.
33✔
2430
        fundingCreated := &lnwire.FundingCreated{
33✔
2431
                PendingChannelID: cid.tempChanID,
33✔
2432
                FundingPoint:     *outPoint,
33✔
2433
        }
33✔
2434

33✔
2435
        // If this is a taproot channel, then we'll need to populate the musig2
33✔
2436
        // partial sig field instead of the regular commit sig field.
33✔
2437
        if resCtx.reservation.IsTaproot() {
38✔
2438
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
5✔
2439
                if !ok {
5✔
2440
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2441
                                sig)
×
2442
                        log.Error(err)
×
2443
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2444

×
2445
                        return
×
2446
                }
×
2447

2448
                fundingCreated.PartialSig = lnwire.MaybePartialSigWithNonce(
5✔
2449
                        partialSig.ToWireSig(),
5✔
2450
                )
5✔
2451
        } else {
31✔
2452
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
31✔
2453
                if err != nil {
31✔
2454
                        log.Errorf("Unable to parse signature: %v", err)
×
2455
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2456
                        return
×
2457
                }
×
2458
        }
2459

2460
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
33✔
2461

33✔
2462
        if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
33✔
2463
                log.Errorf("Unable to send funding complete message: %v", err)
×
2464
                f.failFundingFlow(resCtx.peer, cid, err)
×
2465
                return
×
2466
        }
×
2467
}
2468

2469
// fundeeProcessFundingCreated progresses the funding workflow when the daemon
2470
// is on the responding side of a single funder workflow. Once this message has
2471
// been processed, a signature is sent to the remote peer allowing it to
2472
// broadcast the funding transaction, progressing the workflow into the final
2473
// stage.
2474
//
2475
//nolint:funlen
2476
func (f *Manager) fundeeProcessFundingCreated(peer lnpeer.Peer,
2477
        msg *lnwire.FundingCreated) {
31✔
2478

31✔
2479
        peerKey := peer.IdentityKey()
31✔
2480
        pendingChanID := msg.PendingChannelID
31✔
2481

31✔
2482
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
31✔
2483
        if err != nil {
31✔
2484
                log.Warnf("can't find reservation (peer_id:%v, chan_id:%x)",
×
2485
                        peerKey, pendingChanID[:])
×
2486
                return
×
2487
        }
×
2488

2489
        // The channel initiator has responded with the funding outpoint of the
2490
        // final funding transaction, as well as a signature for our version of
2491
        // the commitment transaction. So at this point, we can validate the
2492
        // initiator's commitment transaction, then send our own if it's valid.
2493
        fundingOut := msg.FundingPoint
31✔
2494
        log.Infof("completing pending_id(%x) with ChannelPoint(%v)",
31✔
2495
                pendingChanID[:], fundingOut)
31✔
2496

31✔
2497
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
31✔
2498
                return
×
2499
        }
×
2500

2501
        // Create the channel identifier without setting the active channel ID.
2502
        cid := newChanIdentifier(pendingChanID)
31✔
2503

31✔
2504
        // For taproot channels, the commit signature is actually the partial
31✔
2505
        // signature. Otherwise, we can convert the ECDSA commit signature into
31✔
2506
        // our internal input.Signature type.
31✔
2507
        var commitSig input.Signature
31✔
2508
        if resCtx.reservation.IsTaproot() {
36✔
2509
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
5✔
2510
                if err != nil {
5✔
2511
                        f.failFundingFlow(peer, cid, err)
×
2512

×
2513
                        return
×
2514
                }
×
2515

2516
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
5✔
2517
                        &partialSig,
5✔
2518
                )
5✔
2519
        } else {
29✔
2520
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2521
                if err != nil {
29✔
2522
                        log.Errorf("unable to parse signature: %v", err)
×
2523
                        f.failFundingFlow(peer, cid, err)
×
2524
                        return
×
2525
                }
×
2526
        }
2527

2528
        // At this point, we'll see if there's an AuxFundingDesc we need to
2529
        // deliver so the funding process can continue properly.
2530
        auxFundingDesc, err := fn.MapOptionZ(
31✔
2531
                f.cfg.AuxFundingController,
31✔
2532
                func(c AuxFundingController) AuxFundingDescResult {
31✔
2533
                        return c.DescFromPendingChanID(
×
2534
                                cid.tempChanID, lnwallet.NewAuxChanState(
×
2535
                                        resCtx.reservation.ChanState(),
×
2536
                                ), resCtx.reservation.CommitmentKeyRings(),
×
2537
                                true,
×
2538
                        )
×
2539
                },
×
2540
        ).Unpack()
2541
        if err != nil {
31✔
2542
                log.Errorf("error continuing PSBT flow: %v", err)
×
2543
                f.failFundingFlow(peer, cid, err)
×
2544
                return
×
2545
        }
×
2546

2547
        // With all the necessary data available, attempt to advance the
2548
        // funding workflow to the next stage. If this succeeds then the
2549
        // funding transaction will broadcast after our next message.
2550
        // CompleteReservationSingle will also mark the channel as 'IsPending'
2551
        // in the database.
2552
        //
2553
        // We'll also directly pass in the AuxFunding controller as well,
2554
        // which may be used by the reservation system to finalize funding our
2555
        // side.
2556
        completeChan, err := resCtx.reservation.CompleteReservationSingle(
31✔
2557
                &fundingOut, commitSig, auxFundingDesc,
31✔
2558
        )
31✔
2559
        if err != nil {
31✔
2560
                log.Errorf("unable to complete single reservation: %v", err)
×
2561
                f.failFundingFlow(peer, cid, err)
×
2562
                return
×
2563
        }
×
2564

2565
        // Get forwarding policy before deleting the reservation context.
2566
        forwardingPolicy := resCtx.forwardingPolicy
31✔
2567

31✔
2568
        // The channel is marked IsPending in the database, and can be removed
31✔
2569
        // from the set of active reservations.
31✔
2570
        f.deleteReservationCtx(peerKey, cid.tempChanID)
31✔
2571

31✔
2572
        // If something goes wrong before the funding transaction is confirmed,
31✔
2573
        // we use this convenience method to delete the pending OpenChannel
31✔
2574
        // from the database.
31✔
2575
        deleteFromDatabase := func() {
31✔
2576
                localBalance := completeChan.LocalCommitment.LocalBalance.ToSatoshis()
×
2577
                closeInfo := &channeldb.ChannelCloseSummary{
×
2578
                        ChanPoint:               completeChan.FundingOutpoint,
×
2579
                        ChainHash:               completeChan.ChainHash,
×
2580
                        RemotePub:               completeChan.IdentityPub,
×
2581
                        CloseType:               channeldb.FundingCanceled,
×
2582
                        Capacity:                completeChan.Capacity,
×
2583
                        SettledBalance:          localBalance,
×
2584
                        RemoteCurrentRevocation: completeChan.RemoteCurrentRevocation,
×
2585
                        RemoteNextRevocation:    completeChan.RemoteNextRevocation,
×
2586
                        LocalChanConfig:         completeChan.LocalChanCfg,
×
2587
                }
×
2588

×
2589
                // Close the channel with us as the initiator because we are
×
2590
                // deciding to exit the funding flow due to an internal error.
×
2591
                if err := completeChan.CloseChannel(
×
2592
                        closeInfo, channeldb.ChanStatusLocalCloseInitiator,
×
2593
                ); err != nil {
×
2594
                        log.Errorf("Failed closing channel %v: %v",
×
2595
                                completeChan.FundingOutpoint, err)
×
2596
                }
×
2597
        }
2598

2599
        // A new channel has almost finished the funding process. In order to
2600
        // properly synchronize with the writeHandler goroutine, we add a new
2601
        // channel to the barriers map which will be closed once the channel is
2602
        // fully open.
2603
        channelID := lnwire.NewChanIDFromOutPoint(fundingOut)
31✔
2604
        log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
31✔
2605

31✔
2606
        fundingSigned := &lnwire.FundingSigned{}
31✔
2607

31✔
2608
        // For taproot channels, we'll need to send over a partial signature
31✔
2609
        // that includes the nonce along side the signature.
31✔
2610
        _, sig := resCtx.reservation.OurSignatures()
31✔
2611
        if resCtx.reservation.IsTaproot() {
36✔
2612
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
5✔
2613
                if !ok {
5✔
2614
                        err := fmt.Errorf("expected musig partial sig, got %T",
×
2615
                                sig)
×
2616
                        log.Error(err)
×
2617
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2618
                        deleteFromDatabase()
×
2619

×
2620
                        return
×
2621
                }
×
2622

2623
                fundingSigned.PartialSig = lnwire.MaybePartialSigWithNonce(
5✔
2624
                        partialSig.ToWireSig(),
5✔
2625
                )
5✔
2626
        } else {
29✔
2627
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
29✔
2628
                if err != nil {
29✔
2629
                        log.Errorf("unable to parse signature: %v", err)
×
2630
                        f.failFundingFlow(peer, cid, err)
×
2631
                        deleteFromDatabase()
×
2632

×
2633
                        return
×
2634
                }
×
2635
        }
2636

2637
        // Before sending FundingSigned, we notify Brontide first to keep track
2638
        // of this pending open channel.
2639
        if err := peer.AddPendingChannel(channelID, f.quit); err != nil {
31✔
2640
                pubKey := peer.IdentityKey().SerializeCompressed()
×
2641
                log.Errorf("Unable to add pending channel %v with peer %x: %v",
×
2642
                        cid.chanID, pubKey, err)
×
2643
        }
×
2644

2645
        // Once Brontide is aware of this channel, we need to set it in
2646
        // chanIdentifier so this channel will be removed from Brontide if the
2647
        // funding flow fails.
2648
        cid.setChanID(channelID)
31✔
2649

31✔
2650
        fundingSigned.ChanID = cid.chanID
31✔
2651

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

31✔
2655
        // With their signature for our version of the commitment transaction
31✔
2656
        // verified, we can now send over our signature to the remote peer.
31✔
2657
        if err := peer.SendMessage(true, fundingSigned); err != nil {
31✔
2658
                log.Errorf("unable to send FundingSigned message: %v", err)
×
2659
                f.failFundingFlow(peer, cid, err)
×
2660
                deleteFromDatabase()
×
2661
                return
×
2662
        }
×
2663

2664
        // With a permanent channel id established we can save the respective
2665
        // forwarding policy in the database. In the channel announcement phase
2666
        // this forwarding policy is retrieved and applied.
2667
        err = f.saveInitialForwardingPolicy(cid.chanID, &forwardingPolicy)
31✔
2668
        if err != nil {
31✔
2669
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2670
        }
×
2671

2672
        // Now that we've sent over our final signature for this channel, we'll
2673
        // send it to the ChainArbitrator so it can watch for any on-chain
2674
        // actions during this final confirmation stage.
2675
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
31✔
2676
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2677
                        "arbitration: %v", fundingOut, err)
×
2678
        }
×
2679

2680
        // Create an entry in the local discovery map so we can ensure that we
2681
        // process the channel confirmation fully before we receive a
2682
        // channel_ready message.
2683
        f.localDiscoverySignals.Store(cid.chanID, make(chan struct{}))
31✔
2684

31✔
2685
        // Inform the ChannelNotifier that the channel has entered
31✔
2686
        // pending open state.
31✔
2687
        f.cfg.NotifyPendingOpenChannelEvent(
31✔
2688
                fundingOut, completeChan, completeChan.IdentityPub,
31✔
2689
        )
31✔
2690

31✔
2691
        // At this point we have sent our last funding message to the
31✔
2692
        // initiating peer before the funding transaction will be broadcast.
31✔
2693
        // With this last message, our job as the responder is now complete.
31✔
2694
        // We'll wait for the funding transaction to reach the specified number
31✔
2695
        // of confirmations, then start normal operations.
31✔
2696
        //
31✔
2697
        // When we get to this point we have sent the signComplete message to
31✔
2698
        // the channel funder, and BOLT#2 specifies that we MUST remember the
31✔
2699
        // channel for reconnection. The channel is already marked
31✔
2700
        // as pending in the database, so in case of a disconnect or restart,
31✔
2701
        // we will continue waiting for the confirmation the next time we start
31✔
2702
        // the funding manager. In case the funding transaction never appears
31✔
2703
        // on the blockchain, we must forget this channel. We therefore
31✔
2704
        // completely forget about this channel if we haven't seen the funding
31✔
2705
        // transaction in 288 blocks (~ 48 hrs), by canceling the reservation
31✔
2706
        // and canceling the wait for the funding confirmation.
31✔
2707
        f.wg.Add(1)
31✔
2708
        go f.advanceFundingState(completeChan, pendingChanID, nil)
31✔
2709
}
2710

2711
// funderProcessFundingSigned processes the final message received in a single
2712
// funder workflow. Once this message is processed, the funding transaction is
2713
// broadcast. Once the funding transaction reaches a sufficient number of
2714
// confirmations, a message is sent to the responding peer along with a compact
2715
// encoding of the location of the channel within the blockchain.
2716
func (f *Manager) funderProcessFundingSigned(peer lnpeer.Peer,
2717
        msg *lnwire.FundingSigned) {
31✔
2718

31✔
2719
        // As the funding signed message will reference the reservation by its
31✔
2720
        // permanent channel ID, we'll need to perform an intermediate look up
31✔
2721
        // before we can obtain the reservation.
31✔
2722
        f.resMtx.Lock()
31✔
2723
        pendingChanID, ok := f.signedReservations[msg.ChanID]
31✔
2724
        delete(f.signedReservations, msg.ChanID)
31✔
2725
        f.resMtx.Unlock()
31✔
2726

31✔
2727
        // Create the channel identifier and set the channel ID.
31✔
2728
        //
31✔
2729
        // NOTE: we may get an empty pending channel ID here if the key cannot
31✔
2730
        // be found, which means when we cancel the reservation context in
31✔
2731
        // `failFundingFlow`, we will get an error. In this case, we will send
31✔
2732
        // an error msg to our peer using the active channel ID.
31✔
2733
        //
31✔
2734
        // TODO(yy): refactor the funding flow to fix this case.
31✔
2735
        cid := newChanIdentifier(pendingChanID)
31✔
2736
        cid.setChanID(msg.ChanID)
31✔
2737

31✔
2738
        // If the pending channel ID is not found, fail the funding flow.
31✔
2739
        if !ok {
31✔
2740
                // NOTE: we directly overwrite the pending channel ID here for
×
2741
                // this rare case since we don't have a valid pending channel
×
2742
                // ID.
×
2743
                cid.tempChanID = msg.ChanID
×
2744

×
2745
                err := fmt.Errorf("unable to find signed reservation for "+
×
2746
                        "chan_id=%x", msg.ChanID)
×
2747
                log.Warnf(err.Error())
×
2748
                f.failFundingFlow(peer, cid, err)
×
2749
                return
×
2750
        }
×
2751

2752
        peerKey := peer.IdentityKey()
31✔
2753
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
31✔
2754
        if err != nil {
31✔
2755
                log.Warnf("Unable to find reservation (peer_id:%v, "+
×
2756
                        "chan_id:%x)", peerKey, pendingChanID[:])
×
2757
                // TODO: add ErrChanNotFound?
×
2758
                f.failFundingFlow(peer, cid, err)
×
2759
                return
×
2760
        }
×
2761

2762
        if resCtx.reservation.State() != lnwallet.SentFundingCreated {
31✔
2763
                err := fmt.Errorf("unable to find reservation for chan_id=%x",
×
2764
                        msg.ChanID)
×
2765
                f.failFundingFlow(peer, cid, err)
×
2766

×
2767
                return
×
2768
        }
×
2769

2770
        // Create an entry in the local discovery map so we can ensure that we
2771
        // process the channel confirmation fully before we receive a
2772
        // channel_ready message.
2773
        fundingPoint := resCtx.reservation.FundingOutpoint()
31✔
2774
        permChanID := lnwire.NewChanIDFromOutPoint(*fundingPoint)
31✔
2775
        f.localDiscoverySignals.Store(permChanID, make(chan struct{}))
31✔
2776

31✔
2777
        // We have to store the forwardingPolicy before the reservation context
31✔
2778
        // is deleted. The policy will then be read and applied in
31✔
2779
        // newChanAnnouncement.
31✔
2780
        err = f.saveInitialForwardingPolicy(
31✔
2781
                permChanID, &resCtx.forwardingPolicy,
31✔
2782
        )
31✔
2783
        if err != nil {
31✔
2784
                log.Errorf("Unable to store the forwarding policy: %v", err)
×
2785
        }
×
2786

2787
        // For taproot channels, the commit signature is actually the partial
2788
        // signature. Otherwise, we can convert the ECDSA commit signature into
2789
        // our internal input.Signature type.
2790
        var commitSig input.Signature
31✔
2791
        if resCtx.reservation.IsTaproot() {
36✔
2792
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
5✔
2793
                if err != nil {
5✔
2794
                        f.failFundingFlow(peer, cid, err)
×
2795

×
2796
                        return
×
2797
                }
×
2798

2799
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
5✔
2800
                        &partialSig,
5✔
2801
                )
5✔
2802
        } else {
29✔
2803
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2804
                if err != nil {
29✔
2805
                        log.Errorf("unable to parse signature: %v", err)
×
2806
                        f.failFundingFlow(peer, cid, err)
×
2807
                        return
×
2808
                }
×
2809
        }
2810

2811
        completeChan, err := resCtx.reservation.CompleteReservation(
31✔
2812
                nil, commitSig,
31✔
2813
        )
31✔
2814
        if err != nil {
31✔
2815
                log.Errorf("Unable to complete reservation sign "+
×
2816
                        "complete: %v", err)
×
2817
                f.failFundingFlow(peer, cid, err)
×
2818
                return
×
2819
        }
×
2820

2821
        // The channel is now marked IsPending in the database, and we can
2822
        // delete it from our set of active reservations.
2823
        f.deleteReservationCtx(peerKey, pendingChanID)
31✔
2824

31✔
2825
        // Broadcast the finalized funding transaction to the network, but only
31✔
2826
        // if we actually have the funding transaction.
31✔
2827
        if completeChan.ChanType.HasFundingTx() {
61✔
2828
                fundingTx := completeChan.FundingTxn
30✔
2829
                var fundingTxBuf bytes.Buffer
30✔
2830
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
30✔
2831
                        log.Errorf("Unable to serialize funding "+
×
2832
                                "transaction %v: %v", fundingTx.TxHash(), err)
×
2833

×
2834
                        // Clear the buffer of any bytes that were written
×
2835
                        // before the serialization error to prevent logging an
×
2836
                        // incomplete transaction.
×
2837
                        fundingTxBuf.Reset()
×
2838
                }
×
2839

2840
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
30✔
2841
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
30✔
2842

30✔
2843
                // Set a nil short channel ID at this stage because we do not
30✔
2844
                // know it until our funding tx confirms.
30✔
2845
                label := labels.MakeLabel(
30✔
2846
                        labels.LabelTypeChannelOpen, nil,
30✔
2847
                )
30✔
2848

30✔
2849
                err = f.cfg.PublishTransaction(fundingTx, label)
30✔
2850
                if err != nil {
30✔
2851
                        log.Errorf("Unable to broadcast funding tx %x for "+
×
2852
                                "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
2853
                                completeChan.FundingOutpoint, err)
×
2854

×
2855
                        // We failed to broadcast the funding transaction, but
×
2856
                        // watch the channel regardless, in case the
×
2857
                        // transaction made it to the network. We will retry
×
2858
                        // broadcast at startup.
×
2859
                        //
×
2860
                        // TODO(halseth): retry more often? Handle with CPFP?
×
2861
                        // Just delete from the DB?
×
2862
                }
×
2863
        }
2864

2865
        // Before we proceed, if we have a funding hook that wants a
2866
        // notification that it's safe to broadcast the funding transaction,
2867
        // then we'll send that now.
2868
        err = fn.MapOptionZ(
31✔
2869
                f.cfg.AuxFundingController,
31✔
2870
                func(controller AuxFundingController) error {
31✔
2871
                        return controller.ChannelFinalized(cid.tempChanID)
×
2872
                },
×
2873
        )
2874
        if err != nil {
31✔
2875
                log.Errorf("Failed to inform aux funding controller about "+
×
2876
                        "ChannelPoint(%v) being finalized: %v", fundingPoint,
×
2877
                        err)
×
2878
        }
×
2879

2880
        // Now that we have a finalized reservation for this funding flow,
2881
        // we'll send the to be active channel to the ChainArbitrator so it can
2882
        // watch for any on-chain actions before the channel has fully
2883
        // confirmed.
2884
        if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
31✔
2885
                log.Errorf("Unable to send new ChannelPoint(%v) for "+
×
2886
                        "arbitration: %v", fundingPoint, err)
×
2887
        }
×
2888

2889
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
31✔
2890
                "waiting for channel open on-chain", pendingChanID[:],
31✔
2891
                fundingPoint)
31✔
2892

31✔
2893
        // Send an update to the upstream client that the negotiation process
31✔
2894
        // is over.
31✔
2895
        upd := &lnrpc.OpenStatusUpdate{
31✔
2896
                Update: &lnrpc.OpenStatusUpdate_ChanPending{
31✔
2897
                        ChanPending: &lnrpc.PendingUpdate{
31✔
2898
                                Txid:        fundingPoint.Hash[:],
31✔
2899
                                OutputIndex: fundingPoint.Index,
31✔
2900
                        },
31✔
2901
                },
31✔
2902
                PendingChanId: pendingChanID[:],
31✔
2903
        }
31✔
2904

31✔
2905
        select {
31✔
2906
        case resCtx.updates <- upd:
31✔
2907
                // Inform the ChannelNotifier that the channel has entered
31✔
2908
                // pending open state.
31✔
2909
                f.cfg.NotifyPendingOpenChannelEvent(
31✔
2910
                        *fundingPoint, completeChan, completeChan.IdentityPub,
31✔
2911
                )
31✔
2912

2913
        case <-f.quit:
×
2914
                return
×
2915
        }
2916

2917
        // At this point we have broadcast the funding transaction and done all
2918
        // necessary processing.
2919
        f.wg.Add(1)
31✔
2920
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
31✔
2921
}
2922

2923
// confirmedChannel wraps a confirmed funding transaction, as well as the short
2924
// channel ID which identifies that channel into a single struct. We'll use
2925
// this to pass around the final state of a channel after it has been
2926
// confirmed.
2927
type confirmedChannel struct {
2928
        // shortChanID expresses where in the block the funding transaction was
2929
        // located.
2930
        shortChanID lnwire.ShortChannelID
2931

2932
        // fundingTx is the funding transaction that created the channel.
2933
        fundingTx *wire.MsgTx
2934
}
2935

2936
// fundingTimeout is called when callers of waitForFundingWithTimeout receive
2937
// an ErrConfirmationTimeout. It is used to clean-up channel state and mark the
2938
// channel as closed. The error is only returned for the responder of the
2939
// channel flow.
2940
func (f *Manager) fundingTimeout(c *channeldb.OpenChannel,
2941
        pendingID PendingChanID) error {
5✔
2942

5✔
2943
        // We'll get a timeout if the number of blocks mined since the channel
5✔
2944
        // was initiated reaches MaxWaitNumBlocksFundingConf and we are not the
5✔
2945
        // channel initiator.
5✔
2946
        localBalance := c.LocalCommitment.LocalBalance.ToSatoshis()
5✔
2947
        closeInfo := &channeldb.ChannelCloseSummary{
5✔
2948
                ChainHash:               c.ChainHash,
5✔
2949
                ChanPoint:               c.FundingOutpoint,
5✔
2950
                RemotePub:               c.IdentityPub,
5✔
2951
                Capacity:                c.Capacity,
5✔
2952
                SettledBalance:          localBalance,
5✔
2953
                CloseType:               channeldb.FundingCanceled,
5✔
2954
                RemoteCurrentRevocation: c.RemoteCurrentRevocation,
5✔
2955
                RemoteNextRevocation:    c.RemoteNextRevocation,
5✔
2956
                LocalChanConfig:         c.LocalChanCfg,
5✔
2957
        }
5✔
2958

5✔
2959
        // Close the channel with us as the initiator because we are timing the
5✔
2960
        // channel out.
5✔
2961
        if err := c.CloseChannel(
5✔
2962
                closeInfo, channeldb.ChanStatusLocalCloseInitiator,
5✔
2963
        ); err != nil {
5✔
2964
                return fmt.Errorf("failed closing channel %v: %w",
×
2965
                        c.FundingOutpoint, err)
×
2966
        }
×
2967

2968
        // Notify other subsystems about the funding timeout.
2969
        f.cfg.NotifyFundingTimeout(c.FundingOutpoint, c.IdentityPub)
5✔
2970

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

5✔
2974
        // When the peer comes online, we'll notify it that we are now
5✔
2975
        // considering the channel flow canceled.
5✔
2976
        f.wg.Add(1)
5✔
2977
        go func() {
10✔
2978
                defer f.wg.Done()
5✔
2979

5✔
2980
                peer, err := f.waitForPeerOnline(c.IdentityPub)
5✔
2981
                switch err {
5✔
2982
                // We're already shutting down, so we can just return.
2983
                case ErrFundingManagerShuttingDown:
×
2984
                        return
×
2985

2986
                // nil error means we continue on.
2987
                case nil:
5✔
2988

2989
                // For unexpected errors, we print the error and still try to
2990
                // fail the funding flow.
2991
                default:
×
2992
                        log.Errorf("Unexpected error while waiting for peer "+
×
2993
                                "to come online: %v", err)
×
2994
                }
2995

2996
                // Create channel identifier and set the channel ID.
2997
                cid := newChanIdentifier(pendingID)
5✔
2998
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
5✔
2999

5✔
3000
                // TODO(halseth): should this send be made
5✔
3001
                // reliable?
5✔
3002

5✔
3003
                // The reservation won't exist at this point, but we'll send an
5✔
3004
                // Error message over anyways with ChanID set to pendingID.
5✔
3005
                f.failFundingFlow(peer, cid, timeoutErr)
5✔
3006
        }()
3007

3008
        return timeoutErr
5✔
3009
}
3010

3011
// waitForFundingWithTimeout is a wrapper around waitForFundingConfirmation and
3012
// waitForTimeout that will return ErrConfirmationTimeout if we are not the
3013
// channel initiator and the MaxWaitNumBlocksFundingConf has passed from the
3014
// funding broadcast height. In case of confirmation, the short channel ID of
3015
// the channel and the funding transaction will be returned.
3016
func (f *Manager) waitForFundingWithTimeout(
3017
        ch *channeldb.OpenChannel) (*confirmedChannel, error) {
62✔
3018

62✔
3019
        confChan := make(chan *confirmedChannel)
62✔
3020
        timeoutChan := make(chan error, 1)
62✔
3021
        cancelChan := make(chan struct{})
62✔
3022

62✔
3023
        f.wg.Add(1)
62✔
3024
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
62✔
3025

62✔
3026
        // If we are not the initiator, we have no money at stake and will
62✔
3027
        // timeout waiting for the funding transaction to confirm after a
62✔
3028
        // while.
62✔
3029
        if !ch.IsInitiator && !ch.IsZeroConf() {
91✔
3030
                f.wg.Add(1)
29✔
3031
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
29✔
3032
        }
29✔
3033
        defer close(cancelChan)
62✔
3034

62✔
3035
        select {
62✔
3036
        case err := <-timeoutChan:
5✔
3037
                if err != nil {
5✔
3038
                        return nil, err
×
3039
                }
×
3040
                return nil, ErrConfirmationTimeout
5✔
3041

3042
        case <-f.quit:
26✔
3043
                // The fundingManager is shutting down, and will resume wait on
26✔
3044
                // startup.
26✔
3045
                return nil, ErrFundingManagerShuttingDown
26✔
3046

3047
        case confirmedChannel, ok := <-confChan:
37✔
3048
                if !ok {
37✔
3049
                        return nil, fmt.Errorf("waiting for funding" +
×
3050
                                "confirmation failed")
×
3051
                }
×
3052
                return confirmedChannel, nil
37✔
3053
        }
3054
}
3055

3056
// makeFundingScript re-creates the funding script for the funding transaction
3057
// of the target channel.
3058
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
82✔
3059
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
82✔
3060
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
82✔
3061

82✔
3062
        if channel.ChanType.IsTaproot() {
90✔
3063
                pkScript, _, err := input.GenTaprootFundingScript(
8✔
3064
                        localKey, remoteKey, int64(channel.Capacity),
8✔
3065
                        channel.TapscriptRoot,
8✔
3066
                )
8✔
3067
                if err != nil {
8✔
3068
                        return nil, err
×
3069
                }
×
3070

3071
                return pkScript, nil
8✔
3072
        }
3073

3074
        multiSigScript, err := input.GenMultiSigScript(
77✔
3075
                localKey.SerializeCompressed(),
77✔
3076
                remoteKey.SerializeCompressed(),
77✔
3077
        )
77✔
3078
        if err != nil {
77✔
3079
                return nil, err
×
3080
        }
×
3081

3082
        return input.WitnessScriptHash(multiSigScript)
77✔
3083
}
3084

3085
// waitForFundingConfirmation handles the final stages of the channel funding
3086
// process once the funding transaction has been broadcast. The primary
3087
// function of waitForFundingConfirmation is to wait for blockchain
3088
// confirmation, and then to notify the other systems that must be notified
3089
// when a channel has become active for lightning transactions. It also updates
3090
// the channel’s opening transaction block height in the database.
3091
// The wait can be canceled by closing the cancelChan. In case of success,
3092
// a *lnwire.ShortChannelID will be passed to confChan.
3093
//
3094
// NOTE: This MUST be run as a goroutine.
3095
func (f *Manager) waitForFundingConfirmation(
3096
        completeChan *channeldb.OpenChannel, cancelChan <-chan struct{},
3097
        confChan chan<- *confirmedChannel) {
62✔
3098

62✔
3099
        defer f.wg.Done()
62✔
3100
        defer close(confChan)
62✔
3101

62✔
3102
        // Register with the ChainNotifier for a notification once the funding
62✔
3103
        // transaction reaches `numConfs` confirmations.
62✔
3104
        txid := completeChan.FundingOutpoint.Hash
62✔
3105
        fundingScript, err := makeFundingScript(completeChan)
62✔
3106
        if err != nil {
62✔
3107
                log.Errorf("unable to create funding script for "+
×
3108
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3109
                        err)
×
3110
                return
×
3111
        }
×
3112
        numConfs := uint32(completeChan.NumConfsRequired)
62✔
3113

62✔
3114
        // If the underlying channel is a zero-conf channel, we'll set numConfs
62✔
3115
        // to 6, since it will be zero here.
62✔
3116
        if completeChan.IsZeroConf() {
71✔
3117
                numConfs = 6
9✔
3118
        }
9✔
3119

3120
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
62✔
3121
                &txid, fundingScript, numConfs,
62✔
3122
                completeChan.BroadcastHeight(),
62✔
3123
        )
62✔
3124
        if err != nil {
62✔
3125
                log.Errorf("Unable to register for confirmation of "+
×
3126
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3127
                        err)
×
3128
                return
×
3129
        }
×
3130

3131
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
62✔
3132
                txid, numConfs)
62✔
3133

62✔
3134
        // Wait until the specified number of confirmations has been reached,
62✔
3135
        // we get a cancel signal, or the wallet signals a shutdown.
62✔
3136
        for {
151✔
3137
                select {
89✔
3138
                case updDetails, ok := <-confNtfn.Updates:
28✔
3139
                        if !ok {
28✔
3140
                                log.Warnf("ChainNotifier shutting down, "+
×
3141
                                        "cannot process updates for "+
×
3142
                                        "ChannelPoint(%v)",
×
3143
                                        completeChan.FundingOutpoint)
×
3144

×
3145
                                return
×
3146
                        }
×
3147

3148
                        log.Debugf("funding tx %s received confirmation in "+
28✔
3149
                                "block %d, %d confirmations left", txid,
28✔
3150
                                updDetails.BlockHeight, updDetails.NumConfsLeft)
28✔
3151

28✔
3152
                        // Only update the ConfirmationHeight the first time a
28✔
3153
                        // confirmation is received, since on subsequent
28✔
3154
                        // confirmations the block height will remain the same.
28✔
3155
                        if completeChan.ConfirmationHeight == 0 {
56✔
3156
                                err := completeChan.MarkConfirmationHeight(
28✔
3157
                                        updDetails.BlockHeight,
28✔
3158
                                )
28✔
3159
                                if err != nil {
28✔
3160
                                        log.Errorf("failed to update "+
×
3161
                                                "confirmed state for "+
×
3162
                                                "ChannelPoint(%v): %v",
×
3163
                                                completeChan.FundingOutpoint,
×
3164
                                                err)
×
3165

×
3166
                                        return
×
3167
                                }
×
3168
                        }
3169

3170
                case _, ok := <-confNtfn.NegativeConf:
4✔
3171
                        if !ok {
4✔
3172
                                log.Warnf("ChainNotifier shutting down, "+
×
3173
                                        "cannot track negative confirmations "+
×
3174
                                        "for ChannelPoint(%v)",
×
3175
                                        completeChan.FundingOutpoint)
×
3176

×
3177
                                return
×
3178
                        }
×
3179

3180
                        log.Warnf("funding tx %s was reorged out; channel "+
4✔
3181
                                "point: %s", txid, completeChan.FundingOutpoint)
4✔
3182

4✔
3183
                        // Reset the confirmation height to 0 because the
4✔
3184
                        // funding transaction was reorged out.
4✔
3185
                        err := completeChan.MarkConfirmationHeight(uint32(0))
4✔
3186
                        if err != nil {
4✔
3187
                                log.Errorf("failed to update state for "+
×
3188
                                        "ChannelPoint(%v): %v",
×
3189
                                        completeChan.FundingOutpoint, err)
×
3190

×
3191
                                return
×
3192
                        }
×
3193

3194
                case confDetails, ok := <-confNtfn.Confirmed:
37✔
3195
                        if !ok {
37✔
3196
                                log.Warnf("ChainNotifier shutting down, "+
×
3197
                                        "cannot complete funding flow for "+
×
3198
                                        "ChannelPoint(%v)",
×
3199
                                        completeChan.FundingOutpoint)
×
3200

×
3201
                                return
×
3202
                        }
×
3203

3204
                        log.Debugf("funding tx %s for ChannelPoint(%v) "+
37✔
3205
                                "confirmed in block %d", txid,
37✔
3206
                                completeChan.FundingOutpoint,
37✔
3207
                                confDetails.BlockHeight)
37✔
3208

37✔
3209
                        // In the case of requiring a single confirmation, it
37✔
3210
                        // can happen that the `Confirmed` channel is read
37✔
3211
                        // from first, in which case the confirmation height
37✔
3212
                        // will not be set. If this happens, we take the
37✔
3213
                        // confirmation height from the `Confirmed` channel.
37✔
3214
                        if completeChan.ConfirmationHeight == 0 {
50✔
3215
                                err := completeChan.MarkConfirmationHeight(
13✔
3216
                                        confDetails.BlockHeight,
13✔
3217
                                )
13✔
3218
                                if err != nil {
13✔
3219
                                        log.Errorf("failed to update "+
×
3220
                                                "confirmed state for "+
×
3221
                                                "ChannelPoint(%v): %v",
×
3222
                                                completeChan.FundingOutpoint,
×
3223
                                                err)
×
3224

×
3225
                                        return
×
3226
                                }
×
3227
                        }
3228

3229
                        err := f.handleConfirmation(
37✔
3230
                                confDetails, completeChan, confChan,
37✔
3231
                        )
37✔
3232
                        if err != nil {
37✔
3233
                                log.Errorf("Error handling confirmation for "+
×
3234
                                        "ChannelPoint(%v), txid=%v: %v",
×
3235
                                        completeChan.FundingOutpoint, txid, err)
×
3236
                        }
×
3237

3238
                        return
37✔
3239

3240
                case <-cancelChan:
5✔
3241
                        log.Warnf("canceled waiting for funding confirmation, "+
5✔
3242
                                "stopping funding flow for ChannelPoint(%v)",
5✔
3243
                                completeChan.FundingOutpoint)
5✔
3244

5✔
3245
                        return
5✔
3246

3247
                case <-f.quit:
26✔
3248
                        log.Warnf("fundingManager shutting down, stopping "+
26✔
3249
                                "funding flow for ChannelPoint(%v)",
26✔
3250
                                completeChan.FundingOutpoint)
26✔
3251

26✔
3252
                        return
26✔
3253
                }
3254
        }
3255
}
3256

3257
// handleConfirmation is a helper function that constructs a ShortChannelID
3258
// based on the confirmation details and sends this information, along with the
3259
// funding transaction, to the provided confirmation channel.
3260
func (f *Manager) handleConfirmation(confDetails *chainntnfs.TxConfirmation,
3261
        completeChan *channeldb.OpenChannel,
3262
        confChan chan<- *confirmedChannel) error {
37✔
3263

37✔
3264
        fundingPoint := completeChan.FundingOutpoint
37✔
3265
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
37✔
3266
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
37✔
3267

37✔
3268
        // With the block height and the transaction index known, we can
37✔
3269
        // construct the compact chanID which is used on the network to unique
37✔
3270
        // identify channels.
37✔
3271
        shortChanID := lnwire.ShortChannelID{
37✔
3272
                BlockHeight: confDetails.BlockHeight,
37✔
3273
                TxIndex:     confDetails.TxIndex,
37✔
3274
                TxPosition:  uint16(fundingPoint.Index),
37✔
3275
        }
37✔
3276

37✔
3277
        select {
37✔
3278
        case confChan <- &confirmedChannel{
3279
                shortChanID: shortChanID,
3280
                fundingTx:   confDetails.Tx,
3281
        }:
37✔
3282
        case <-f.quit:
×
3283
                return fmt.Errorf("manager shutting down")
×
3284
        }
3285

3286
        return nil
37✔
3287
}
3288

3289
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3290
// has passed from the broadcast height of the given channel. In case of error,
3291
// the error is sent on timeoutChan. The wait can be canceled by closing the
3292
// cancelChan.
3293
//
3294
// NOTE: timeoutChan MUST be buffered.
3295
// NOTE: This MUST be run as a goroutine.
3296
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3297
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
29✔
3298

29✔
3299
        defer f.wg.Done()
29✔
3300

29✔
3301
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
29✔
3302
        if err != nil {
29✔
3303
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3304
                        "notification: %v", err)
×
3305
                return
×
3306
        }
×
3307

3308
        defer epochClient.Cancel()
29✔
3309

29✔
3310
        // The value of waitBlocksForFundingConf is adjusted in a development
29✔
3311
        // environment to enhance test capabilities. Otherwise, it is set to
29✔
3312
        // DefaultMaxWaitNumBlocksFundingConf.
29✔
3313
        waitBlocksForFundingConf := uint32(
29✔
3314
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
29✔
3315
        )
29✔
3316

29✔
3317
        if lncfg.IsDevBuild() {
32✔
3318
                waitBlocksForFundingConf =
3✔
3319
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3320
        }
3✔
3321

3322
        // On block maxHeight we will cancel the funding confirmation wait.
3323
        broadcastHeight := completeChan.BroadcastHeight()
29✔
3324
        maxHeight := broadcastHeight + waitBlocksForFundingConf
29✔
3325
        for {
60✔
3326
                select {
31✔
3327
                case epoch, ok := <-epochClient.Epochs:
7✔
3328
                        if !ok {
7✔
3329
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3330
                                        "shutting down")
×
3331
                                return
×
3332
                        }
×
3333

3334
                        // Close the timeout channel and exit if the block is
3335
                        // above the max height.
3336
                        if uint32(epoch.Height) >= maxHeight {
12✔
3337
                                log.Warnf("Waited for %v blocks without "+
5✔
3338
                                        "seeing funding transaction confirmed,"+
5✔
3339
                                        " cancelling.",
5✔
3340
                                        waitBlocksForFundingConf)
5✔
3341

5✔
3342
                                // Notify the caller of the timeout.
5✔
3343
                                close(timeoutChan)
5✔
3344
                                return
5✔
3345
                        }
5✔
3346

3347
                        // TODO: If we are the channel initiator implement
3348
                        // a method for recovering the funds from the funding
3349
                        // transaction
3350

3351
                case <-cancelChan:
18✔
3352
                        return
18✔
3353

3354
                case <-f.quit:
12✔
3355
                        // The fundingManager is shutting down, will resume
12✔
3356
                        // waiting for the funding transaction on startup.
12✔
3357
                        return
12✔
3358
                }
3359
        }
3360
}
3361

3362
// makeLabelForTx updates the label for the confirmed funding transaction. If
3363
// we opened the channel, and lnd's wallet published our funding tx (which is
3364
// not the case for some channels) then we update our transaction label with
3365
// our short channel ID, which is known now that our funding transaction has
3366
// confirmed. We do not label transactions we did not publish, because our
3367
// wallet has no knowledge of them.
3368
func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
37✔
3369
        if c.IsInitiator && c.ChanType.HasFundingTx() {
56✔
3370
                shortChanID := c.ShortChanID()
19✔
3371

19✔
3372
                // For zero-conf channels, we'll use the actually-confirmed
19✔
3373
                // short channel id.
19✔
3374
                if c.IsZeroConf() {
24✔
3375
                        shortChanID = c.ZeroConfRealScid()
5✔
3376
                }
5✔
3377

3378
                label := labels.MakeLabel(
19✔
3379
                        labels.LabelTypeChannelOpen, &shortChanID,
19✔
3380
                )
19✔
3381

19✔
3382
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
19✔
3383
                if err != nil {
19✔
3384
                        log.Errorf("unable to update label: %v", err)
×
3385
                }
×
3386
        }
3387
}
3388

3389
// handleFundingConfirmation marks a channel as open in the database, and set
3390
// the channelOpeningState markedOpen. In addition it will report the now
3391
// decided short channel ID to the switch, and close the local discovery signal
3392
// for this channel.
3393
func (f *Manager) handleFundingConfirmation(
3394
        completeChan *channeldb.OpenChannel,
3395
        confChannel *confirmedChannel) error {
33✔
3396

33✔
3397
        fundingPoint := completeChan.FundingOutpoint
33✔
3398
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
33✔
3399

33✔
3400
        // TODO(roasbeef): ideally persistent state update for chan above
33✔
3401
        // should be abstracted
33✔
3402

33✔
3403
        // Now that that the channel has been fully confirmed, we'll request
33✔
3404
        // that the wallet fully verify this channel to ensure that it can be
33✔
3405
        // used.
33✔
3406
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
33✔
3407
        if err != nil {
33✔
3408
                // TODO(roasbeef): delete chan state?
×
3409
                return fmt.Errorf("unable to validate channel: %w", err)
×
3410
        }
×
3411

3412
        // Now that the channel has been validated, we'll persist an alias for
3413
        // this channel if the option-scid-alias feature-bit was negotiated.
3414
        if completeChan.NegotiatedAliasFeature() {
38✔
3415
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
3416
                if err != nil {
5✔
3417
                        return fmt.Errorf("unable to request alias: %w", err)
×
3418
                }
×
3419

3420
                err = f.cfg.AliasManager.AddLocalAlias(
5✔
3421
                        aliasScid, confChannel.shortChanID, true, false,
5✔
3422
                )
5✔
3423
                if err != nil {
5✔
3424
                        return fmt.Errorf("unable to request alias: %w", err)
×
3425
                }
×
3426
        }
3427

3428
        // The funding transaction now being confirmed, we add this channel to
3429
        // the fundingManager's internal persistent state machine that we use
3430
        // to track the remaining process of the channel opening. This is
3431
        // useful to resume the opening process in case of restarts. We set the
3432
        // opening state before we mark the channel opened in the database,
3433
        // such that we can receover from one of the db writes failing.
3434
        err = f.saveChannelOpeningState(
33✔
3435
                &fundingPoint, markedOpen, &confChannel.shortChanID,
33✔
3436
        )
33✔
3437
        if err != nil {
33✔
3438
                return fmt.Errorf("error setting channel state to "+
×
3439
                        "markedOpen: %v", err)
×
3440
        }
×
3441

3442
        // Now that the channel has been fully confirmed and we successfully
3443
        // saved the opening state, we'll mark it as open within the database.
3444
        err = completeChan.MarkAsOpen(confChannel.shortChanID)
33✔
3445
        if err != nil {
33✔
3446
                return fmt.Errorf("error setting channel pending flag to "+
×
3447
                        "false:        %v", err)
×
3448
        }
×
3449

3450
        // Update the confirmed funding transaction label.
3451
        f.makeLabelForTx(completeChan)
33✔
3452

33✔
3453
        // Inform the ChannelNotifier that the channel has transitioned from
33✔
3454
        // pending open to open.
33✔
3455
        f.cfg.NotifyOpenChannelEvent(
33✔
3456
                completeChan.FundingOutpoint, completeChan.IdentityPub,
33✔
3457
        )
33✔
3458

33✔
3459
        // Close the discoverySignal channel, indicating to a separate
33✔
3460
        // goroutine that the channel now is marked as open in the database
33✔
3461
        // and that it is acceptable to process channel_ready messages
33✔
3462
        // from the peer.
33✔
3463
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
66✔
3464
                close(discoverySignal)
33✔
3465
        }
33✔
3466

3467
        return nil
33✔
3468
}
3469

3470
// sendChannelReady creates and sends the channelReady message.
3471
// This should be called after the funding transaction has been confirmed,
3472
// and the channelState is 'markedOpen'.
3473
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3474
        channel *lnwallet.LightningChannel) error {
38✔
3475

38✔
3476
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
38✔
3477

38✔
3478
        var peerKey [33]byte
38✔
3479
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
38✔
3480

38✔
3481
        // Next, we'll send over the channel_ready message which marks that we
38✔
3482
        // consider the channel open by presenting the remote party with our
38✔
3483
        // next revocation key. Without the revocation key, the remote party
38✔
3484
        // will be unable to propose state transitions.
38✔
3485
        nextRevocation, err := channel.NextRevocationKey()
38✔
3486
        if err != nil {
38✔
3487
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3488
        }
×
3489
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
38✔
3490

38✔
3491
        // If this is a taproot channel, then we also need to send along our
38✔
3492
        // set of musig2 nonces as well.
38✔
3493
        if completeChan.ChanType.IsTaproot() {
45✔
3494
                log.Infof("ChanID(%v): generating musig2 nonces...",
7✔
3495
                        chanID)
7✔
3496

7✔
3497
                f.nonceMtx.Lock()
7✔
3498
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
3499
                if !ok {
14✔
3500
                        // If we don't have any nonces generated yet for this
7✔
3501
                        // first state, then we'll generate them now and stow
7✔
3502
                        // them away.  When we receive the funding locked
7✔
3503
                        // message, we'll then pass along this same set of
7✔
3504
                        // nonces.
7✔
3505
                        newNonce, err := channel.GenMusigNonces()
7✔
3506
                        if err != nil {
7✔
3507
                                f.nonceMtx.Unlock()
×
3508
                                return err
×
3509
                        }
×
3510

3511
                        // Now that we've generated the nonce for this channel,
3512
                        // we'll store it in the set of pending nonces.
3513
                        localNonce = newNonce
7✔
3514
                        f.pendingMusigNonces[chanID] = localNonce
7✔
3515
                }
3516
                f.nonceMtx.Unlock()
7✔
3517

7✔
3518
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
7✔
3519
                        localNonce.PubNonce,
7✔
3520
                )
7✔
3521
        }
3522

3523
        // If the channel negotiated the option-scid-alias feature bit, we'll
3524
        // send a TLV segment that includes an alias the peer can use in their
3525
        // invoice hop hints. We'll send the first alias we find for the
3526
        // channel since it does not matter which alias we send. We'll error
3527
        // out in the odd case that no aliases are found.
3528
        if completeChan.NegotiatedAliasFeature() {
47✔
3529
                aliases := f.cfg.AliasManager.GetAliases(
9✔
3530
                        completeChan.ShortChanID(),
9✔
3531
                )
9✔
3532
                if len(aliases) == 0 {
9✔
3533
                        return fmt.Errorf("no aliases found")
×
3534
                }
×
3535

3536
                // We can use a pointer to aliases since GetAliases returns a
3537
                // copy of the alias slice.
3538
                channelReadyMsg.AliasScid = &aliases[0]
9✔
3539
        }
3540

3541
        // If the peer has disconnected before we reach this point, we will need
3542
        // to wait for him to come back online before sending the channelReady
3543
        // message. This is special for channelReady, since failing to send any
3544
        // of the previous messages in the funding flow just cancels the flow.
3545
        // But now the funding transaction is confirmed, the channel is open
3546
        // and we have to make sure the peer gets the channelReady message when
3547
        // it comes back online. This is also crucial during restart of lnd,
3548
        // where we might try to resend the channelReady message before the
3549
        // server has had the time to connect to the peer. We keep trying to
3550
        // send channelReady until we succeed, or the fundingManager is shut
3551
        // down.
3552
        for {
76✔
3553
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
38✔
3554
                if err != nil {
39✔
3555
                        return err
1✔
3556
                }
1✔
3557

3558
                localAlias := peer.LocalFeatures().HasFeature(
37✔
3559
                        lnwire.ScidAliasOptional,
37✔
3560
                )
37✔
3561
                remoteAlias := peer.RemoteFeatures().HasFeature(
37✔
3562
                        lnwire.ScidAliasOptional,
37✔
3563
                )
37✔
3564

37✔
3565
                // We could also refresh the channel state instead of checking
37✔
3566
                // whether the feature was negotiated, but this saves us a
37✔
3567
                // database read.
37✔
3568
                if channelReadyMsg.AliasScid == nil && localAlias &&
37✔
3569
                        remoteAlias {
37✔
3570

×
3571
                        // If an alias was not assigned above and the scid
×
3572
                        // alias feature was negotiated, check if we already
×
3573
                        // have an alias stored in case handleChannelReady was
×
3574
                        // called before this. If an alias exists, use that in
×
3575
                        // channel_ready. Otherwise, request and store an
×
3576
                        // alias and use that.
×
3577
                        aliases := f.cfg.AliasManager.GetAliases(
×
3578
                                completeChan.ShortChannelID,
×
3579
                        )
×
3580
                        if len(aliases) == 0 {
×
3581
                                // No aliases were found.
×
3582
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3583
                                if err != nil {
×
3584
                                        return err
×
3585
                                }
×
3586

3587
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3588
                                        alias, completeChan.ShortChannelID,
×
3589
                                        false, false,
×
3590
                                )
×
3591
                                if err != nil {
×
3592
                                        return err
×
3593
                                }
×
3594

3595
                                channelReadyMsg.AliasScid = &alias
×
3596
                        } else {
×
3597
                                channelReadyMsg.AliasScid = &aliases[0]
×
3598
                        }
×
3599
                }
3600

3601
                log.Infof("Peer(%x) is online, sending ChannelReady "+
37✔
3602
                        "for ChannelID(%v)", peerKey, chanID)
37✔
3603

37✔
3604
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
74✔
3605
                        // Sending succeeded, we can break out and continue the
37✔
3606
                        // funding flow.
37✔
3607
                        break
37✔
3608
                }
3609

3610
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3611
                        "Will retry when online", peerKey, err)
×
3612
        }
3613

3614
        return nil
37✔
3615
}
3616

3617
// receivedChannelReady checks whether or not we've received a ChannelReady
3618
// from the remote peer. If we have, RemoteNextRevocation will be set.
3619
func (f *Manager) receivedChannelReady(node *btcec.PublicKey,
3620
        chanID lnwire.ChannelID) (bool, error) {
63✔
3621

63✔
3622
        // If the funding manager has exited, return an error to stop looping.
63✔
3623
        // Note that the peer may appear as online while the funding manager
63✔
3624
        // has stopped due to the shutdown order in the server.
63✔
3625
        select {
63✔
UNCOV
3626
        case <-f.quit:
×
UNCOV
3627
                return false, ErrFundingManagerShuttingDown
×
3628
        default:
63✔
3629
        }
3630

3631
        // Avoid a tight loop if peer is offline.
3632
        if _, err := f.waitForPeerOnline(node); err != nil {
63✔
UNCOV
3633
                log.Errorf("Wait for peer online failed: %v", err)
×
UNCOV
3634
                return false, err
×
UNCOV
3635
        }
×
3636

3637
        // If we cannot find the channel, then we haven't processed the
3638
        // remote's channelReady message.
3639
        channel, err := f.cfg.FindChannel(node, chanID)
63✔
3640
        if err != nil {
63✔
3641
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3642
                        "ChannelReady was received", chanID)
×
3643
                return false, err
×
3644
        }
×
3645

3646
        // If we haven't insert the next revocation point, we haven't finished
3647
        // processing the channel ready message.
3648
        if channel.RemoteNextRevocation == nil {
101✔
3649
                return false, nil
38✔
3650
        }
38✔
3651

3652
        // Finally, the barrier signal is removed once we finish
3653
        // `handleChannelReady`. If we can still find the signal, we haven't
3654
        // finished processing it yet.
3655
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
28✔
3656

28✔
3657
        return !loaded, nil
28✔
3658
}
3659

3660
// extractAnnounceParams extracts the various channel announcement and update
3661
// parameters that will be needed to construct a ChannelAnnouncement and a
3662
// ChannelUpdate.
3663
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3664
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
29✔
3665

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

29✔
3672
        // We don't necessarily want to go as low as the remote party allows.
29✔
3673
        // Check it against our default forwarding policy.
29✔
3674
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
32✔
3675
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3676
        }
3✔
3677

3678
        // We'll obtain the max HTLC value we can forward in our direction, as
3679
        // we'll use this value within our ChannelUpdate. This value must be <=
3680
        // channel capacity and <= the maximum in-flight msats set by the peer.
3681
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
29✔
3682
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
29✔
3683
        if fwdMaxHTLC > capacityMSat {
29✔
3684
                fwdMaxHTLC = capacityMSat
×
3685
        }
×
3686

3687
        return fwdMinHTLC, fwdMaxHTLC
29✔
3688
}
3689

3690
// addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
3691
// gossiper so that the channel is added to the graph builder's internal graph.
3692
// These announcement messages are NOT broadcasted to the greater network,
3693
// only to the channel counter party. The proofs required to announce the
3694
// channel to the greater network will be created and sent in annAfterSixConfs.
3695
// The peerAlias is used for zero-conf channels to give the counter-party a
3696
// ChannelUpdate they understand. ourPolicy may be set for various
3697
// option-scid-alias channels to re-use the same policy.
3698
func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
3699
        shortChanID *lnwire.ShortChannelID,
3700
        peerAlias *lnwire.ShortChannelID,
3701
        ourPolicy *models.ChannelEdgePolicy) error {
29✔
3702

29✔
3703
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
29✔
3704

29✔
3705
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
29✔
3706

29✔
3707
        ann, err := f.newChanAnnouncement(
29✔
3708
                f.cfg.IDKey, completeChan.IdentityPub,
29✔
3709
                &completeChan.LocalChanCfg.MultiSigKey,
29✔
3710
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
29✔
3711
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
29✔
3712
                completeChan.ChanType,
29✔
3713
        )
29✔
3714
        if err != nil {
29✔
3715
                return fmt.Errorf("error generating channel "+
×
3716
                        "announcement: %v", err)
×
3717
        }
×
3718

3719
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3720
        // to the Router's topology.
3721
        errChan := f.cfg.SendAnnouncement(
29✔
3722
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
29✔
3723
                discovery.ChannelPoint(completeChan.FundingOutpoint),
29✔
3724
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
29✔
3725
        )
29✔
3726
        select {
29✔
3727
        case err := <-errChan:
29✔
3728
                if err != nil {
29✔
3729
                        if graph.IsError(err, graph.ErrOutdated,
×
3730
                                graph.ErrIgnored) {
×
3731

×
3732
                                log.Debugf("Graph rejected "+
×
3733
                                        "ChannelAnnouncement: %v", err)
×
3734
                        } else {
×
3735
                                return fmt.Errorf("error sending channel "+
×
3736
                                        "announcement: %v", err)
×
3737
                        }
×
3738
                }
3739
        case <-f.quit:
×
3740
                return ErrFundingManagerShuttingDown
×
3741
        }
3742

3743
        errChan = f.cfg.SendAnnouncement(
29✔
3744
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
29✔
3745
        )
29✔
3746
        select {
29✔
3747
        case err := <-errChan:
29✔
3748
                if err != nil {
29✔
3749
                        if graph.IsError(err, graph.ErrOutdated,
×
3750
                                graph.ErrIgnored) {
×
3751

×
3752
                                log.Debugf("Graph rejected "+
×
3753
                                        "ChannelUpdate: %v", err)
×
3754
                        } else {
×
3755
                                return fmt.Errorf("error sending channel "+
×
3756
                                        "update: %v", err)
×
3757
                        }
×
3758
                }
3759
        case <-f.quit:
×
3760
                return ErrFundingManagerShuttingDown
×
3761
        }
3762

3763
        return nil
29✔
3764
}
3765

3766
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3767
// the network after 6 confs. Should be called after the channelReady message
3768
// is sent and the channel is added to the graph (channelState is
3769
// 'addedToGraph') and the channel is ready to be used. This is the last
3770
// step in the channel opening process, and the opening state will be deleted
3771
// from the database if successful.
3772
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3773
        shortChanID *lnwire.ShortChannelID) error {
29✔
3774

29✔
3775
        // If this channel is not meant to be announced to the greater network,
29✔
3776
        // we'll only send our NodeAnnouncement1 to our counterparty to ensure
29✔
3777
        // we don't leak any of our information.
29✔
3778
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
29✔
3779
        if !announceChan {
40✔
3780
                log.Debugf("Will not announce private channel %v.",
11✔
3781
                        shortChanID.ToUint64())
11✔
3782

11✔
3783
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
11✔
3784
                if err != nil {
11✔
3785
                        return err
×
3786
                }
×
3787

3788
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
11✔
3789
                if err != nil {
11✔
3790
                        return fmt.Errorf("unable to retrieve current node "+
×
3791
                                "announcement: %v", err)
×
3792
                }
×
3793

3794
                chanID := lnwire.NewChanIDFromOutPoint(
11✔
3795
                        completeChan.FundingOutpoint,
11✔
3796
                )
11✔
3797
                pubKey := peer.PubKey()
11✔
3798
                log.Debugf("Sending our NodeAnnouncement1 for "+
11✔
3799
                        "ChannelID(%v) to %x", chanID, pubKey)
11✔
3800

11✔
3801
                // TODO(halseth): make reliable. If the peer is not online this
11✔
3802
                // will fail, and the opening process will stop. Should instead
11✔
3803
                // block here, waiting for the peer to come online.
11✔
3804
                if err := peer.SendMessage(true, &nodeAnn); err != nil {
11✔
3805
                        return fmt.Errorf("unable to send node announcement "+
×
3806
                                "to peer %x: %v", pubKey, err)
×
3807
                }
×
3808
        } else {
21✔
3809
                // Otherwise, we'll wait until the funding transaction has
21✔
3810
                // reached 6 confirmations before announcing it.
21✔
3811
                numConfs := uint32(completeChan.NumConfsRequired)
21✔
3812
                if numConfs < 6 {
42✔
3813
                        numConfs = 6
21✔
3814
                }
21✔
3815
                txid := completeChan.FundingOutpoint.Hash
21✔
3816
                log.Debugf("Will announce channel %v after ChannelPoint"+
21✔
3817
                        "(%v) has gotten %d confirmations",
21✔
3818
                        shortChanID.ToUint64(), completeChan.FundingOutpoint,
21✔
3819
                        numConfs)
21✔
3820

21✔
3821
                fundingScript, err := makeFundingScript(completeChan)
21✔
3822
                if err != nil {
21✔
3823
                        return fmt.Errorf("unable to create funding script "+
×
3824
                                "for ChannelPoint(%v): %v",
×
3825
                                completeChan.FundingOutpoint, err)
×
3826
                }
×
3827

3828
                // Register with the ChainNotifier for a notification once the
3829
                // funding transaction reaches at least 6 confirmations.
3830
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
21✔
3831
                        &txid, fundingScript, numConfs,
21✔
3832
                        completeChan.BroadcastHeight(),
21✔
3833
                )
21✔
3834
                if err != nil {
21✔
3835
                        return fmt.Errorf("unable to register for "+
×
3836
                                "confirmation of ChannelPoint(%v): %v",
×
3837
                                completeChan.FundingOutpoint, err)
×
3838
                }
×
3839

3840
                // Wait until 6 confirmations has been reached or the wallet
3841
                // signals a shutdown.
3842
                select {
21✔
3843
                case _, ok := <-confNtfn.Confirmed:
19✔
3844
                        if !ok {
19✔
3845
                                return fmt.Errorf("ChainNotifier shutting "+
×
3846
                                        "down, cannot complete funding flow "+
×
3847
                                        "for ChannelPoint(%v)",
×
3848
                                        completeChan.FundingOutpoint)
×
3849
                        }
×
3850
                        // Fallthrough.
3851

3852
                case <-f.quit:
5✔
3853
                        return fmt.Errorf("%v, stopping funding flow for "+
5✔
3854
                                "ChannelPoint(%v)",
5✔
3855
                                ErrFundingManagerShuttingDown,
5✔
3856
                                completeChan.FundingOutpoint)
5✔
3857
                }
3858

3859
                fundingPoint := completeChan.FundingOutpoint
19✔
3860
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
19✔
3861

19✔
3862
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
19✔
3863
                        &fundingPoint, shortChanID)
19✔
3864

19✔
3865
                // If this is a non-zero-conf option-scid-alias channel, we'll
19✔
3866
                // delete the mappings the gossiper uses so that ChannelUpdates
19✔
3867
                // with aliases won't be accepted. This is done elsewhere for
19✔
3868
                // zero-conf channels.
19✔
3869
                isScidFeature := completeChan.NegotiatedAliasFeature()
19✔
3870
                isZeroConf := completeChan.IsZeroConf()
19✔
3871
                if isScidFeature && !isZeroConf {
22✔
3872
                        baseScid := completeChan.ShortChanID()
3✔
3873
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
3✔
3874
                        if err != nil {
3✔
3875
                                return fmt.Errorf("failed deleting six confs "+
×
3876
                                        "maps: %v", err)
×
3877
                        }
×
3878

3879
                        // We'll delete the edge and add it again via
3880
                        // addToGraph. This is because the peer may have
3881
                        // sent us a ChannelUpdate with an alias and we don't
3882
                        // want to relay this.
3883
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
3✔
3884
                        if err != nil {
3✔
3885
                                return fmt.Errorf("failed deleting real edge "+
×
3886
                                        "for alias channel from graph: %v",
×
3887
                                        err)
×
3888
                        }
×
3889

3890
                        err = f.addToGraph(
3✔
3891
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3892
                        )
3✔
3893
                        if err != nil {
3✔
3894
                                return fmt.Errorf("failed to re-add to "+
×
3895
                                        "graph: %v", err)
×
3896
                        }
×
3897
                }
3898

3899
                // Create and broadcast the proofs required to make this channel
3900
                // public and usable for other nodes for routing.
3901
                err = f.announceChannel(
19✔
3902
                        f.cfg.IDKey, completeChan.IdentityPub,
19✔
3903
                        &completeChan.LocalChanCfg.MultiSigKey,
19✔
3904
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
19✔
3905
                        *shortChanID, chanID, completeChan.ChanType,
19✔
3906
                )
19✔
3907
                if err != nil {
22✔
3908
                        return fmt.Errorf("channel announcement failed: %w",
3✔
3909
                                err)
3✔
3910
                }
3✔
3911

3912
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
19✔
3913
                        "sent to gossiper", &fundingPoint, shortChanID)
19✔
3914
        }
3915

3916
        return nil
27✔
3917
}
3918

3919
// waitForZeroConfChannel is called when the state is addedToGraph with
3920
// a zero-conf channel. This will wait for the real confirmation, add the
3921
// confirmed SCID to the router graph, and then announce after six confs.
3922
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
9✔
3923
        // First we'll check whether the channel is confirmed on-chain. If it
9✔
3924
        // is already confirmed, the chainntnfs subsystem will return with the
9✔
3925
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
9✔
3926
        confChan, err := f.waitForFundingWithTimeout(c)
9✔
3927
        if err != nil {
14✔
3928
                return fmt.Errorf("error waiting for zero-conf funding "+
5✔
3929
                        "confirmation for ChannelPoint(%v): %v",
5✔
3930
                        c.FundingOutpoint, err)
5✔
3931
        }
5✔
3932

3933
        // We'll need to refresh the channel state so that things are properly
3934
        // populated when validating the channel state. Otherwise, a panic may
3935
        // occur due to inconsistency in the OpenChannel struct.
3936
        err = c.Refresh()
7✔
3937
        if err != nil {
10✔
3938
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3939
        }
3✔
3940

3941
        // Now that we have the confirmed transaction and the proper SCID,
3942
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3943
        // formatted.
3944
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
7✔
3945
        if err != nil {
7✔
3946
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3947
                        "%v", err)
×
3948
        }
×
3949

3950
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3951
        // the database and refresh the OpenChannel struct with it.
3952
        err = c.MarkRealScid(confChan.shortChanID)
7✔
3953
        if err != nil {
7✔
3954
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3955
                        "channel: %v", err)
×
3956
        }
×
3957

3958
        // Six confirmations have been reached. If this channel is public,
3959
        // we'll delete some of the alias mappings the gossiper uses.
3960
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
7✔
3961
        if isPublic {
12✔
3962
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
5✔
3963
                if err != nil {
5✔
3964
                        return fmt.Errorf("unable to delete base alias after "+
×
3965
                                "six confirmations: %v", err)
×
3966
                }
×
3967

3968
                // TODO: Make this atomic!
3969
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
5✔
3970
                if err != nil {
5✔
3971
                        return fmt.Errorf("unable to delete alias edge from "+
×
3972
                                "graph: %v", err)
×
3973
                }
×
3974

3975
                // We'll need to update the graph with the new ShortChannelID
3976
                // via an addToGraph call. We don't pass in the peer's
3977
                // alias since we'll be using the confirmed SCID from now on
3978
                // regardless if it's public or not.
3979
                err = f.addToGraph(
5✔
3980
                        c, &confChan.shortChanID, nil, ourPolicy,
5✔
3981
                )
5✔
3982
                if err != nil {
5✔
3983
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3984
                                "SCID to graph: %v", err)
×
3985
                }
×
3986
        }
3987

3988
        // Since we have now marked down the confirmed SCID, we'll also need to
3989
        // tell the Switch to refresh the relevant ChannelLink so that forwards
3990
        // under the confirmed SCID are possible if this is a public channel.
3991
        err = f.cfg.ReportShortChanID(c.FundingOutpoint)
7✔
3992
        if err != nil {
7✔
3993
                // This should only fail if the link is not found in the
×
3994
                // Switch's linkIndex map. If this is the case, then the peer
×
3995
                // has gone offline and the next time the link is loaded, it
×
3996
                // will have a refreshed state. Just log an error here.
×
3997
                log.Errorf("unable to report scid for zero-conf channel "+
×
3998
                        "channel: %v", err)
×
3999
        }
×
4000

4001
        // Update the confirmed transaction's label.
4002
        f.makeLabelForTx(c)
7✔
4003

7✔
4004
        return nil
7✔
4005
}
4006

4007
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
4008
// is the verification nonce for the state created for us after the initial
4009
// commitment transaction signed as part of the funding flow.
4010
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
4011
) (*musig2.Nonces, error) {
7✔
4012

7✔
4013
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
7✔
4014
                channel.RevocationProducer,
7✔
4015
        )
7✔
4016
        if err != nil {
7✔
4017
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4018
                        "nonces: %v", err)
×
4019
        }
×
4020

4021
        // We use the _next_ commitment height here as we need to generate the
4022
        // nonce for the next state the remote party will sign for us.
4023
        verNonce, err := channeldb.NewMusigVerificationNonce(
7✔
4024
                channel.LocalChanCfg.MultiSigKey.PubKey,
7✔
4025
                channel.LocalCommitment.CommitHeight+1,
7✔
4026
                musig2ShaChain,
7✔
4027
        )
7✔
4028
        if err != nil {
7✔
4029
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4030
                        "nonces: %v", err)
×
4031
        }
×
4032

4033
        return verNonce, nil
7✔
4034
}
4035

4036
// handleChannelReady finalizes the channel funding process and enables the
4037
// channel to enter normal operating mode.
4038
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
4039
        msg *lnwire.ChannelReady) {
31✔
4040

31✔
4041
        defer f.wg.Done()
31✔
4042

31✔
4043
        // Notify the aux hook that the specified peer just established a
31✔
4044
        // channel with us, identified by the given channel ID.
31✔
4045
        f.cfg.AuxChannelNegotiator.WhenSome(
31✔
4046
                func(acn lnwallet.AuxChannelNegotiator) {
31✔
4047
                        acn.ProcessChannelReady(msg.ChanID, peer.PubKey())
×
4048
                },
×
4049
        )
4050

4051
        // If we are in development mode, we'll wait for specified duration
4052
        // before processing the channel ready message.
4053
        if f.cfg.Dev != nil {
34✔
4054
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
4055
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
4056
                        "channel_ready", msg.ChanID, duration)
3✔
4057

3✔
4058
                select {
3✔
4059
                case <-time.After(duration):
3✔
4060
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
4061
                                "channel_ready", msg.ChanID, duration)
3✔
4062
                case <-f.quit:
×
4063
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
4064
                        return
×
4065
                }
4066
        }
4067

4068
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
31✔
4069
                "peer %x", msg.ChanID,
31✔
4070
                peer.IdentityKey().SerializeCompressed())
31✔
4071

31✔
4072
        // We now load or create a new channel barrier for this channel.
31✔
4073
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
31✔
4074
                msg.ChanID, struct{}{},
31✔
4075
        )
31✔
4076

31✔
4077
        // If we are currently in the process of handling a channel_ready
31✔
4078
        // message for this channel, ignore.
31✔
4079
        if loaded {
35✔
4080
                log.Infof("Already handling channelReady for "+
4✔
4081
                        "ChannelID(%v), ignoring.", msg.ChanID)
4✔
4082
                return
4✔
4083
        }
4✔
4084

4085
        // If not already handling channelReady for this channel, then the
4086
        // `LoadOrStore` has set up a barrier, and it will be removed once this
4087
        // function exits.
4088
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
30✔
4089

30✔
4090
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
30✔
4091
        if ok {
58✔
4092
                // Before we proceed with processing the channel_ready
28✔
4093
                // message, we'll wait for the local waitForFundingConfirmation
28✔
4094
                // goroutine to signal that it has the necessary state in
28✔
4095
                // place. Otherwise, we may be missing critical information
28✔
4096
                // required to handle forwarded HTLC's.
28✔
4097
                select {
28✔
4098
                case <-localDiscoverySignal:
28✔
4099
                        // Fallthrough
4100
                case <-f.quit:
3✔
4101
                        return
3✔
4102
                }
4103

4104
                // With the signal received, we can now safely delete the entry
4105
                // from the map.
4106
                f.localDiscoverySignals.Delete(msg.ChanID)
28✔
4107
        }
4108

4109
        // First, we'll attempt to locate the channel whose funding workflow is
4110
        // being finalized by this message. We go to the database rather than
4111
        // our reservation map as we may have restarted, mid funding flow. Also
4112
        // provide the node's public key to make the search faster.
4113
        chanID := msg.ChanID
30✔
4114
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
30✔
4115
        if err != nil {
30✔
4116
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
4117
                        "funding", chanID)
×
4118
                return
×
4119
        }
×
4120

4121
        // If this is a taproot channel, then we can generate the set of nonces
4122
        // the remote party needs to send the next remote commitment here.
4123
        var firstVerNonce *musig2.Nonces
30✔
4124
        if channel.ChanType.IsTaproot() {
37✔
4125
                firstVerNonce, err = genFirstStateMusigNonce(channel)
7✔
4126
                if err != nil {
7✔
4127
                        log.Error(err)
×
4128
                        return
×
4129
                }
×
4130
        }
4131

4132
        // We'll need to store the received TLV alias if the option_scid_alias
4133
        // feature was negotiated. This will be used to provide route hints
4134
        // during invoice creation. In the zero-conf case, it is also used to
4135
        // provide a ChannelUpdate to the remote peer. This is done before the
4136
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
4137
        // If it were to fail on the first call to handleChannelReady, we
4138
        // wouldn't want the channel to be usable yet.
4139
        if channel.NegotiatedAliasFeature() {
39✔
4140
                // If the AliasScid field is nil, we must fail out. We will
9✔
4141
                // most likely not be able to route through the peer.
9✔
4142
                if msg.AliasScid == nil {
9✔
4143
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
4144
                                "does not implement the option-scid-alias "+
×
4145
                                "feature properly", chanID)
×
4146
                        return
×
4147
                }
×
4148

4149
                // We'll store the AliasScid so that invoice creation can use
4150
                // it.
4151
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
9✔
4152
                if err != nil {
9✔
4153
                        log.Errorf("unable to store peer's alias: %v", err)
×
4154
                        return
×
4155
                }
×
4156

4157
                // If we do not have an alias stored, we'll create one now.
4158
                // This is only used in the upgrade case where a user toggles
4159
                // the option-scid-alias feature-bit to on. We'll also send the
4160
                // channel_ready message here in case the link is created
4161
                // before sendChannelReady is called.
4162
                aliases := f.cfg.AliasManager.GetAliases(
9✔
4163
                        channel.ShortChannelID,
9✔
4164
                )
9✔
4165
                if len(aliases) == 0 {
9✔
4166
                        // No aliases were found so we'll request and store an
×
4167
                        // alias and use it in the channel_ready message.
×
4168
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
4169
                        if err != nil {
×
4170
                                log.Errorf("unable to request alias: %v", err)
×
4171
                                return
×
4172
                        }
×
4173

4174
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4175
                                alias, channel.ShortChannelID, false, false,
×
4176
                        )
×
4177
                        if err != nil {
×
4178
                                log.Errorf("unable to add local alias: %v",
×
4179
                                        err)
×
4180
                                return
×
4181
                        }
×
4182

4183
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4184
                        if err != nil {
×
4185
                                log.Errorf("unable to fetch second "+
×
4186
                                        "commitment point: %v", err)
×
4187
                                return
×
4188
                        }
×
4189

4190
                        channelReadyMsg := lnwire.NewChannelReady(
×
4191
                                chanID, secondPoint,
×
4192
                        )
×
4193
                        channelReadyMsg.AliasScid = &alias
×
4194

×
4195
                        if firstVerNonce != nil {
×
4196
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4197
                                        firstVerNonce.PubNonce,
×
4198
                                )
×
4199
                        }
×
4200

4201
                        err = peer.SendMessage(true, channelReadyMsg)
×
4202
                        if err != nil {
×
4203
                                log.Errorf("unable to send channel_ready: %v",
×
4204
                                        err)
×
4205
                                return
×
4206
                        }
×
4207
                }
4208
        }
4209

4210
        // If the RemoteNextRevocation is non-nil, it means that we have
4211
        // already processed channelReady for this channel, so ignore. This
4212
        // check is after the alias logic so we store the peer's most recent
4213
        // alias. The spec requires us to validate that subsequent
4214
        // channel_ready messages use the same per commitment point (the
4215
        // second), but it is not actually necessary since we'll just end up
4216
        // ignoring it. We are, however, required to *send* the same per
4217
        // commitment point, since another pedantic implementation might
4218
        // verify it.
4219
        if channel.RemoteNextRevocation != nil {
34✔
4220
                log.Infof("Received duplicate channelReady for "+
4✔
4221
                        "ChannelID(%v), ignoring.", chanID)
4✔
4222
                return
4✔
4223
        }
4✔
4224

4225
        // If this is a taproot channel, then we'll need to map the received
4226
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4227
        // required in order to make the channel whole.
4228
        var chanOpts []lnwallet.ChannelOpt
29✔
4229
        if channel.ChanType.IsTaproot() {
36✔
4230
                f.nonceMtx.Lock()
7✔
4231
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
4232
                if !ok {
10✔
4233
                        // If there's no pending nonce for this channel ID,
3✔
4234
                        // we'll use the one generated above.
3✔
4235
                        localNonce = firstVerNonce
3✔
4236
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4237
                }
3✔
4238
                f.nonceMtx.Unlock()
7✔
4239

7✔
4240
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
7✔
4241
                        chanID)
7✔
4242

7✔
4243
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
7✔
4244
                        errNoLocalNonce,
7✔
4245
                )
7✔
4246
                if err != nil {
7✔
4247
                        cid := newChanIdentifier(msg.ChanID)
×
4248
                        f.sendWarning(peer, cid, err)
×
4249

×
4250
                        return
×
4251
                }
×
4252

4253
                chanOpts = append(
7✔
4254
                        chanOpts,
7✔
4255
                        lnwallet.WithLocalMusigNonces(localNonce),
7✔
4256
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
7✔
4257
                                PubNonce: remoteNonce,
7✔
4258
                        }),
7✔
4259
                )
7✔
4260

7✔
4261
                // Inform the aux funding controller that the liquidity in the
7✔
4262
                // custom channel is now ready to be advertised. We potentially
7✔
4263
                // haven't sent our own channel ready message yet, but other
7✔
4264
                // than that the channel is ready to count toward available
7✔
4265
                // liquidity.
7✔
4266
                err = fn.MapOptionZ(
7✔
4267
                        f.cfg.AuxFundingController,
7✔
4268
                        func(controller AuxFundingController) error {
7✔
4269
                                return controller.ChannelReady(
×
4270
                                        lnwallet.NewAuxChanState(channel),
×
4271
                                )
×
4272
                        },
×
4273
                )
4274
                if err != nil {
7✔
4275
                        cid := newChanIdentifier(msg.ChanID)
×
4276
                        f.sendWarning(peer, cid, err)
×
4277

×
4278
                        return
×
4279
                }
×
4280
        }
4281

4282
        // The channel_ready message contains the next commitment point we'll
4283
        // need to create the next commitment state for the remote party. So
4284
        // we'll insert that into the channel now before passing it along to
4285
        // other sub-systems.
4286
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
29✔
4287
        if err != nil {
29✔
4288
                log.Errorf("unable to insert next commitment point: %v", err)
×
4289
                return
×
4290
        }
×
4291

4292
        // Before we can add the channel to the peer, we'll need to ensure that
4293
        // we have an initial forwarding policy set.
4294
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
29✔
4295
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4296
                        err)
×
4297
        }
×
4298

4299
        err = peer.AddNewChannel(&lnpeer.NewChannel{
29✔
4300
                OpenChannel: channel,
29✔
4301
                ChanOpts:    chanOpts,
29✔
4302
        }, f.quit)
29✔
4303
        if err != nil {
30✔
4304
                log.Errorf("Unable to add new channel %v with peer %x: %v",
1✔
4305
                        channel.FundingOutpoint,
1✔
4306
                        peer.IdentityKey().SerializeCompressed(), err,
1✔
4307
                )
1✔
4308
        }
1✔
4309
}
4310

4311
// handleChannelReadyReceived is called once the remote's channelReady message
4312
// is received and processed. At this stage, we must have sent out our
4313
// channelReady message, once the remote's channelReady is processed, the
4314
// channel is now active, thus we change its state to `addedToGraph` to
4315
// let the channel start handling routing.
4316
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4317
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4318
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
27✔
4319

27✔
4320
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
27✔
4321

27✔
4322
        // Since we've sent+received funding locked at this point, we
27✔
4323
        // can clean up the pending musig2 nonce state.
27✔
4324
        f.nonceMtx.Lock()
27✔
4325
        delete(f.pendingMusigNonces, chanID)
27✔
4326
        f.nonceMtx.Unlock()
27✔
4327

27✔
4328
        var peerAlias *lnwire.ShortChannelID
27✔
4329
        if channel.IsZeroConf() {
34✔
4330
                // We'll need to wait until channel_ready has been received and
7✔
4331
                // the peer lets us know the alias they want to use for the
7✔
4332
                // channel. With this information, we can then construct a
7✔
4333
                // ChannelUpdate for them.  If an alias does not yet exist,
7✔
4334
                // we'll just return, letting the next iteration of the loop
7✔
4335
                // check again.
7✔
4336
                var defaultAlias lnwire.ShortChannelID
7✔
4337
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
7✔
4338
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
7✔
4339
                if foundAlias == defaultAlias {
7✔
4340
                        return nil
×
4341
                }
×
4342

4343
                peerAlias = &foundAlias
7✔
4344
        }
4345

4346
        err := f.addToGraph(channel, scid, peerAlias, nil)
27✔
4347
        if err != nil {
27✔
4348
                return fmt.Errorf("failed adding to graph: %w", err)
×
4349
        }
×
4350

4351
        // As the channel is now added to the ChannelRouter's topology, the
4352
        // channel is moved to the next state of the state machine. It will be
4353
        // moved to the last state (actually deleted from the database) after
4354
        // the channel is finally announced.
4355
        err = f.saveChannelOpeningState(
27✔
4356
                &channel.FundingOutpoint, addedToGraph, scid,
27✔
4357
        )
27✔
4358
        if err != nil {
27✔
4359
                return fmt.Errorf("error setting channel state to"+
×
4360
                        " addedToGraph: %w", err)
×
4361
        }
×
4362

4363
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
4364
                "added to graph", chanID, scid)
27✔
4365

27✔
4366
        err = fn.MapOptionZ(
27✔
4367
                f.cfg.AuxFundingController,
27✔
4368
                func(controller AuxFundingController) error {
27✔
4369
                        return controller.ChannelReady(
×
4370
                                lnwallet.NewAuxChanState(channel),
×
4371
                        )
×
4372
                },
×
4373
        )
4374
        if err != nil {
27✔
4375
                return fmt.Errorf("failed notifying aux funding controller "+
×
4376
                        "about channel ready: %w", err)
×
4377
        }
×
4378

4379
        // Give the caller a final update notifying them that the channel is
4380
        fundingPoint := channel.FundingOutpoint
27✔
4381
        cp := &lnrpc.ChannelPoint{
27✔
4382
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
27✔
4383
                        FundingTxidBytes: fundingPoint.Hash[:],
27✔
4384
                },
27✔
4385
                OutputIndex: fundingPoint.Index,
27✔
4386
        }
27✔
4387

27✔
4388
        if updateChan != nil {
40✔
4389
                upd := &lnrpc.OpenStatusUpdate{
13✔
4390
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
13✔
4391
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
13✔
4392
                                        ChannelPoint: cp,
13✔
4393
                                },
13✔
4394
                        },
13✔
4395
                        PendingChanId: pendingChanID[:],
13✔
4396
                }
13✔
4397

13✔
4398
                select {
13✔
4399
                case updateChan <- upd:
13✔
4400
                case <-f.quit:
×
4401
                        return ErrFundingManagerShuttingDown
×
4402
                }
4403
        }
4404

4405
        return nil
27✔
4406
}
4407

4408
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4409
// policy set for the given channel. If we don't, we'll fall back to the default
4410
// values.
4411
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4412
        channel *channeldb.OpenChannel) error {
29✔
4413

29✔
4414
        // Before we can add the channel to the peer, we'll need to ensure that
29✔
4415
        // we have an initial forwarding policy set. This should always be the
29✔
4416
        // case except for a channel that was created with lnd <= 0.15.5 and
29✔
4417
        // is still pending while updating to this version.
29✔
4418
        var needDBUpdate bool
29✔
4419
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
29✔
4420
        if err != nil {
29✔
4421
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4422
                        "falling back to default values: %v", err)
×
4423

×
4424
                forwardingPolicy = f.defaultForwardingPolicy(
×
4425
                        channel.LocalChanCfg.ChannelStateBounds,
×
4426
                )
×
4427
                needDBUpdate = true
×
4428
        }
×
4429

4430
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4431
        // after 0.16.x, so if a channel was opened with such a version and is
4432
        // still pending while updating to this version, we'll need to set the
4433
        // values to the default values.
4434
        if forwardingPolicy.MinHTLCOut == 0 {
45✔
4435
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
16✔
4436
                needDBUpdate = true
16✔
4437
        }
16✔
4438
        if forwardingPolicy.MaxHTLC == 0 {
45✔
4439
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
16✔
4440
                needDBUpdate = true
16✔
4441
        }
16✔
4442

4443
        // And finally, if we found that the values currently stored aren't
4444
        // sufficient for the link, we'll update the database.
4445
        if needDBUpdate {
45✔
4446
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
16✔
4447
                if err != nil {
16✔
4448
                        return fmt.Errorf("unable to update initial "+
×
4449
                                "forwarding policy: %v", err)
×
4450
                }
×
4451
        }
4452

4453
        return nil
29✔
4454
}
4455

4456
// chanAnnouncement encapsulates the two authenticated announcements that we
4457
// send out to the network after a new channel has been created locally.
4458
type chanAnnouncement struct {
4459
        chanAnn       *lnwire.ChannelAnnouncement1
4460
        chanUpdateAnn *lnwire.ChannelUpdate1
4461
        chanProof     *lnwire.AnnounceSignatures1
4462
}
4463

4464
// newChanAnnouncement creates the authenticated channel announcement messages
4465
// required to broadcast a newly created channel to the network. The
4466
// announcement is two part: the first part authenticates the existence of the
4467
// channel and contains four signatures binding the funding pub keys and
4468
// identity pub keys of both parties to the channel, and the second segment is
4469
// authenticated only by us and contains our directional routing policy for the
4470
// channel. ourPolicy may be set in order to re-use an existing, non-default
4471
// policy.
4472
func (f *Manager) newChanAnnouncement(localPubKey,
4473
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4474
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4475
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4476
        ourPolicy *models.ChannelEdgePolicy,
4477
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
45✔
4478

45✔
4479
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
45✔
4480

45✔
4481
        // The unconditional section of the announcement is the ShortChannelID
45✔
4482
        // itself which compactly encodes the location of the funding output
45✔
4483
        // within the blockchain.
45✔
4484
        chanAnn := &lnwire.ChannelAnnouncement1{
45✔
4485
                ShortChannelID: shortChanID,
45✔
4486
                Features:       lnwire.NewRawFeatureVector(),
45✔
4487
                ChainHash:      chainHash,
45✔
4488
        }
45✔
4489

45✔
4490
        // If this is a taproot channel, then we'll set a special bit in the
45✔
4491
        // feature vector to indicate to the routing layer that this needs a
45✔
4492
        // slightly different type of validation.
45✔
4493
        //
45✔
4494
        // TODO(roasbeef): temp, remove after gossip 1.5
45✔
4495
        if chanType.IsTaproot() {
52✔
4496
                log.Debugf("Applying taproot feature bit to "+
7✔
4497
                        "ChannelAnnouncement for %v", chanID)
7✔
4498

7✔
4499
                chanAnn.Features.Set(
7✔
4500
                        lnwire.SimpleTaprootChannelsRequiredStaging,
7✔
4501
                )
7✔
4502
        }
7✔
4503

4504
        // The chanFlags field indicates which directed edge of the channel is
4505
        // being updated within the ChannelUpdateAnnouncement announcement
4506
        // below. A value of zero means it's the edge of the "first" node and 1
4507
        // being the other node.
4508
        var chanFlags lnwire.ChanUpdateChanFlags
45✔
4509

45✔
4510
        // The lexicographical ordering of the two identity public keys of the
45✔
4511
        // nodes indicates which of the nodes is "first". If our serialized
45✔
4512
        // identity key is lower than theirs then we're the "first" node and
45✔
4513
        // second otherwise.
45✔
4514
        selfBytes := localPubKey.SerializeCompressed()
45✔
4515
        remoteBytes := remotePubKey.SerializeCompressed()
45✔
4516
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
69✔
4517
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
24✔
4518
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
24✔
4519
                copy(
24✔
4520
                        chanAnn.BitcoinKey1[:],
24✔
4521
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4522
                )
24✔
4523
                copy(
24✔
4524
                        chanAnn.BitcoinKey2[:],
24✔
4525
                        remoteFundingKey.SerializeCompressed(),
24✔
4526
                )
24✔
4527

24✔
4528
                // If we're the first node then update the chanFlags to
24✔
4529
                // indicate the "direction" of the update.
24✔
4530
                chanFlags = 0
24✔
4531
        } else {
48✔
4532
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
24✔
4533
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
24✔
4534
                copy(
24✔
4535
                        chanAnn.BitcoinKey1[:],
24✔
4536
                        remoteFundingKey.SerializeCompressed(),
24✔
4537
                )
24✔
4538
                copy(
24✔
4539
                        chanAnn.BitcoinKey2[:],
24✔
4540
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4541
                )
24✔
4542

24✔
4543
                // If we're the second node then update the chanFlags to
24✔
4544
                // indicate the "direction" of the update.
24✔
4545
                chanFlags = 1
24✔
4546
        }
24✔
4547

4548
        // Our channel update message flags will signal that we support the
4549
        // max_htlc field.
4550
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
45✔
4551

45✔
4552
        // We announce the channel with the default values. Some of
45✔
4553
        // these values can later be changed by crafting a new ChannelUpdate.
45✔
4554
        chanUpdateAnn := &lnwire.ChannelUpdate1{
45✔
4555
                ShortChannelID: shortChanID,
45✔
4556
                ChainHash:      chainHash,
45✔
4557
                Timestamp:      uint32(time.Now().Unix()),
45✔
4558
                MessageFlags:   msgFlags,
45✔
4559
                ChannelFlags:   chanFlags,
45✔
4560
                TimeLockDelta: uint16(
45✔
4561
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
45✔
4562
                ),
45✔
4563
                HtlcMinimumMsat: fwdMinHTLC,
45✔
4564
                HtlcMaximumMsat: fwdMaxHTLC,
45✔
4565
        }
45✔
4566

45✔
4567
        // The caller of newChanAnnouncement is expected to provide the initial
45✔
4568
        // forwarding policy to be announced. If no persisted initial policy
45✔
4569
        // values are found, then we will use the default policy values in the
45✔
4570
        // channel announcement.
45✔
4571
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
45✔
4572
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
45✔
4573
                return nil, fmt.Errorf("unable to generate channel "+
×
4574
                        "update announcement: %w", err)
×
4575
        }
×
4576

4577
        switch {
45✔
4578
        case ourPolicy != nil:
3✔
4579
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4580
                // ChannelUpdate.
3✔
4581
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4582
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4583
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4584
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4585
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4586
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4587
                chanUpdateAnn.FeeRate = uint32(
3✔
4588
                        ourPolicy.FeeProportionalMillionths,
3✔
4589
                )
3✔
4590

4591
        case storedFwdingPolicy != nil:
45✔
4592
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
45✔
4593
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
45✔
4594

4595
        default:
×
4596
                log.Infof("No channel forwarding policy specified for channel "+
×
4597
                        "announcement of ChannelID(%v). "+
×
4598
                        "Assuming default fee parameters.", chanID)
×
4599
                chanUpdateAnn.BaseFee = uint32(
×
4600
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4601
                )
×
4602
                chanUpdateAnn.FeeRate = uint32(
×
4603
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4604
                )
×
4605
        }
4606

4607
        // With the channel update announcement constructed, we'll generate a
4608
        // signature that signs a double-sha digest of the announcement.
4609
        // This'll serve to authenticate this announcement and any other future
4610
        // updates we may send.
4611
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
45✔
4612
        if err != nil {
45✔
4613
                return nil, err
×
4614
        }
×
4615
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
45✔
4616
        if err != nil {
45✔
4617
                return nil, fmt.Errorf("unable to generate channel "+
×
4618
                        "update announcement signature: %w", err)
×
4619
        }
×
4620
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
45✔
4621
        if err != nil {
45✔
4622
                return nil, fmt.Errorf("unable to generate channel "+
×
4623
                        "update announcement signature: %w", err)
×
4624
        }
×
4625

4626
        // The channel existence proofs itself is currently announced in
4627
        // distinct message. In order to properly authenticate this message, we
4628
        // need two signatures: one under the identity public key used which
4629
        // signs the message itself and another signature of the identity
4630
        // public key under the funding key itself.
4631
        //
4632
        // TODO(roasbeef): use SignAnnouncement here instead?
4633
        chanAnnMsg, err := chanAnn.DataToSign()
45✔
4634
        if err != nil {
45✔
4635
                return nil, err
×
4636
        }
×
4637
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
45✔
4638
        if err != nil {
45✔
4639
                return nil, fmt.Errorf("unable to generate node "+
×
4640
                        "signature for channel announcement: %w", err)
×
4641
        }
×
4642
        bitcoinSig, err := f.cfg.SignMessage(
45✔
4643
                localFundingKey.KeyLocator, chanAnnMsg, true,
45✔
4644
        )
45✔
4645
        if err != nil {
45✔
4646
                return nil, fmt.Errorf("unable to generate bitcoin "+
×
4647
                        "signature for node public key: %w", err)
×
4648
        }
×
4649

4650
        // Finally, we'll generate the announcement proof which we'll use to
4651
        // provide the other side with the necessary signatures required to
4652
        // allow them to reconstruct the full channel announcement.
4653
        proof := &lnwire.AnnounceSignatures1{
45✔
4654
                ChannelID:      chanID,
45✔
4655
                ShortChannelID: shortChanID,
45✔
4656
        }
45✔
4657
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
45✔
4658
        if err != nil {
45✔
4659
                return nil, err
×
4660
        }
×
4661
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
45✔
4662
        if err != nil {
45✔
4663
                return nil, err
×
4664
        }
×
4665

4666
        return &chanAnnouncement{
45✔
4667
                chanAnn:       chanAnn,
45✔
4668
                chanUpdateAnn: chanUpdateAnn,
45✔
4669
                chanProof:     proof,
45✔
4670
        }, nil
45✔
4671
}
4672

4673
// announceChannel announces a newly created channel to the rest of the network
4674
// by crafting the two authenticated announcements required for the peers on
4675
// the network to recognize the legitimacy of the channel. The crafted
4676
// announcements are then sent to the channel router to handle broadcasting to
4677
// the network during its next trickle.
4678
// This method is synchronous and will return when all the network requests
4679
// finish, either successfully or with an error.
4680
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4681
        localFundingKey *keychain.KeyDescriptor,
4682
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4683
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
19✔
4684

19✔
4685
        // First, we'll create the batch of announcements to be sent upon
19✔
4686
        // initial channel creation. This includes the channel announcement
19✔
4687
        // itself, the channel update announcement, and our half of the channel
19✔
4688
        // proof needed to fully authenticate the channel.
19✔
4689
        //
19✔
4690
        // We can pass in zeroes for the min and max htlc policy, because we
19✔
4691
        // only use the channel announcement message from the returned struct.
19✔
4692
        ann, err := f.newChanAnnouncement(
19✔
4693
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
19✔
4694
                shortChanID, chanID, 0, 0, nil, chanType,
19✔
4695
        )
19✔
4696
        if err != nil {
19✔
4697
                log.Errorf("can't generate channel announcement: %v", err)
×
4698
                return err
×
4699
        }
×
4700

4701
        // We only send the channel proof announcement and the node announcement
4702
        // because addToGraph previously sent the ChannelAnnouncement and
4703
        // the ChannelUpdate announcement messages. The channel proof and node
4704
        // announcements are broadcast to the greater network.
4705
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
19✔
4706
        select {
19✔
4707
        case err := <-errChan:
19✔
4708
                if err != nil {
22✔
4709
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4710
                                graph.ErrIgnored) {
3✔
4711

×
4712
                                log.Debugf("Graph rejected "+
×
4713
                                        "AnnounceSignatures: %v", err)
×
4714
                        } else {
3✔
4715
                                log.Errorf("Unable to send channel "+
3✔
4716
                                        "proof: %v", err)
3✔
4717
                                return err
3✔
4718
                        }
3✔
4719
                }
4720

4721
        case <-f.quit:
×
4722
                return ErrFundingManagerShuttingDown
×
4723
        }
4724

4725
        // Now that the channel is announced to the network, we will also
4726
        // obtain and send a node announcement. This is done since a node
4727
        // announcement is only accepted after a channel is known for that
4728
        // particular node, and this might be our first channel.
4729
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
19✔
4730
        if err != nil {
19✔
4731
                log.Errorf("can't generate node announcement: %v", err)
×
4732
                return err
×
4733
        }
×
4734

4735
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
19✔
4736
        select {
19✔
4737
        case err := <-errChan:
19✔
4738
                if err != nil {
22✔
4739
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4740
                                graph.ErrIgnored) {
6✔
4741

3✔
4742
                                log.Debugf("Graph rejected "+
3✔
4743
                                        "NodeAnnouncement1: %v", err)
3✔
4744
                        } else {
3✔
4745
                                log.Errorf("Unable to send node "+
×
4746
                                        "announcement: %v", err)
×
4747
                                return err
×
4748
                        }
×
4749
                }
4750

4751
        case <-f.quit:
×
4752
                return ErrFundingManagerShuttingDown
×
4753
        }
4754

4755
        return nil
19✔
4756
}
4757

4758
// InitFundingWorkflow sends a message to the funding manager instructing it
4759
// to initiate a single funder workflow with the source peer.
4760
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
60✔
4761
        f.fundingRequests <- msg
60✔
4762
}
60✔
4763

4764
// getUpfrontShutdownScript takes a user provided script and a getScript
4765
// function which can be used to generate an upfront shutdown script. If our
4766
// peer does not support the feature, this function will error if a non-zero
4767
// script was provided by the user, and return an empty script otherwise. If
4768
// our peer does support the feature, we will return the user provided script
4769
// if non-zero, or a freshly generated script if our node is configured to set
4770
// upfront shutdown scripts automatically.
4771
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4772
        script lnwire.DeliveryAddress,
4773
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4774
        error) {
113✔
4775

113✔
4776
        // Check whether the remote peer supports upfront shutdown scripts.
113✔
4777
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
113✔
4778
                lnwire.UpfrontShutdownScriptOptional,
113✔
4779
        )
113✔
4780

113✔
4781
        // If the peer does not support upfront shutdown scripts, and one has been
113✔
4782
        // provided, return an error because the feature is not supported.
113✔
4783
        if !remoteUpfrontShutdown && len(script) != 0 {
114✔
4784
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4785
        }
1✔
4786

4787
        // If the peer does not support upfront shutdown, return an empty address.
4788
        if !remoteUpfrontShutdown {
217✔
4789
                return nil, nil
105✔
4790
        }
105✔
4791

4792
        // If the user has provided an script and the peer supports the feature,
4793
        // return it. Note that user set scripts override the enable upfront
4794
        // shutdown flag.
4795
        if len(script) > 0 {
12✔
4796
                return script, nil
5✔
4797
        }
5✔
4798

4799
        // If we do not have setting of upfront shutdown script enabled, return
4800
        // an empty script.
4801
        if !enableUpfrontShutdown {
9✔
4802
                return nil, nil
4✔
4803
        }
4✔
4804

4805
        // We can safely send a taproot address iff, both sides have negotiated
4806
        // the shutdown-any-segwit feature.
4807
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4808
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4809

1✔
4810
        return getScript(taprootOK)
1✔
4811
}
4812

4813
// handleInitFundingMsg creates a channel reservation within the daemon's
4814
// wallet, then sends a funding request to the remote peer kicking off the
4815
// funding workflow.
4816
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
60✔
4817
        var (
60✔
4818
                peerKey        = msg.Peer.IdentityKey()
60✔
4819
                localAmt       = msg.LocalFundingAmt
60✔
4820
                baseFee        = msg.BaseFee
60✔
4821
                feeRate        = msg.FeeRate
60✔
4822
                minHtlcIn      = msg.MinHtlcIn
60✔
4823
                remoteCsvDelay = msg.RemoteCsvDelay
60✔
4824
                maxValue       = msg.MaxValueInFlight
60✔
4825
                maxHtlcs       = msg.MaxHtlcs
60✔
4826
                maxCSV         = msg.MaxLocalCsv
60✔
4827
                chanReserve    = msg.RemoteChanReserve
60✔
4828
                outpoints      = msg.Outpoints
60✔
4829
        )
60✔
4830

60✔
4831
        // If no maximum CSV delay was set for this channel, we use our default
60✔
4832
        // value.
60✔
4833
        if maxCSV == 0 {
120✔
4834
                maxCSV = f.cfg.MaxLocalCSVDelay
60✔
4835
        }
60✔
4836

4837
        log.Infof("Initiating fundingRequest(local_amt=%v "+
60✔
4838
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
60✔
4839
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
60✔
4840
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
60✔
4841

60✔
4842
        // We set the channel flags to indicate whether we want this channel to
60✔
4843
        // be announced to the network.
60✔
4844
        var channelFlags lnwire.FundingFlag
60✔
4845
        if !msg.Private {
115✔
4846
                // This channel will be announced.
55✔
4847
                channelFlags = lnwire.FFAnnounceChannel
55✔
4848
        }
55✔
4849

4850
        // If the caller specified their own channel ID, then we'll use that.
4851
        // Otherwise we'll generate a fresh one as normal.  This will be used
4852
        // to track this reservation throughout its lifetime.
4853
        var chanID PendingChanID
60✔
4854
        if msg.PendingChanID == zeroID {
120✔
4855
                chanID = f.nextPendingChanID()
60✔
4856
        } else {
63✔
4857
                // If the user specified their own pending channel ID, then
3✔
4858
                // we'll ensure it doesn't collide with any existing pending
3✔
4859
                // channel ID.
3✔
4860
                chanID = msg.PendingChanID
3✔
4861
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
3✔
4862
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4863
                                "already present", chanID[:])
×
4864
                        return
×
4865
                }
×
4866
        }
4867

4868
        // If the funder did not provide an upfront-shutdown address, fall back
4869
        // to the configured shutdown script (if any).
4870
        shutdownScript := msg.ShutdownScript
60✔
4871
        if len(shutdownScript) == 0 {
120✔
4872
                f.cfg.ShutdownScript.WhenSome(
60✔
4873
                        func(script lnwire.DeliveryAddress) {
63✔
4874
                                shutdownScript = script
3✔
4875
                        },
3✔
4876
                )
4877
        }
4878

4879
        // Check whether the peer supports upfront shutdown, and get an address
4880
        // which should be used (either a user specified address or a new
4881
        // address from the wallet if our node is configured to set shutdown
4882
        // address by default).
4883
        shutdown, err := getUpfrontShutdownScript(
60✔
4884
                f.cfg.EnableUpfrontShutdown, msg.Peer, shutdownScript,
60✔
4885
                f.selectShutdownScript,
60✔
4886
        )
60✔
4887
        if err != nil {
60✔
4888
                msg.Err <- err
×
4889
                return
×
4890
        }
×
4891

4892
        // Initialize a funding reservation with the local wallet. If the
4893
        // wallet doesn't have enough funds to commit to this channel, then the
4894
        // request will fail, and be aborted.
4895
        //
4896
        // Before we init the channel, we'll also check to see what commitment
4897
        // format we can use with this peer. This is dependent on *both* us and
4898
        // the remote peer are signaling the proper feature bit.
4899
        chanType, commitType, err := negotiateCommitmentType(
60✔
4900
                msg.ChannelType, msg.Peer.LocalFeatures(),
60✔
4901
                msg.Peer.RemoteFeatures(),
60✔
4902
        )
60✔
4903
        if err != nil {
63✔
4904
                log.Errorf("channel type negotiation failed: %v", err)
3✔
4905
                msg.Err <- err
3✔
4906
                return
3✔
4907
        }
3✔
4908

4909
        var (
60✔
4910
                zeroConf bool
60✔
4911
                scid     bool
60✔
4912
        )
60✔
4913

60✔
4914
        if chanType != nil {
67✔
4915
                // Check if the returned chanType includes either the zero-conf
7✔
4916
                // or scid-alias bits.
7✔
4917
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
4918
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
4919
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
4920

7✔
4921
                // The option-scid-alias channel type for a public channel is
7✔
4922
                // disallowed.
7✔
4923
                if scid && !msg.Private {
7✔
4924
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4925
                                "public channel")
×
4926
                        log.Error(err)
×
4927
                        msg.Err <- err
×
4928

×
4929
                        return
×
4930
                }
×
4931
        }
4932

4933
        // First, we'll query the fee estimator for a fee that should get the
4934
        // commitment transaction confirmed by the next few blocks (conf target
4935
        // of 3). We target the near blocks here to ensure that we'll be able
4936
        // to execute a timely unilateral channel closure if needed.
4937
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
60✔
4938
        if err != nil {
60✔
4939
                msg.Err <- err
×
4940
                return
×
4941
        }
×
4942

4943
        // For anchor channels cap the initial commit fee rate at our defined
4944
        // maximum.
4945
        if commitType.HasAnchors() &&
60✔
4946
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
67✔
4947

7✔
4948
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
7✔
4949
        }
7✔
4950

4951
        var scidFeatureVal bool
60✔
4952
        if hasFeatures(
60✔
4953
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
60✔
4954
                lnwire.ScidAliasOptional,
60✔
4955
        ) {
66✔
4956

6✔
4957
                scidFeatureVal = true
6✔
4958
        }
6✔
4959

4960
        // At this point, if we have an AuxFundingController active, we'll check
4961
        // to see if we have a special tapscript root to use in our MuSig2
4962
        // funding output.
4963
        tapscriptRoot, err := fn.MapOptionZ(
60✔
4964
                f.cfg.AuxFundingController,
60✔
4965
                func(c AuxFundingController) AuxTapscriptResult {
60✔
4966
                        return c.DeriveTapscriptRoot(chanID)
×
4967
                },
×
4968
        ).Unpack()
4969
        if err != nil {
60✔
4970
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4971
                log.Error(err)
×
4972
                msg.Err <- err
×
4973

×
4974
                return
×
4975
        }
×
4976

4977
        req := &lnwallet.InitFundingReserveMsg{
60✔
4978
                ChainHash:         &msg.ChainHash,
60✔
4979
                PendingChanID:     chanID,
60✔
4980
                NodeID:            peerKey,
60✔
4981
                NodeAddr:          msg.Peer.Address(),
60✔
4982
                SubtractFees:      msg.SubtractFees,
60✔
4983
                LocalFundingAmt:   localAmt,
60✔
4984
                RemoteFundingAmt:  0,
60✔
4985
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
60✔
4986
                MinFundAmt:        msg.MinFundAmt,
60✔
4987
                RemoteChanReserve: chanReserve,
60✔
4988
                Outpoints:         outpoints,
60✔
4989
                CommitFeePerKw:    commitFeePerKw,
60✔
4990
                FundingFeePerKw:   msg.FundingFeePerKw,
60✔
4991
                PushMSat:          msg.PushAmt,
60✔
4992
                Flags:             channelFlags,
60✔
4993
                MinConfs:          msg.MinConfs,
60✔
4994
                CommitType:        commitType,
60✔
4995
                ChanFunder:        msg.ChanFunder,
60✔
4996
                // Unconfirmed Utxos which are marked by the sweeper subsystem
60✔
4997
                // are excluded from the coin selection because they are not
60✔
4998
                // final and can be RBFed by the sweeper subsystem.
60✔
4999
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
121✔
5000
                        // Utxos with at least 1 confirmation are safe to use
61✔
5001
                        // for channel openings because they don't bare the risk
61✔
5002
                        // of being replaced (BIP 125 RBF).
61✔
5003
                        if u.Confirmations > 0 {
64✔
5004
                                return true
3✔
5005
                        }
3✔
5006

5007
                        // Query the sweeper storage to make sure we don't use
5008
                        // an unconfirmed utxo still in use by the sweeper
5009
                        // subsystem.
5010
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
61✔
5011
                },
5012
                ZeroConf:         zeroConf,
5013
                OptionScidAlias:  scid,
5014
                ScidAliasFeature: scidFeatureVal,
5015
                Memo:             msg.Memo,
5016
                TapscriptRoot:    tapscriptRoot,
5017
        }
5018

5019
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
60✔
5020
        if err != nil {
63✔
5021
                msg.Err <- err
3✔
5022
                return
3✔
5023
        }
3✔
5024

5025
        if zeroConf {
65✔
5026
                // Store the alias for zero-conf channels in the underlying
5✔
5027
                // partial channel state.
5✔
5028
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
5029
                if err != nil {
5✔
5030
                        msg.Err <- err
×
5031
                        return
×
5032
                }
×
5033

5034
                reservation.AddAlias(aliasScid)
5✔
5035
        }
5036

5037
        // Set our upfront shutdown address in the existing reservation.
5038
        reservation.SetOurUpfrontShutdown(shutdown)
60✔
5039

60✔
5040
        // Now that we have successfully reserved funds for this channel in the
60✔
5041
        // wallet, we can fetch the final channel capacity. This is done at
60✔
5042
        // this point since the final capacity might change in case of
60✔
5043
        // SubtractFees=true.
60✔
5044
        capacity := reservation.Capacity()
60✔
5045

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

60✔
5049
        // If the remote CSV delay was not set in the open channel request,
60✔
5050
        // we'll use the RequiredRemoteDelay closure to compute the delay we
60✔
5051
        // require given the total amount of funds within the channel.
60✔
5052
        if remoteCsvDelay == 0 {
119✔
5053
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
59✔
5054
        }
59✔
5055

5056
        // If no minimum HTLC value was specified, use the default one.
5057
        if minHtlcIn == 0 {
119✔
5058
                minHtlcIn = f.cfg.DefaultMinHtlcIn
59✔
5059
        }
59✔
5060

5061
        // If no max value was specified, use the default one.
5062
        if maxValue == 0 {
119✔
5063
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
59✔
5064
        }
59✔
5065

5066
        if maxHtlcs == 0 {
120✔
5067
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
60✔
5068
        }
60✔
5069

5070
        // Once the reservation has been created, and indexed, queue a funding
5071
        // request to the remote peer, kicking off the funding workflow.
5072
        ourContribution := reservation.OurContribution()
60✔
5073

60✔
5074
        // Prepare the optional channel fee values from the initFundingMsg. If
60✔
5075
        // useBaseFee or useFeeRate are false the client did not provide fee
60✔
5076
        // values hence we assume default fee settings from the config.
60✔
5077
        forwardingPolicy := f.defaultForwardingPolicy(
60✔
5078
                ourContribution.ChannelStateBounds,
60✔
5079
        )
60✔
5080
        if baseFee != nil {
64✔
5081
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
4✔
5082
        }
4✔
5083

5084
        if feeRate != nil {
64✔
5085
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
4✔
5086
        }
4✔
5087

5088
        // Fetch our dust limit which is part of the default channel
5089
        // constraints, and log it.
5090
        ourDustLimit := ourContribution.DustLimit
60✔
5091

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

60✔
5094
        // If the channel reserve is not specified, then we calculate an
60✔
5095
        // appropriate amount here.
60✔
5096
        if chanReserve == 0 {
116✔
5097
                chanReserve = f.cfg.RequiredRemoteChanReserve(
56✔
5098
                        capacity, ourDustLimit,
56✔
5099
                )
56✔
5100
        }
56✔
5101

5102
        // If a pending channel map for this peer isn't already created, then
5103
        // we create one, ultimately allowing us to track this pending
5104
        // reservation within the target peer.
5105
        peerIDKey := newSerializedKey(peerKey)
60✔
5106
        f.resMtx.Lock()
60✔
5107
        if _, ok := f.activeReservations[peerIDKey]; !ok {
113✔
5108
                f.activeReservations[peerIDKey] = make(pendingChannels)
53✔
5109
        }
53✔
5110

5111
        resCtx := &reservationWithCtx{
60✔
5112
                chanAmt:           capacity,
60✔
5113
                forwardingPolicy:  *forwardingPolicy,
60✔
5114
                remoteCsvDelay:    remoteCsvDelay,
60✔
5115
                remoteMinHtlc:     minHtlcIn,
60✔
5116
                remoteMaxValue:    maxValue,
60✔
5117
                remoteMaxHtlcs:    maxHtlcs,
60✔
5118
                remoteChanReserve: chanReserve,
60✔
5119
                maxLocalCsv:       maxCSV,
60✔
5120
                channelType:       chanType,
60✔
5121
                reservation:       reservation,
60✔
5122
                peer:              msg.Peer,
60✔
5123
                updates:           msg.Updates,
60✔
5124
                err:               msg.Err,
60✔
5125
        }
60✔
5126
        f.activeReservations[peerIDKey][chanID] = resCtx
60✔
5127
        f.resMtx.Unlock()
60✔
5128

60✔
5129
        // Update the timestamp once the InitFundingMsg has been handled.
60✔
5130
        defer resCtx.updateTimestamp()
60✔
5131

60✔
5132
        // Check the sanity of the selected channel constraints.
60✔
5133
        bounds := &channeldb.ChannelStateBounds{
60✔
5134
                ChanReserve:      chanReserve,
60✔
5135
                MaxPendingAmount: maxValue,
60✔
5136
                MinHTLC:          minHtlcIn,
60✔
5137
                MaxAcceptedHtlcs: maxHtlcs,
60✔
5138
        }
60✔
5139
        commitParams := &channeldb.CommitmentParams{
60✔
5140
                DustLimit: ourDustLimit,
60✔
5141
                CsvDelay:  remoteCsvDelay,
60✔
5142
        }
60✔
5143
        err = lnwallet.VerifyConstraints(
60✔
5144
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
60✔
5145
        )
60✔
5146
        if err != nil {
62✔
5147
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
2✔
5148
                if reserveErr != nil {
2✔
5149
                        log.Errorf("unable to cancel reservation: %v",
×
5150
                                reserveErr)
×
5151
                }
×
5152

5153
                msg.Err <- err
2✔
5154
                return
2✔
5155
        }
5156

5157
        // When opening a script enforced channel lease, include the required
5158
        // expiry TLV record in our proposal.
5159
        var leaseExpiry *lnwire.LeaseExpiry
58✔
5160
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
61✔
5161
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5162
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5163
        }
3✔
5164

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

58✔
5168
        reservation.SetState(lnwallet.SentOpenChannel)
58✔
5169

58✔
5170
        fundingOpen := lnwire.OpenChannel{
58✔
5171
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
58✔
5172
                PendingChannelID:      chanID,
58✔
5173
                FundingAmount:         capacity,
58✔
5174
                PushAmount:            msg.PushAmt,
58✔
5175
                DustLimit:             ourDustLimit,
58✔
5176
                MaxValueInFlight:      maxValue,
58✔
5177
                ChannelReserve:        chanReserve,
58✔
5178
                HtlcMinimum:           minHtlcIn,
58✔
5179
                FeePerKiloWeight:      uint32(commitFeePerKw),
58✔
5180
                CsvDelay:              remoteCsvDelay,
58✔
5181
                MaxAcceptedHTLCs:      maxHtlcs,
58✔
5182
                FundingKey:            ourContribution.MultiSigKey.PubKey,
58✔
5183
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
58✔
5184
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
58✔
5185
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
58✔
5186
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
58✔
5187
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
58✔
5188
                ChannelFlags:          channelFlags,
58✔
5189
                UpfrontShutdownScript: shutdown,
58✔
5190
                ChannelType:           chanType,
58✔
5191
                LeaseExpiry:           leaseExpiry,
58✔
5192
        }
58✔
5193

58✔
5194
        if commitType.IsTaproot() {
63✔
5195
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
5196
                        ourContribution.LocalNonce.PubNonce,
5✔
5197
                )
5✔
5198
        }
5✔
5199

5200
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
58✔
5201
                e := fmt.Errorf("unable to send funding request message: %w",
×
5202
                        err)
×
5203
                log.Errorf(e.Error())
×
5204

×
5205
                // Since we were unable to send the initial message to the peer
×
5206
                // and start the funding flow, we'll cancel this reservation.
×
5207
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5208
                if err != nil {
×
5209
                        log.Errorf("unable to cancel reservation: %v", err)
×
5210
                }
×
5211

5212
                msg.Err <- e
×
5213
                return
×
5214
        }
5215
}
5216

5217
// handleWarningMsg processes the warning which was received from remote peer.
5218
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
44✔
5219
        log.Warnf("received warning message from peer %x: %v",
44✔
5220
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
44✔
5221
}
44✔
5222

5223
// handleErrorMsg processes the error which was received from remote peer,
5224
// depending on the type of error we should do different clean up steps and
5225
// inform the user about it.
5226
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
3✔
5227
        chanID := msg.ChanID
3✔
5228
        peerKey := peer.IdentityKey()
3✔
5229

3✔
5230
        // First, we'll attempt to retrieve and cancel the funding workflow
3✔
5231
        // that this error was tied to. If we're unable to do so, then we'll
3✔
5232
        // exit early as this was an unwarranted error.
3✔
5233
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
3✔
5234
        if err != nil {
3✔
5235
                log.Warnf("Received error for non-existent funding "+
×
5236
                        "flow: %v (%v)", err, msg.Error())
×
5237
                return
×
5238
        }
×
5239

5240
        // If we did indeed find the funding workflow, then we'll return the
5241
        // error back to the caller (if any), and cancel the workflow itself.
5242
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5243
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5244
        )
3✔
5245
        log.Errorf(fundingErr.Error())
3✔
5246

3✔
5247
        // If this was a PSBT funding flow, the remote likely timed out because
3✔
5248
        // we waited too long. Return a nice error message to the user in that
3✔
5249
        // case so the user knows what's the problem.
3✔
5250
        if resCtx.reservation.IsPsbt() {
6✔
5251
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
3✔
5252
                        fundingErr)
3✔
5253
        }
3✔
5254

5255
        resCtx.err <- fundingErr
3✔
5256
}
5257

5258
// pruneZombieReservations loops through all pending reservations and fails the
5259
// funding flow for any reservations that have not been updated since the
5260
// ReservationTimeout and are not locked waiting for the funding transaction.
5261
func (f *Manager) pruneZombieReservations() {
6✔
5262
        zombieReservations := make(pendingChannels)
6✔
5263

6✔
5264
        f.resMtx.RLock()
6✔
5265
        for _, pendingReservations := range f.activeReservations {
12✔
5266
                for pendingChanID, resCtx := range pendingReservations {
12✔
5267
                        if resCtx.isLocked() {
6✔
5268
                                continue
×
5269
                        }
5270

5271
                        // We don't want to expire PSBT funding reservations.
5272
                        // These reservations are always initiated by us and the
5273
                        // remote peer is likely going to cancel them after some
5274
                        // idle time anyway. So no need for us to also prune
5275
                        // them.
5276
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
6✔
5277
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
6✔
5278
                        if !resCtx.reservation.IsPsbt() && isExpired {
12✔
5279
                                zombieReservations[pendingChanID] = resCtx
6✔
5280
                        }
6✔
5281
                }
5282
        }
5283
        f.resMtx.RUnlock()
6✔
5284

6✔
5285
        for pendingChanID, resCtx := range zombieReservations {
12✔
5286
                err := fmt.Errorf("reservation timed out waiting for peer "+
6✔
5287
                        "(peer_id:%x, chan_id:%x)",
6✔
5288
                        resCtx.peer.IdentityKey().SerializeCompressed(),
6✔
5289
                        pendingChanID[:])
6✔
5290
                log.Warnf(err.Error())
6✔
5291

6✔
5292
                chanID := lnwire.NewChanIDFromOutPoint(
6✔
5293
                        *resCtx.reservation.FundingOutpoint(),
6✔
5294
                )
6✔
5295

6✔
5296
                // Create channel identifier and set the channel ID.
6✔
5297
                cid := newChanIdentifier(pendingChanID)
6✔
5298
                cid.setChanID(chanID)
6✔
5299

6✔
5300
                f.failFundingFlow(resCtx.peer, cid, err)
6✔
5301
        }
6✔
5302
}
5303

5304
// cancelReservationCtx does all needed work in order to securely cancel the
5305
// reservation.
5306
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5307
        pendingChanID PendingChanID,
5308
        byRemote bool) (*reservationWithCtx, error) {
27✔
5309

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

27✔
5313
        peerIDKey := newSerializedKey(peerKey)
27✔
5314
        f.resMtx.Lock()
27✔
5315
        defer f.resMtx.Unlock()
27✔
5316

27✔
5317
        nodeReservations, ok := f.activeReservations[peerIDKey]
27✔
5318
        if !ok {
38✔
5319
                // No reservations for this node.
11✔
5320
                return nil, fmt.Errorf("no active reservations for peer(%x)",
11✔
5321
                        peerIDKey[:])
11✔
5322
        }
11✔
5323

5324
        ctx, ok := nodeReservations[pendingChanID]
19✔
5325
        if !ok {
21✔
5326
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
2✔
5327
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5328
        }
2✔
5329

5330
        // If the reservation was a PSBT funding flow and it was canceled by the
5331
        // remote peer, then we need to thread through a different error message
5332
        // to the subroutine that's waiting for the user input so it can return
5333
        // a nice error message to the user.
5334
        if ctx.reservation.IsPsbt() && byRemote {
20✔
5335
                ctx.reservation.RemoteCanceled()
3✔
5336
        }
3✔
5337

5338
        if err := ctx.reservation.Cancel(); err != nil {
17✔
5339
                return nil, fmt.Errorf("unable to cancel reservation: %w", err)
×
5340
        }
×
5341

5342
        delete(nodeReservations, pendingChanID)
17✔
5343

17✔
5344
        // If this was the last active reservation for this peer, delete the
17✔
5345
        // peer's entry altogether.
17✔
5346
        if len(nodeReservations) == 0 {
34✔
5347
                delete(f.activeReservations, peerIDKey)
17✔
5348
        }
17✔
5349
        return ctx, nil
17✔
5350
}
5351

5352
// deleteReservationCtx deletes the reservation uniquely identified by the
5353
// target public key of the peer, and the specified pending channel ID.
5354
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5355
        pendingChanID PendingChanID) {
59✔
5356

59✔
5357
        peerIDKey := newSerializedKey(peerKey)
59✔
5358
        f.resMtx.Lock()
59✔
5359
        defer f.resMtx.Unlock()
59✔
5360

59✔
5361
        nodeReservations, ok := f.activeReservations[peerIDKey]
59✔
5362
        if !ok {
59✔
5363
                // No reservations for this node.
×
5364
                return
×
5365
        }
×
5366
        delete(nodeReservations, pendingChanID)
59✔
5367

59✔
5368
        // If this was the last active reservation for this peer, delete the
59✔
5369
        // peer's entry altogether.
59✔
5370
        if len(nodeReservations) == 0 {
111✔
5371
                delete(f.activeReservations, peerIDKey)
52✔
5372
        }
52✔
5373
}
5374

5375
// getReservationCtx returns the reservation context for a particular pending
5376
// channel ID for a target peer.
5377
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5378
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
94✔
5379

94✔
5380
        peerIDKey := newSerializedKey(peerKey)
94✔
5381
        f.resMtx.RLock()
94✔
5382
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
94✔
5383
        f.resMtx.RUnlock()
94✔
5384

94✔
5385
        if !ok {
97✔
5386
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
3✔
5387
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5388
        }
3✔
5389

5390
        return resCtx, nil
94✔
5391
}
5392

5393
// IsPendingChannel returns a boolean indicating whether the channel identified
5394
// by the pendingChanID and given peer is pending, meaning it is in the process
5395
// of being funded. After the funding transaction has been confirmed, the
5396
// channel will receive a new, permanent channel ID, and will no longer be
5397
// considered pending.
5398
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5399
        peer lnpeer.Peer) bool {
3✔
5400

3✔
5401
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5402
        f.resMtx.RLock()
3✔
5403
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5404
        f.resMtx.RUnlock()
3✔
5405

3✔
5406
        return ok
3✔
5407
}
3✔
5408

5409
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
388✔
5410
        var tmp btcec.JacobianPoint
388✔
5411
        pub.AsJacobian(&tmp)
388✔
5412
        tmp.ToAffine()
388✔
5413
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
388✔
5414
}
388✔
5415

5416
// defaultForwardingPolicy returns the default forwarding policy based on the
5417
// default routing policy and our local channel constraints.
5418
func (f *Manager) defaultForwardingPolicy(
5419
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
107✔
5420

107✔
5421
        return &models.ForwardingPolicy{
107✔
5422
                MinHTLCOut:    bounds.MinHTLC,
107✔
5423
                MaxHTLC:       bounds.MaxPendingAmount,
107✔
5424
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
107✔
5425
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
107✔
5426
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
107✔
5427
        }
107✔
5428
}
107✔
5429

5430
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5431
// chanPoint in the channelOpeningStateBucket.
5432
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5433
        forwardingPolicy *models.ForwardingPolicy) error {
72✔
5434

72✔
5435
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
72✔
5436
                chanID, forwardingPolicy,
72✔
5437
        )
72✔
5438
}
72✔
5439

5440
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5441
// channel id from the database which will be applied during the channel
5442
// announcement phase.
5443
func (f *Manager) getInitialForwardingPolicy(
5444
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
97✔
5445

97✔
5446
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
97✔
5447
}
97✔
5448

5449
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5450
// the database.
5451
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
27✔
5452
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
27✔
5453
}
27✔
5454

5455
// saveChannelOpeningState saves the channelOpeningState for the provided
5456
// chanPoint to the channelOpeningStateBucket.
5457
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5458
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
95✔
5459

95✔
5460
        var outpointBytes bytes.Buffer
95✔
5461
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
95✔
5462
                return err
×
5463
        }
×
5464

5465
        // Save state and the uint64 representation of the shortChanID
5466
        // for later use.
5467
        scratch := make([]byte, 10)
95✔
5468
        byteOrder.PutUint16(scratch[:2], uint16(state))
95✔
5469
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
95✔
5470

95✔
5471
        return f.cfg.ChannelDB.SaveChannelOpeningState(
95✔
5472
                outpointBytes.Bytes(), scratch,
95✔
5473
        )
95✔
5474
}
5475

5476
// getChannelOpeningState fetches the channelOpeningState for the provided
5477
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5478
// is not found.
5479
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5480
        channelOpeningState, *lnwire.ShortChannelID, error) {
257✔
5481

257✔
5482
        var outpointBytes bytes.Buffer
257✔
5483
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
257✔
5484
                return 0, nil, err
×
5485
        }
×
5486

5487
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
257✔
5488
                outpointBytes.Bytes(),
257✔
5489
        )
257✔
5490
        if err != nil {
309✔
5491
                return 0, nil, err
52✔
5492
        }
52✔
5493

5494
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
208✔
5495
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
208✔
5496
        return state, &shortChanID, nil
208✔
5497
}
5498

5499
// deleteChannelOpeningState removes any state for chanPoint from the database.
5500
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
27✔
5501
        var outpointBytes bytes.Buffer
27✔
5502
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
27✔
5503
                return err
×
5504
        }
×
5505

5506
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
27✔
5507
                outpointBytes.Bytes(),
27✔
5508
        )
27✔
5509
}
5510

5511
// selectShutdownScript selects the shutdown script we should send to the peer.
5512
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5513
// script.
5514
func (f *Manager) selectShutdownScript(taprootOK bool,
5515
) (lnwire.DeliveryAddress, error) {
×
5516

×
5517
        addrType := lnwallet.WitnessPubKey
×
5518
        if taprootOK {
×
5519
                addrType = lnwallet.TaprootPubkey
×
5520
        }
×
5521

5522
        addr, err := f.cfg.Wallet.NewAddress(
×
5523
                addrType, false, lnwallet.DefaultAccountName,
×
5524
        )
×
5525
        if err != nil {
×
5526
                return nil, err
×
5527
        }
×
5528

5529
        return txscript.PayToAddrScript(addr)
×
5530
}
5531

5532
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5533
// and then returns the online peer.
5534
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5535
        error) {
108✔
5536

108✔
5537
        peerChan := make(chan lnpeer.Peer, 1)
108✔
5538

108✔
5539
        var peerKey [33]byte
108✔
5540
        copy(peerKey[:], peerPubkey.SerializeCompressed())
108✔
5541

108✔
5542
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
108✔
5543

108✔
5544
        var peer lnpeer.Peer
108✔
5545
        select {
108✔
5546
        case peer = <-peerChan:
107✔
5547
        case <-f.quit:
1✔
5548
                return peer, ErrFundingManagerShuttingDown
1✔
5549
        }
5550
        return peer, nil
107✔
5551
}
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