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

lightningnetwork / lnd / 18197857992

02 Oct 2025 03:32PM UTC coverage: 66.622% (-0.02%) from 66.646%
18197857992

Pull #10267

github

web-flow
Merge 0d9bfccfe into 1c2ff4a7e
Pull Request #10267: [g175] multi: small G175 preparations

24 of 141 new or added lines in 12 files covered. (17.02%)

64 existing lines in 20 files now uncovered.

137216 of 205963 relevant lines covered (66.62%)

21302.01 hits per line

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

73.57
/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 {
392✔
326
        var s serializedPubKey
392✔
327
        copy(s[:], pubKey.SerializeCompressed())
392✔
328
        return s
392✔
329
}
392✔
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

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

591
        // cfg is a copy of the configuration struct that the FundingManager
592
        // was initialized with.
593
        cfg *Config
594

595
        // chanIDKey is a cryptographically random key that's used to generate
596
        // temporary channel ID's.
597
        chanIDKey [32]byte
598

599
        // chanIDNonce is a nonce that's incremented for each new funding
600
        // reservation created.
601
        chanIDNonce atomic.Uint64
602

603
        // nonceMtx is a mutex that guards the pendingMusigNonces.
604
        nonceMtx sync.RWMutex
605

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

617
        // activeReservations is a map which houses the state of all pending
618
        // funding workflows.
619
        activeReservations map[serializedPubKey]pendingChannels
620

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

628
        // resMtx guards both of the maps above to ensure that all access is
629
        // goroutine safe.
630
        resMtx sync.RWMutex
631

632
        // fundingMsgs is a channel that relays fundingMsg structs from
633
        // external sub-systems using the ProcessFundingMsg call.
634
        fundingMsgs chan *fundingMsg
635

636
        // fundingRequests is a channel used to receive channel initiation
637
        // requests from a local subsystem within the daemon.
638
        fundingRequests chan *InitFundingMsg
639

640
        localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
641

642
        handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
643

644
        quit chan struct{}
645
        wg   sync.WaitGroup
646
}
647

648
// channelOpeningState represents the different states a channel can be in
649
// between the funding transaction has been confirmed and the channel is
650
// announced to the network and ready to be used.
651
type channelOpeningState uint8
652

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

659
        // channelReadySent is the opening state of a channel if the
660
        // channelReady message has successfully been sent to the other peer,
661
        // but we still haven't announced the channel to the network.
662
        channelReadySent
663

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

671
func (c channelOpeningState) String() string {
3✔
672
        switch c {
3✔
673
        case markedOpen:
3✔
674
                return "markedOpen"
3✔
675
        case channelReadySent:
3✔
676
                return "channelReadySent"
3✔
677
        case addedToGraph:
3✔
678
                return "addedToGraph"
3✔
679
        default:
×
680
                return "unknown"
×
681
        }
682
}
683

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

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

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

738
        for _, channel := range allChannels {
124✔
739
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
12✔
740

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

4✔
750
                        f.localDiscoverySignals.Store(
4✔
751
                                chanID, make(chan struct{}),
4✔
752
                        )
4✔
753

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

4✔
762
                                f.rebroadcastFundingTx(channel)
4✔
763
                        }
4✔
764
                } else if channel.ChanType.IsSingleFunder() &&
11✔
765
                        channel.ChanType.HasFundingTx() &&
11✔
766
                        channel.IsZeroConf() && channel.IsInitiator &&
11✔
767
                        !channel.ZeroConfConfirmed() {
13✔
768

2✔
769
                        // Rebroadcast the funding transaction for unconfirmed
2✔
770
                        // zero-conf channels if we have the funding tx and are
2✔
771
                        // also the initiator.
2✔
772
                        f.rebroadcastFundingTx(channel)
2✔
773
                }
2✔
774

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

783
        f.wg.Add(1) // TODO(roasbeef): tune
112✔
784
        go f.reservationCoordinator()
112✔
785

112✔
786
        return nil
112✔
787
}
788

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

108✔
796
                close(f.quit)
108✔
797
                f.wg.Wait()
108✔
798
        })
108✔
799

800
        return nil
109✔
801
}
802

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

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

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

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

833
// PendingChanID is a type that represents a pending channel ID. This might be
834
// selected by the caller, but if not, will be automatically selected.
835
type PendingChanID = [32]byte
836

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

60✔
843
        var nonceBytes [8]byte
60✔
844
        binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
60✔
845

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

60✔
856
        return nextChanID
60✔
857
}
60✔
858

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

3✔
865
        f.resMtx.Lock()
3✔
866
        defer f.resMtx.Unlock()
3✔
867

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

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

886
                resCtx.err <- fmt.Errorf("peer disconnected")
×
887
                delete(nodeReservations, pendingID)
×
888
        }
889

890
        // Finally, we'll delete the node itself from the set of reservations.
891
        delete(f.activeReservations, nodePub)
×
892
}
893

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

905
        // chanID is the channel ID created by the funder once the
906
        // `accept_channel` message is received. For fundee, it's received from
907
        // the `funding_created` message.
908
        chanID lnwire.ChannelID
909

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

918
// newChanIdentifier creates a new chanIdentifier.
919
func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
151✔
920
        return &chanIdentifier{
151✔
921
                tempChanID: tempChanID,
151✔
922
        }
151✔
923
}
151✔
924

925
// setChanID updates the `chanIdentifier` with the active channel ID.
926
func (c *chanIdentifier) setChanID(chanID lnwire.ChannelID) {
94✔
927
        c.chanID = chanID
94✔
928
        c.chanIDSet = true
94✔
929
}
94✔
930

931
// hasChanID returns true if the active channel ID has been set.
932
func (c *chanIdentifier) hasChanID() bool {
24✔
933
        return c.chanIDSet
24✔
934
}
24✔
935

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

24✔
946
        log.Debugf("Failing funding flow for pending_id=%v: %v",
24✔
947
                cid.tempChanID, fundingErr)
24✔
948

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

962
        ctx, err := f.cancelReservationCtx(
24✔
963
                peer.IdentityKey(), cid.tempChanID, false,
24✔
964
        )
24✔
965
        if err != nil {
36✔
966
                log.Errorf("unable to cancel reservation: %v", err)
12✔
967
        }
12✔
968

969
        // In case the case where the reservation existed, send the funding
970
        // error on the error channel.
971
        if ctx != nil {
39✔
972
                ctx.err <- fundingErr
15✔
973
        }
15✔
974

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

988
        // For all other error types we just send a generic error.
989
        default:
15✔
990
                msg = lnwire.ErrorData("funding failed due to internal error")
15✔
991
        }
992

993
        errMsg := &lnwire.Error{
24✔
994
                ChanID: cid.tempChanID,
24✔
995
                Data:   msg,
24✔
996
        }
24✔
997

24✔
998
        log.Debugf("Sending funding error to peer (%x): %v",
24✔
999
                peer.IdentityKey().SerializeCompressed(),
24✔
1000
                lnutils.SpewLogClosure(errMsg))
24✔
1001

24✔
1002
        if err := peer.SendMessage(false, errMsg); err != nil {
24✔
UNCOV
1003
                log.Errorf("unable to send error message to peer %v", err)
×
UNCOV
1004
        }
×
1005
}
1006

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

×
1012
        msg := fundingErr.Error()
×
1013

×
1014
        errMsg := &lnwire.Warning{
×
1015
                ChanID: cid.tempChanID,
×
1016
                Data:   lnwire.WarningData(msg),
×
1017
        }
×
1018

×
1019
        log.Debugf("Sending funding warning to peer (%x): %v",
×
1020
                peer.IdentityKey().SerializeCompressed(),
×
1021
                lnutils.SpewLogClosure(errMsg),
×
1022
        )
×
1023

×
1024
        if err := peer.SendMessage(false, errMsg); err != nil {
×
1025
                log.Errorf("unable to send error message to peer %v", err)
×
1026
        }
×
1027
}
1028

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

112✔
1036
        zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
112✔
1037
        defer zombieSweepTicker.Stop()
112✔
1038

112✔
1039
        for {
496✔
1040
                select {
384✔
1041
                case fmsg := <-f.fundingMsgs:
218✔
1042
                        switch msg := fmsg.msg.(type) {
218✔
1043
                        case *lnwire.OpenChannel:
57✔
1044
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
57✔
1045

1046
                        case *lnwire.AcceptChannel:
36✔
1047
                                f.funderProcessAcceptChannel(fmsg.peer, msg)
36✔
1048

1049
                        case *lnwire.FundingCreated:
31✔
1050
                                f.fundeeProcessFundingCreated(fmsg.peer, msg)
31✔
1051

1052
                        case *lnwire.FundingSigned:
31✔
1053
                                f.funderProcessFundingSigned(fmsg.peer, msg)
31✔
1054

1055
                        case *lnwire.ChannelReady:
31✔
1056
                                f.wg.Add(1)
31✔
1057
                                go f.handleChannelReady(fmsg.peer, msg)
31✔
1058

1059
                        case *lnwire.Warning:
44✔
1060
                                f.handleWarningMsg(fmsg.peer, msg)
44✔
1061

1062
                        case *lnwire.Error:
3✔
1063
                                f.handleErrorMsg(fmsg.peer, msg)
3✔
1064
                        }
1065
                case req := <-f.fundingRequests:
60✔
1066
                        f.handleInitFundingMsg(req)
60✔
1067

1068
                case <-zombieSweepTicker.C:
3✔
1069
                        f.pruneZombieReservations()
3✔
1070

1071
                case <-f.quit:
108✔
1072
                        return
108✔
1073
                }
1074
        }
1075
}
1076

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

68✔
1089
        defer f.wg.Done()
68✔
1090

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

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

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

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

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

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

126✔
1172
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
126✔
1173
        log.Debugf("Channel(%v) with ShortChanID %v has opening state %v",
126✔
1174
                chanID, shortChanID, channelState)
126✔
1175

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

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

1199
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
37✔
1200
                        "sent ChannelReady", chanID, shortChanID)
37✔
1201

37✔
1202
                return nil
37✔
1203

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

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

1227
                        return nil
27✔
1228
                }
1229

1230
                return f.handleChannelReadyReceived(
27✔
1231
                        channel, shortChanID, pendingChanID, updateChan,
27✔
1232
                )
27✔
1233

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

1247
                        // Update the local shortChanID variable such that
1248
                        // annAfterSixConfs uses the confirmed SCID.
1249
                        confirmedScid := channel.ZeroConfRealScid()
7✔
1250
                        shortChanID = &confirmedScid
7✔
1251
                }
1252

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

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

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

1280
                log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
1281
                        "announced", chanID, shortChanID)
27✔
1282

27✔
1283
                return nil
27✔
1284
        }
1285

1286
        return fmt.Errorf("undefined channelState: %v", channelState)
×
1287
}
1288

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

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

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

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

1326
                // Inform the ChannelNotifier that the channel has transitioned
1327
                // from pending open to open.
1328
                f.cfg.NotifyOpenChannelEvent(
7✔
1329
                        channel.FundingOutpoint, channel.IdentityPub,
7✔
1330
                )
7✔
1331

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

1340
                return nil
7✔
1341
        }
1342

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

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

2✔
1359
                if channel.NumConfsRequired > maturity {
2✔
1360
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1361
                }
×
1362

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

×
1370
                        return err
×
1371
                }
×
1372

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

×
1382
                        return err
×
1383
                }
×
1384

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

1394
                case <-f.quit:
×
1395
                        return ErrFundingManagerShuttingDown
×
1396
                }
1397
        }
1398

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

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

1411
        return nil
33✔
1412
}
1413

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

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

57✔
1435
        // Check number of pending channels to be smaller than maximum allowed
57✔
1436
        // number and send ErrorGeneric to remote peer if condition is
57✔
1437
        // violated.
57✔
1438
        peerPubKey := peer.IdentityKey()
57✔
1439
        peerIDKey := newSerializedKey(peerPubKey)
57✔
1440

57✔
1441
        amt := msg.FundingAmount
57✔
1442

57✔
1443
        // We get all pending channels for this peer. This is the list of the
57✔
1444
        // active reservations and the channels pending open in the database.
57✔
1445
        f.resMtx.RLock()
57✔
1446
        reservations := f.activeReservations[peerIDKey]
57✔
1447

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

57✔
1459
        // Create the channel identifier.
57✔
1460
        cid := newChanIdentifier(msg.PendingChannelID)
57✔
1461

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

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

1482
        // TODO(roasbeef): modify to only accept a _single_ pending channel per
1483
        // block unless white listed
1484
        if numPending >= f.cfg.MaxPendingChannels {
64✔
1485
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
7✔
1486

7✔
1487
                return
7✔
1488
        }
7✔
1489

1490
        // Ensure that the pendingChansLimit is respected.
1491
        pendingChans, err := f.cfg.ChannelDB.FetchPendingChannels()
53✔
1492
        if err != nil {
53✔
1493
                f.failFundingFlow(peer, cid, err)
×
1494
                return
×
1495
        }
×
1496

1497
        if len(pendingChans) > pendingChansLimit {
53✔
1498
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1499
                return
×
1500
        }
×
1501

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

1515
        // Ensure that the remote party respects our maximum channel size.
1516
        if amt > f.cfg.MaxChanSize {
58✔
1517
                f.failFundingFlow(
5✔
1518
                        peer, cid,
5✔
1519
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
5✔
1520
                )
5✔
1521
                return
5✔
1522
        }
5✔
1523

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

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

1541
        // Send the OpenChannel request to the ChannelAcceptor to determine
1542
        // whether this node will accept the channel.
1543
        chanReq := &chanacceptor.ChannelAcceptRequest{
50✔
1544
                Node:        peer.IdentityKey(),
50✔
1545
                OpenChanMsg: msg,
50✔
1546
        }
50✔
1547

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

1556
        log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
50✔
1557
                "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
50✔
1558
                msg.CsvDelay, msg.PendingChannelID,
50✔
1559
                peer.IdentityKey().SerializeCompressed())
50✔
1560

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

1582
        var scidFeatureVal bool
50✔
1583
        if hasFeatures(
50✔
1584
                peer.LocalFeatures(), peer.RemoteFeatures(),
50✔
1585
                lnwire.ScidAliasOptional,
50✔
1586
        ) {
56✔
1587

6✔
1588
                scidFeatureVal = true
6✔
1589
        }
6✔
1590

1591
        var (
50✔
1592
                zeroConf bool
50✔
1593
                scid     bool
50✔
1594
        )
50✔
1595

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

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

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

1634
                        // Set zeroConf to true to enable the zero-conf flow.
1635
                        zeroConf = true
×
1636
                }
1637
        }
1638

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

×
1650
                return
×
1651

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

×
1660
                return
×
1661
        }
1662

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

×
1677
                return
×
1678
        }
×
1679

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

50✔
1699
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
50✔
1700
        if err != nil {
50✔
1701
                log.Errorf("Unable to initialize reservation: %v", err)
×
1702
                f.failFundingFlow(peer, cid, err)
×
1703
                return
×
1704
        }
×
1705

1706
        log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
50✔
1707
                "cannedShim=%v", reservation.IsZeroConf(),
50✔
1708
                reservation.IsPsbt(), reservation.IsCannedShim())
50✔
1709

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

1720
                reservation.AddAlias(aliasScid)
5✔
1721
        }
1722

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

1734
        // We'll ignore the min_depth calculated above if this is a zero-conf
1735
        // channel.
1736
        if zeroConf {
55✔
1737
                numConfsReq = 0
5✔
1738
        }
5✔
1739

1740
        reservation.SetNumConfsRequired(numConfsReq)
50✔
1741

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

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

50✔
1780
        // If a script enforced channel lease is being proposed, we'll need to
50✔
1781
        // validate its custom TLV records.
50✔
1782
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
53✔
1783
                if msg.LeaseExpiry == nil {
3✔
1784
                        err := errors.New("missing lease expiry")
×
1785
                        f.failFundingFlow(peer, cid, err)
×
1786
                        return
×
1787
                }
×
1788

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

×
1797
                                err := errors.New("lease expiry mismatch")
×
1798
                                f.failFundingFlow(peer, cid, err)
×
1799
                                return
×
1800
                        }
×
1801
                }
1802
        }
1803

1804
        log.Infof("Requiring %v confirmations for pendingChan(%x): "+
50✔
1805
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
50✔
1806
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
50✔
1807
                commitType, msg.UpfrontShutdownScript)
50✔
1808

50✔
1809
        // Generate our required constraints for the remote party, using the
50✔
1810
        // values provided by the channel acceptor if they are non-zero.
50✔
1811
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
50✔
1812
        if acceptorResp.CSVDelay != 0 {
50✔
1813
                remoteCsvDelay = acceptorResp.CSVDelay
×
1814
        }
×
1815

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

1828
        chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
50✔
1829
        if acceptorResp.Reserve != 0 {
50✔
1830
                chanReserve = acceptorResp.Reserve
×
1831
        }
×
1832

1833
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
50✔
1834
        if acceptorResp.InFlightTotal != 0 {
50✔
1835
                remoteMaxValue = acceptorResp.InFlightTotal
×
1836
        }
×
1837

1838
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
50✔
1839
        if acceptorResp.HtlcLimit != 0 {
50✔
1840
                maxHtlcs = acceptorResp.HtlcLimit
×
1841
        }
×
1842

1843
        // Default to our default minimum hltc value, replacing it with the
1844
        // channel acceptor's value if it is set.
1845
        minHtlc := f.cfg.DefaultMinHtlcIn
50✔
1846
        if acceptorResp.MinHtlcIn != 0 {
50✔
1847
                minHtlc = acceptorResp.MinHtlcIn
×
1848
        }
×
1849

1850
        // If we are handling a FundingOpen request then we need to specify the
1851
        // default channel fees since they are not provided by the responder
1852
        // interactively.
1853
        ourContribution := reservation.OurContribution()
50✔
1854
        forwardingPolicy := f.defaultForwardingPolicy(
50✔
1855
                ourContribution.ChannelStateBounds,
50✔
1856
        )
50✔
1857

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

50✔
1882
        // Update the timestamp once the fundingOpenMsg has been handled.
50✔
1883
        defer resCtx.updateTimestamp()
50✔
1884

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

50✔
1913
        // With our parameters set, we'll now process their contribution so we
50✔
1914
        // can move the funding workflow ahead.
50✔
1915
        remoteContribution := &lnwallet.ChannelContribution{
50✔
1916
                FundingAmount:        amt,
50✔
1917
                FirstCommitmentPoint: msg.FirstCommitmentPoint,
50✔
1918
                ChannelConfig:        &cfg,
50✔
1919
                UpfrontShutdown:      msg.UpfrontShutdownScript,
50✔
1920
        }
50✔
1921

50✔
1922
        if resCtx.reservation.IsTaproot() {
55✔
1923
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
1924
                if err != nil {
5✔
1925
                        log.Error(errNoLocalNonce)
×
1926

×
1927
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1928

×
1929
                        return
×
1930
                }
×
1931

1932
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
1933
                        PubNonce: localNonce,
5✔
1934
                }
5✔
1935
        }
1936

1937
        err = reservation.ProcessSingleContribution(remoteContribution)
50✔
1938
        if err != nil {
56✔
1939
                log.Errorf("unable to add contribution reservation: %v", err)
6✔
1940
                f.failFundingFlow(peer, cid, err)
6✔
1941
                return
6✔
1942
        }
6✔
1943

1944
        log.Infof("Sending fundingResp for pending_id(%x)",
44✔
1945
                msg.PendingChannelID)
44✔
1946
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
44✔
1947
        log.Debugf("Remote party accepted channel state space bounds: %v",
44✔
1948
                lnutils.SpewLogClosure(bounds))
44✔
1949
        params := remoteContribution.ChannelConfig.CommitmentParams
44✔
1950
        log.Debugf("Remote party accepted commitment rendering params: %v",
44✔
1951
                lnutils.SpewLogClosure(params))
44✔
1952

44✔
1953
        reservation.SetState(lnwallet.SentAcceptChannel)
44✔
1954

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

44✔
1977
        if commitType.IsTaproot() {
49✔
1978
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
1979
                        ourContribution.LocalNonce.PubNonce,
5✔
1980
                )
5✔
1981
        }
5✔
1982

1983
        if err := peer.SendMessage(true, &fundingAccept); err != nil {
44✔
1984
                log.Errorf("unable to send funding response to peer: %v", err)
×
1985
                f.failFundingFlow(peer, cid, err)
×
1986
                return
×
1987
        }
×
1988
}
1989

1990
// funderProcessAcceptChannel processes a response to the workflow initiation
1991
// sent by the remote peer. This message then queues a message with the funding
1992
// outpoint, and a commitment signature to the remote peer.
1993
//
1994
//nolint:funlen
1995
func (f *Manager) funderProcessAcceptChannel(peer lnpeer.Peer,
1996
        msg *lnwire.AcceptChannel) {
36✔
1997

36✔
1998
        pendingChanID := msg.PendingChannelID
36✔
1999
        peerKey := peer.IdentityKey()
36✔
2000
        var peerKeyBytes []byte
36✔
2001
        if peerKey != nil {
72✔
2002
                peerKeyBytes = peerKey.SerializeCompressed()
36✔
2003
        }
36✔
2004

2005
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
36✔
2006
        if err != nil {
36✔
2007
                log.Warnf("Can't find reservation (peerKey:%x, chan_id:%v)",
×
2008
                        peerKeyBytes, pendingChanID)
×
2009
                return
×
2010
        }
×
2011

2012
        // Update the timestamp once the fundingAcceptMsg has been handled.
2013
        defer resCtx.updateTimestamp()
36✔
2014

36✔
2015
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
36✔
2016
                return
×
2017
        }
×
2018

2019
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
36✔
2020
                pendingChanID[:])
36✔
2021

36✔
2022
        // Create the channel identifier.
36✔
2023
        cid := newChanIdentifier(msg.PendingChannelID)
36✔
2024

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

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

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

×
2072
                _, negotiatedCommitType, err := negotiateCommitmentType(
×
2073
                        msg.ChannelType, peer.LocalFeatures(),
×
2074
                        peer.RemoteFeatures(),
×
2075
                )
×
2076
                if err != nil {
×
2077
                        err := errors.New("received unexpected channel type")
×
2078
                        f.failFundingFlow(peer, cid, err)
×
2079
                        return
×
2080
                }
×
2081

2082
                if implicitCommitType != negotiatedCommitType {
×
2083
                        err := errors.New("negotiated unexpected channel type")
×
2084
                        f.failFundingFlow(peer, cid, err)
×
2085
                        return
×
2086
                }
×
2087
        }
2088

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

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

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

×
2118
                minDepth = 1
×
2119
        }
×
2120

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

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

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

33✔
2182
        if resCtx.reservation.IsTaproot() {
38✔
2183
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
5✔
2184
                if err != nil {
5✔
2185
                        log.Error(errNoLocalNonce)
×
2186

×
2187
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2188

×
2189
                        return
×
2190
                }
×
2191

2192
                remoteContribution.LocalNonce = &musig2.Nonces{
5✔
2193
                        PubNonce: localNonce,
5✔
2194
                }
5✔
2195
        }
2196

2197
        err = resCtx.reservation.ProcessContribution(remoteContribution)
33✔
2198

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

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

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

3✔
2260
                        f.waitForPsbt(psbtIntent, resCtx, cid)
3✔
2261
                }()
3✔
2262

2263
                // With the new goroutine spawned, we can now exit to unblock
2264
                // the main event loop.
2265
                return
3✔
2266
        }
2267

2268
        // In a normal, non-PSBT funding flow, we can jump directly to the next
2269
        // step where we expect our contribution to be finalized.
2270
        f.continueFundingAccept(resCtx, cid)
33✔
2271
}
2272

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

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

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

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

2313
                // Nil error means the flow continues normally now.
2314
                case nil:
3✔
2315

2316
                // For any other error, we'll fail the funding flow.
2317
                default:
×
2318
                        failFlow("error waiting for PSBT flow", err)
×
2319
                        return
×
2320
                }
2321

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

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

2355
                // We are now ready to continue the funding flow.
2356
                f.continueFundingAccept(resCtx, cid)
3✔
2357

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

2369
// continueFundingAccept continues the channel funding flow once our
2370
// contribution is finalized, the channel output is known and the funding
2371
// transaction is signed.
2372
func (f *Manager) continueFundingAccept(resCtx *reservationWithCtx,
2373
        cid *chanIdentifier) {
33✔
2374

33✔
2375
        // Now that we have their contribution, we can extract, then send over
33✔
2376
        // both the funding out point and our signature for their version of
33✔
2377
        // the commitment transaction to the remote peer.
33✔
2378
        outPoint := resCtx.reservation.FundingOutpoint()
33✔
2379
        _, sig := resCtx.reservation.OurSignatures()
33✔
2380

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

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

33✔
2396
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
33✔
2397
                cid.tempChanID[:])
33✔
2398

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

2408
        // Once Brontide is aware of this channel, we need to set it in
2409
        // chanIdentifier so this channel will be removed from Brontide if the
2410
        // funding flow fails.
2411
        cid.setChanID(channelID)
33✔
2412

33✔
2413
        // Send the FundingCreated msg.
33✔
2414
        fundingCreated := &lnwire.FundingCreated{
33✔
2415
                PendingChannelID: cid.tempChanID,
33✔
2416
                FundingPoint:     *outPoint,
33✔
2417
        }
33✔
2418

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

×
2429
                        return
×
2430
                }
×
2431

2432
                fundingCreated.PartialSig = lnwire.MaybePartialSigWithNonce(
5✔
2433
                        partialSig.ToWireSig(),
5✔
2434
                )
5✔
2435
        } else {
31✔
2436
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
31✔
2437
                if err != nil {
31✔
2438
                        log.Errorf("Unable to parse signature: %v", err)
×
2439
                        f.failFundingFlow(resCtx.peer, cid, err)
×
2440
                        return
×
2441
                }
×
2442
        }
2443

2444
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
33✔
2445

33✔
2446
        if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
33✔
2447
                log.Errorf("Unable to send funding complete message: %v", err)
×
2448
                f.failFundingFlow(resCtx.peer, cid, err)
×
2449
                return
×
2450
        }
×
2451
}
2452

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

31✔
2463
        peerKey := peer.IdentityKey()
31✔
2464
        pendingChanID := msg.PendingChannelID
31✔
2465

31✔
2466
        resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
31✔
2467
        if err != nil {
31✔
2468
                log.Warnf("can't find reservation (peer_id:%v, chan_id:%x)",
×
2469
                        peerKey, pendingChanID[:])
×
2470
                return
×
2471
        }
×
2472

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

31✔
2481
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
31✔
2482
                return
×
2483
        }
×
2484

2485
        // Create the channel identifier without setting the active channel ID.
2486
        cid := newChanIdentifier(pendingChanID)
31✔
2487

31✔
2488
        // For taproot channels, the commit signature is actually the partial
31✔
2489
        // signature. Otherwise, we can convert the ECDSA commit signature into
31✔
2490
        // our internal input.Signature type.
31✔
2491
        var commitSig input.Signature
31✔
2492
        if resCtx.reservation.IsTaproot() {
36✔
2493
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
5✔
2494
                if err != nil {
5✔
2495
                        f.failFundingFlow(peer, cid, err)
×
2496

×
2497
                        return
×
2498
                }
×
2499

2500
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
5✔
2501
                        &partialSig,
5✔
2502
                )
5✔
2503
        } else {
29✔
2504
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2505
                if err != nil {
29✔
2506
                        log.Errorf("unable to parse signature: %v", err)
×
2507
                        f.failFundingFlow(peer, cid, err)
×
2508
                        return
×
2509
                }
×
2510
        }
2511

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

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

2549
        // Get forwarding policy before deleting the reservation context.
2550
        forwardingPolicy := resCtx.forwardingPolicy
31✔
2551

31✔
2552
        // The channel is marked IsPending in the database, and can be removed
31✔
2553
        // from the set of active reservations.
31✔
2554
        f.deleteReservationCtx(peerKey, cid.tempChanID)
31✔
2555

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

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

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

31✔
2590
        fundingSigned := &lnwire.FundingSigned{}
31✔
2591

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

×
2604
                        return
×
2605
                }
×
2606

2607
                fundingSigned.PartialSig = lnwire.MaybePartialSigWithNonce(
5✔
2608
                        partialSig.ToWireSig(),
5✔
2609
                )
5✔
2610
        } else {
29✔
2611
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
29✔
2612
                if err != nil {
29✔
2613
                        log.Errorf("unable to parse signature: %v", err)
×
2614
                        f.failFundingFlow(peer, cid, err)
×
2615
                        deleteFromDatabase()
×
2616

×
2617
                        return
×
2618
                }
×
2619
        }
2620

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

2629
        // Once Brontide is aware of this channel, we need to set it in
2630
        // chanIdentifier so this channel will be removed from Brontide if the
2631
        // funding flow fails.
2632
        cid.setChanID(channelID)
31✔
2633

31✔
2634
        fundingSigned.ChanID = cid.chanID
31✔
2635

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

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

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

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

2664
        // Create an entry in the local discovery map so we can ensure that we
2665
        // process the channel confirmation fully before we receive a
2666
        // channel_ready message.
2667
        f.localDiscoverySignals.Store(cid.chanID, make(chan struct{}))
31✔
2668

31✔
2669
        // Inform the ChannelNotifier that the channel has entered
31✔
2670
        // pending open state.
31✔
2671
        f.cfg.NotifyPendingOpenChannelEvent(
31✔
2672
                fundingOut, completeChan, completeChan.IdentityPub,
31✔
2673
        )
31✔
2674

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

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

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

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

31✔
2722
        // If the pending channel ID is not found, fail the funding flow.
31✔
2723
        if !ok {
31✔
2724
                // NOTE: we directly overwrite the pending channel ID here for
×
2725
                // this rare case since we don't have a valid pending channel
×
2726
                // ID.
×
2727
                cid.tempChanID = msg.ChanID
×
2728

×
2729
                err := fmt.Errorf("unable to find signed reservation for "+
×
2730
                        "chan_id=%x", msg.ChanID)
×
2731
                log.Warnf(err.Error())
×
2732
                f.failFundingFlow(peer, cid, err)
×
2733
                return
×
2734
        }
×
2735

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

2746
        if resCtx.reservation.State() != lnwallet.SentFundingCreated {
31✔
2747
                err := fmt.Errorf("unable to find reservation for chan_id=%x",
×
2748
                        msg.ChanID)
×
2749
                f.failFundingFlow(peer, cid, err)
×
2750

×
2751
                return
×
2752
        }
×
2753

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

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

2771
        // For taproot channels, the commit signature is actually the partial
2772
        // signature. Otherwise, we can convert the ECDSA commit signature into
2773
        // our internal input.Signature type.
2774
        var commitSig input.Signature
31✔
2775
        if resCtx.reservation.IsTaproot() {
36✔
2776
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
5✔
2777
                if err != nil {
5✔
2778
                        f.failFundingFlow(peer, cid, err)
×
2779

×
2780
                        return
×
2781
                }
×
2782

2783
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
5✔
2784
                        &partialSig,
5✔
2785
                )
5✔
2786
        } else {
29✔
2787
                commitSig, err = msg.CommitSig.ToSignature()
29✔
2788
                if err != nil {
29✔
2789
                        log.Errorf("unable to parse signature: %v", err)
×
2790
                        f.failFundingFlow(peer, cid, err)
×
2791
                        return
×
2792
                }
×
2793
        }
2794

2795
        completeChan, err := resCtx.reservation.CompleteReservation(
31✔
2796
                nil, commitSig,
31✔
2797
        )
31✔
2798
        if err != nil {
31✔
2799
                log.Errorf("Unable to complete reservation sign "+
×
2800
                        "complete: %v", err)
×
2801
                f.failFundingFlow(peer, cid, err)
×
2802
                return
×
2803
        }
×
2804

2805
        // The channel is now marked IsPending in the database, and we can
2806
        // delete it from our set of active reservations.
2807
        f.deleteReservationCtx(peerKey, pendingChanID)
31✔
2808

31✔
2809
        // Broadcast the finalized funding transaction to the network, but only
31✔
2810
        // if we actually have the funding transaction.
31✔
2811
        if completeChan.ChanType.HasFundingTx() {
61✔
2812
                fundingTx := completeChan.FundingTxn
30✔
2813
                var fundingTxBuf bytes.Buffer
30✔
2814
                if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
30✔
2815
                        log.Errorf("Unable to serialize funding "+
×
2816
                                "transaction %v: %v", fundingTx.TxHash(), err)
×
2817

×
2818
                        // Clear the buffer of any bytes that were written
×
2819
                        // before the serialization error to prevent logging an
×
2820
                        // incomplete transaction.
×
2821
                        fundingTxBuf.Reset()
×
2822
                }
×
2823

2824
                log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
30✔
2825
                        completeChan.FundingOutpoint, fundingTxBuf.Bytes())
30✔
2826

30✔
2827
                // Set a nil short channel ID at this stage because we do not
30✔
2828
                // know it until our funding tx confirms.
30✔
2829
                label := labels.MakeLabel(
30✔
2830
                        labels.LabelTypeChannelOpen, nil,
30✔
2831
                )
30✔
2832

30✔
2833
                err = f.cfg.PublishTransaction(fundingTx, label)
30✔
2834
                if err != nil {
30✔
2835
                        log.Errorf("Unable to broadcast funding tx %x for "+
×
2836
                                "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
×
2837
                                completeChan.FundingOutpoint, err)
×
2838

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

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

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

2873
        log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
31✔
2874
                "waiting for channel open on-chain", pendingChanID[:],
31✔
2875
                fundingPoint)
31✔
2876

31✔
2877
        // Send an update to the upstream client that the negotiation process
31✔
2878
        // is over.
31✔
2879
        upd := &lnrpc.OpenStatusUpdate{
31✔
2880
                Update: &lnrpc.OpenStatusUpdate_ChanPending{
31✔
2881
                        ChanPending: &lnrpc.PendingUpdate{
31✔
2882
                                Txid:        fundingPoint.Hash[:],
31✔
2883
                                OutputIndex: fundingPoint.Index,
31✔
2884
                        },
31✔
2885
                },
31✔
2886
                PendingChanId: pendingChanID[:],
31✔
2887
        }
31✔
2888

31✔
2889
        select {
31✔
2890
        case resCtx.updates <- upd:
31✔
2891
                // Inform the ChannelNotifier that the channel has entered
31✔
2892
                // pending open state.
31✔
2893
                f.cfg.NotifyPendingOpenChannelEvent(
31✔
2894
                        *fundingPoint, completeChan, completeChan.IdentityPub,
31✔
2895
                )
31✔
2896

2897
        case <-f.quit:
×
2898
                return
×
2899
        }
2900

2901
        // At this point we have broadcast the funding transaction and done all
2902
        // necessary processing.
2903
        f.wg.Add(1)
31✔
2904
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
31✔
2905
}
2906

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

2916
        // fundingTx is the funding transaction that created the channel.
2917
        fundingTx *wire.MsgTx
2918
}
2919

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

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

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

2952
        // Notify other subsystems about the funding timeout.
2953
        f.cfg.NotifyFundingTimeout(c.FundingOutpoint, c.IdentityPub)
5✔
2954

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

5✔
2958
        // When the peer comes online, we'll notify it that we are now
5✔
2959
        // considering the channel flow canceled.
5✔
2960
        f.wg.Add(1)
5✔
2961
        go func() {
10✔
2962
                defer f.wg.Done()
5✔
2963

5✔
2964
                peer, err := f.waitForPeerOnline(c.IdentityPub)
5✔
2965
                switch err {
5✔
2966
                // We're already shutting down, so we can just return.
2967
                case ErrFundingManagerShuttingDown:
×
2968
                        return
×
2969

2970
                // nil error means we continue on.
2971
                case nil:
5✔
2972

2973
                // For unexpected errors, we print the error and still try to
2974
                // fail the funding flow.
2975
                default:
×
2976
                        log.Errorf("Unexpected error while waiting for peer "+
×
2977
                                "to come online: %v", err)
×
2978
                }
2979

2980
                // Create channel identifier and set the channel ID.
2981
                cid := newChanIdentifier(pendingID)
5✔
2982
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
5✔
2983

5✔
2984
                // TODO(halseth): should this send be made
5✔
2985
                // reliable?
5✔
2986

5✔
2987
                // The reservation won't exist at this point, but we'll send an
5✔
2988
                // Error message over anyways with ChanID set to pendingID.
5✔
2989
                f.failFundingFlow(peer, cid, timeoutErr)
5✔
2990
        }()
2991

2992
        return timeoutErr
5✔
2993
}
2994

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

62✔
3003
        confChan := make(chan *confirmedChannel)
62✔
3004
        timeoutChan := make(chan error, 1)
62✔
3005
        cancelChan := make(chan struct{})
62✔
3006

62✔
3007
        f.wg.Add(1)
62✔
3008
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
62✔
3009

62✔
3010
        // If we are not the initiator, we have no money at stake and will
62✔
3011
        // timeout waiting for the funding transaction to confirm after a
62✔
3012
        // while.
62✔
3013
        if !ch.IsInitiator && !ch.IsZeroConf() {
91✔
3014
                f.wg.Add(1)
29✔
3015
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
29✔
3016
        }
29✔
3017
        defer close(cancelChan)
62✔
3018

62✔
3019
        select {
62✔
3020
        case err := <-timeoutChan:
5✔
3021
                if err != nil {
5✔
3022
                        return nil, err
×
3023
                }
×
3024
                return nil, ErrConfirmationTimeout
5✔
3025

3026
        case <-f.quit:
26✔
3027
                // The fundingManager is shutting down, and will resume wait on
26✔
3028
                // startup.
26✔
3029
                return nil, ErrFundingManagerShuttingDown
26✔
3030

3031
        case confirmedChannel, ok := <-confChan:
37✔
3032
                if !ok {
37✔
3033
                        return nil, fmt.Errorf("waiting for funding" +
×
3034
                                "confirmation failed")
×
3035
                }
×
3036
                return confirmedChannel, nil
37✔
3037
        }
3038
}
3039

3040
// makeFundingScript re-creates the funding script for the funding transaction
3041
// of the target channel.
3042
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
82✔
3043
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
82✔
3044
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
82✔
3045

82✔
3046
        if channel.ChanType.IsTaproot() {
90✔
3047
                pkScript, _, err := input.GenTaprootFundingScript(
8✔
3048
                        localKey, remoteKey, int64(channel.Capacity),
8✔
3049
                        channel.TapscriptRoot,
8✔
3050
                )
8✔
3051
                if err != nil {
8✔
3052
                        return nil, err
×
3053
                }
×
3054

3055
                return pkScript, nil
8✔
3056
        }
3057

3058
        multiSigScript, err := input.GenMultiSigScript(
77✔
3059
                localKey.SerializeCompressed(),
77✔
3060
                remoteKey.SerializeCompressed(),
77✔
3061
        )
77✔
3062
        if err != nil {
77✔
3063
                return nil, err
×
3064
        }
×
3065

3066
        return input.WitnessScriptHash(multiSigScript)
77✔
3067
}
3068

3069
// waitForFundingConfirmation handles the final stages of the channel funding
3070
// process once the funding transaction has been broadcast. The primary
3071
// function of waitForFundingConfirmation is to wait for blockchain
3072
// confirmation, and then to notify the other systems that must be notified
3073
// when a channel has become active for lightning transactions. It also updates
3074
// the channel’s opening transaction block height in the database.
3075
// The wait can be canceled by closing the cancelChan. In case of success,
3076
// a *lnwire.ShortChannelID will be passed to confChan.
3077
//
3078
// NOTE: This MUST be run as a goroutine.
3079
func (f *Manager) waitForFundingConfirmation(
3080
        completeChan *channeldb.OpenChannel, cancelChan <-chan struct{},
3081
        confChan chan<- *confirmedChannel) {
62✔
3082

62✔
3083
        defer f.wg.Done()
62✔
3084
        defer close(confChan)
62✔
3085

62✔
3086
        // Register with the ChainNotifier for a notification once the funding
62✔
3087
        // transaction reaches `numConfs` confirmations.
62✔
3088
        txid := completeChan.FundingOutpoint.Hash
62✔
3089
        fundingScript, err := makeFundingScript(completeChan)
62✔
3090
        if err != nil {
62✔
3091
                log.Errorf("unable to create funding script for "+
×
3092
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3093
                        err)
×
3094
                return
×
3095
        }
×
3096
        numConfs := uint32(completeChan.NumConfsRequired)
62✔
3097

62✔
3098
        // If the underlying channel is a zero-conf channel, we'll set numConfs
62✔
3099
        // to 6, since it will be zero here.
62✔
3100
        if completeChan.IsZeroConf() {
71✔
3101
                numConfs = 6
9✔
3102
        }
9✔
3103

3104
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
62✔
3105
                &txid, fundingScript, numConfs,
62✔
3106
                completeChan.BroadcastHeight(),
62✔
3107
        )
62✔
3108
        if err != nil {
62✔
3109
                log.Errorf("Unable to register for confirmation of "+
×
3110
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3111
                        err)
×
3112
                return
×
3113
        }
×
3114

3115
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
62✔
3116
                txid, numConfs)
62✔
3117

62✔
3118
        // Wait until the specified number of confirmations has been reached,
62✔
3119
        // we get a cancel signal, or the wallet signals a shutdown.
62✔
3120
        for {
152✔
3121
                select {
90✔
3122
                case updDetails, ok := <-confNtfn.Updates:
29✔
3123
                        if !ok {
29✔
3124
                                log.Warnf("ChainNotifier shutting down, "+
×
3125
                                        "cannot process updates for "+
×
3126
                                        "ChannelPoint(%v)",
×
3127
                                        completeChan.FundingOutpoint)
×
3128

×
3129
                                return
×
3130
                        }
×
3131

3132
                        log.Debugf("funding tx %s received confirmation in "+
29✔
3133
                                "block %d, %d confirmations left", txid,
29✔
3134
                                updDetails.BlockHeight, updDetails.NumConfsLeft)
29✔
3135

29✔
3136
                        // Only update the ConfirmationHeight the first time a
29✔
3137
                        // confirmation is received, since on subsequent
29✔
3138
                        // confirmations the block height will remain the same.
29✔
3139
                        if completeChan.ConfirmationHeight == 0 {
58✔
3140
                                err := completeChan.MarkConfirmationHeight(
29✔
3141
                                        updDetails.BlockHeight,
29✔
3142
                                )
29✔
3143
                                if err != nil {
29✔
3144
                                        log.Errorf("failed to update "+
×
3145
                                                "confirmed state for "+
×
3146
                                                "ChannelPoint(%v): %v",
×
3147
                                                completeChan.FundingOutpoint,
×
3148
                                                err)
×
3149

×
3150
                                        return
×
3151
                                }
×
3152
                        }
3153

3154
                case _, ok := <-confNtfn.NegativeConf:
4✔
3155
                        if !ok {
4✔
3156
                                log.Warnf("ChainNotifier shutting down, "+
×
3157
                                        "cannot track negative confirmations "+
×
3158
                                        "for ChannelPoint(%v)",
×
3159
                                        completeChan.FundingOutpoint)
×
3160

×
3161
                                return
×
3162
                        }
×
3163

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

4✔
3167
                        // Reset the confirmation height to 0 because the
4✔
3168
                        // funding transaction was reorged out.
4✔
3169
                        err := completeChan.MarkConfirmationHeight(uint32(0))
4✔
3170
                        if err != nil {
4✔
3171
                                log.Errorf("failed to update state for "+
×
3172
                                        "ChannelPoint(%v): %v",
×
3173
                                        completeChan.FundingOutpoint, err)
×
3174

×
3175
                                return
×
3176
                        }
×
3177

3178
                case confDetails, ok := <-confNtfn.Confirmed:
37✔
3179
                        if !ok {
37✔
3180
                                log.Warnf("ChainNotifier shutting down, "+
×
3181
                                        "cannot complete funding flow for "+
×
3182
                                        "ChannelPoint(%v)",
×
3183
                                        completeChan.FundingOutpoint)
×
3184

×
3185
                                return
×
3186
                        }
×
3187

3188
                        log.Debugf("funding tx %s for ChannelPoint(%v) "+
37✔
3189
                                "confirmed in block %d", txid,
37✔
3190
                                completeChan.FundingOutpoint,
37✔
3191
                                confDetails.BlockHeight)
37✔
3192

37✔
3193
                        // In the case of requiring a single confirmation, it
37✔
3194
                        // can happen that the `Confirmed` channel is read
37✔
3195
                        // from first, in which case the confirmation height
37✔
3196
                        // will not be set. If this happens, we take the
37✔
3197
                        // confirmation height from the `Confirmed` channel.
37✔
3198
                        if completeChan.ConfirmationHeight == 0 {
49✔
3199
                                err := completeChan.MarkConfirmationHeight(
12✔
3200
                                        confDetails.BlockHeight,
12✔
3201
                                )
12✔
3202
                                if err != nil {
12✔
3203
                                        log.Errorf("failed to update "+
×
3204
                                                "confirmed state for "+
×
3205
                                                "ChannelPoint(%v): %v",
×
3206
                                                completeChan.FundingOutpoint,
×
3207
                                                err)
×
3208

×
3209
                                        return
×
3210
                                }
×
3211
                        }
3212

3213
                        err := f.handleConfirmation(
37✔
3214
                                confDetails, completeChan, confChan,
37✔
3215
                        )
37✔
3216
                        if err != nil {
37✔
3217
                                log.Errorf("Error handling confirmation for "+
×
3218
                                        "ChannelPoint(%v), txid=%v: %v",
×
3219
                                        completeChan.FundingOutpoint, txid, err)
×
3220
                        }
×
3221

3222
                        return
37✔
3223

3224
                case <-cancelChan:
9✔
3225
                        log.Warnf("canceled waiting for funding confirmation, "+
9✔
3226
                                "stopping funding flow for ChannelPoint(%v)",
9✔
3227
                                completeChan.FundingOutpoint)
9✔
3228

9✔
3229
                        return
9✔
3230

3231
                case <-f.quit:
22✔
3232
                        log.Warnf("fundingManager shutting down, stopping "+
22✔
3233
                                "funding flow for ChannelPoint(%v)",
22✔
3234
                                completeChan.FundingOutpoint)
22✔
3235

22✔
3236
                        return
22✔
3237
                }
3238
        }
3239
}
3240

3241
// handleConfirmation is a helper function that constructs a ShortChannelID
3242
// based on the confirmation details and sends this information, along with the
3243
// funding transaction, to the provided confirmation channel.
3244
func (f *Manager) handleConfirmation(confDetails *chainntnfs.TxConfirmation,
3245
        completeChan *channeldb.OpenChannel,
3246
        confChan chan<- *confirmedChannel) error {
37✔
3247

37✔
3248
        fundingPoint := completeChan.FundingOutpoint
37✔
3249
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
37✔
3250
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
37✔
3251

37✔
3252
        // With the block height and the transaction index known, we can
37✔
3253
        // construct the compact chanID which is used on the network to unique
37✔
3254
        // identify channels.
37✔
3255
        shortChanID := lnwire.ShortChannelID{
37✔
3256
                BlockHeight: confDetails.BlockHeight,
37✔
3257
                TxIndex:     confDetails.TxIndex,
37✔
3258
                TxPosition:  uint16(fundingPoint.Index),
37✔
3259
        }
37✔
3260

37✔
3261
        select {
37✔
3262
        case confChan <- &confirmedChannel{
3263
                shortChanID: shortChanID,
3264
                fundingTx:   confDetails.Tx,
3265
        }:
37✔
3266
        case <-f.quit:
×
3267
                return fmt.Errorf("manager shutting down")
×
3268
        }
3269

3270
        return nil
37✔
3271
}
3272

3273
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3274
// has passed from the broadcast height of the given channel. In case of error,
3275
// the error is sent on timeoutChan. The wait can be canceled by closing the
3276
// cancelChan.
3277
//
3278
// NOTE: timeoutChan MUST be buffered.
3279
// NOTE: This MUST be run as a goroutine.
3280
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3281
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
29✔
3282

29✔
3283
        defer f.wg.Done()
29✔
3284

29✔
3285
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
29✔
3286
        if err != nil {
29✔
3287
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3288
                        "notification: %v", err)
×
3289
                return
×
3290
        }
×
3291

3292
        defer epochClient.Cancel()
29✔
3293

29✔
3294
        // The value of waitBlocksForFundingConf is adjusted in a development
29✔
3295
        // environment to enhance test capabilities. Otherwise, it is set to
29✔
3296
        // DefaultMaxWaitNumBlocksFundingConf.
29✔
3297
        waitBlocksForFundingConf := uint32(
29✔
3298
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
29✔
3299
        )
29✔
3300

29✔
3301
        if lncfg.IsDevBuild() {
32✔
3302
                waitBlocksForFundingConf =
3✔
3303
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3304
        }
3✔
3305

3306
        // On block maxHeight we will cancel the funding confirmation wait.
3307
        broadcastHeight := completeChan.BroadcastHeight()
29✔
3308
        maxHeight := broadcastHeight + waitBlocksForFundingConf
29✔
3309
        for {
60✔
3310
                select {
31✔
3311
                case epoch, ok := <-epochClient.Epochs:
7✔
3312
                        if !ok {
7✔
3313
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3314
                                        "shutting down")
×
3315
                                return
×
3316
                        }
×
3317

3318
                        // Close the timeout channel and exit if the block is
3319
                        // above the max height.
3320
                        if uint32(epoch.Height) >= maxHeight {
12✔
3321
                                log.Warnf("Waited for %v blocks without "+
5✔
3322
                                        "seeing funding transaction confirmed,"+
5✔
3323
                                        " cancelling.",
5✔
3324
                                        waitBlocksForFundingConf)
5✔
3325

5✔
3326
                                // Notify the caller of the timeout.
5✔
3327
                                close(timeoutChan)
5✔
3328
                                return
5✔
3329
                        }
5✔
3330

3331
                        // TODO: If we are the channel initiator implement
3332
                        // a method for recovering the funds from the funding
3333
                        // transaction
3334

3335
                case <-cancelChan:
18✔
3336
                        return
18✔
3337

3338
                case <-f.quit:
12✔
3339
                        // The fundingManager is shutting down, will resume
12✔
3340
                        // waiting for the funding transaction on startup.
12✔
3341
                        return
12✔
3342
                }
3343
        }
3344
}
3345

3346
// makeLabelForTx updates the label for the confirmed funding transaction. If
3347
// we opened the channel, and lnd's wallet published our funding tx (which is
3348
// not the case for some channels) then we update our transaction label with
3349
// our short channel ID, which is known now that our funding transaction has
3350
// confirmed. We do not label transactions we did not publish, because our
3351
// wallet has no knowledge of them.
3352
func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
37✔
3353
        if c.IsInitiator && c.ChanType.HasFundingTx() {
56✔
3354
                shortChanID := c.ShortChanID()
19✔
3355

19✔
3356
                // For zero-conf channels, we'll use the actually-confirmed
19✔
3357
                // short channel id.
19✔
3358
                if c.IsZeroConf() {
24✔
3359
                        shortChanID = c.ZeroConfRealScid()
5✔
3360
                }
5✔
3361

3362
                label := labels.MakeLabel(
19✔
3363
                        labels.LabelTypeChannelOpen, &shortChanID,
19✔
3364
                )
19✔
3365

19✔
3366
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
19✔
3367
                if err != nil {
19✔
3368
                        log.Errorf("unable to update label: %v", err)
×
3369
                }
×
3370
        }
3371
}
3372

3373
// handleFundingConfirmation marks a channel as open in the database, and set
3374
// the channelOpeningState markedOpen. In addition it will report the now
3375
// decided short channel ID to the switch, and close the local discovery signal
3376
// for this channel.
3377
func (f *Manager) handleFundingConfirmation(
3378
        completeChan *channeldb.OpenChannel,
3379
        confChannel *confirmedChannel) error {
33✔
3380

33✔
3381
        fundingPoint := completeChan.FundingOutpoint
33✔
3382
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
33✔
3383

33✔
3384
        // TODO(roasbeef): ideally persistent state update for chan above
33✔
3385
        // should be abstracted
33✔
3386

33✔
3387
        // Now that that the channel has been fully confirmed, we'll request
33✔
3388
        // that the wallet fully verify this channel to ensure that it can be
33✔
3389
        // used.
33✔
3390
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
33✔
3391
        if err != nil {
33✔
3392
                // TODO(roasbeef): delete chan state?
×
3393
                return fmt.Errorf("unable to validate channel: %w", err)
×
3394
        }
×
3395

3396
        // Now that the channel has been validated, we'll persist an alias for
3397
        // this channel if the option-scid-alias feature-bit was negotiated.
3398
        if completeChan.NegotiatedAliasFeature() {
38✔
3399
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
3400
                if err != nil {
5✔
3401
                        return fmt.Errorf("unable to request alias: %w", err)
×
3402
                }
×
3403

3404
                err = f.cfg.AliasManager.AddLocalAlias(
5✔
3405
                        aliasScid, confChannel.shortChanID, true, false,
5✔
3406
                )
5✔
3407
                if err != nil {
5✔
3408
                        return fmt.Errorf("unable to request alias: %w", err)
×
3409
                }
×
3410
        }
3411

3412
        // The funding transaction now being confirmed, we add this channel to
3413
        // the fundingManager's internal persistent state machine that we use
3414
        // to track the remaining process of the channel opening. This is
3415
        // useful to resume the opening process in case of restarts. We set the
3416
        // opening state before we mark the channel opened in the database,
3417
        // such that we can receover from one of the db writes failing.
3418
        err = f.saveChannelOpeningState(
33✔
3419
                &fundingPoint, markedOpen, &confChannel.shortChanID,
33✔
3420
        )
33✔
3421
        if err != nil {
33✔
3422
                return fmt.Errorf("error setting channel state to "+
×
3423
                        "markedOpen: %v", err)
×
3424
        }
×
3425

3426
        // Now that the channel has been fully confirmed and we successfully
3427
        // saved the opening state, we'll mark it as open within the database.
3428
        err = completeChan.MarkAsOpen(confChannel.shortChanID)
33✔
3429
        if err != nil {
33✔
3430
                return fmt.Errorf("error setting channel pending flag to "+
×
3431
                        "false:        %v", err)
×
3432
        }
×
3433

3434
        // Update the confirmed funding transaction label.
3435
        f.makeLabelForTx(completeChan)
33✔
3436

33✔
3437
        // Inform the ChannelNotifier that the channel has transitioned from
33✔
3438
        // pending open to open.
33✔
3439
        f.cfg.NotifyOpenChannelEvent(
33✔
3440
                completeChan.FundingOutpoint, completeChan.IdentityPub,
33✔
3441
        )
33✔
3442

33✔
3443
        // Close the discoverySignal channel, indicating to a separate
33✔
3444
        // goroutine that the channel now is marked as open in the database
33✔
3445
        // and that it is acceptable to process channel_ready messages
33✔
3446
        // from the peer.
33✔
3447
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
66✔
3448
                close(discoverySignal)
33✔
3449
        }
33✔
3450

3451
        return nil
33✔
3452
}
3453

3454
// sendChannelReady creates and sends the channelReady message.
3455
// This should be called after the funding transaction has been confirmed,
3456
// and the channelState is 'markedOpen'.
3457
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3458
        channel *lnwallet.LightningChannel) error {
38✔
3459

38✔
3460
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
38✔
3461

38✔
3462
        var peerKey [33]byte
38✔
3463
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
38✔
3464

38✔
3465
        // Next, we'll send over the channel_ready message which marks that we
38✔
3466
        // consider the channel open by presenting the remote party with our
38✔
3467
        // next revocation key. Without the revocation key, the remote party
38✔
3468
        // will be unable to propose state transitions.
38✔
3469
        nextRevocation, err := channel.NextRevocationKey()
38✔
3470
        if err != nil {
38✔
3471
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3472
        }
×
3473
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
38✔
3474

38✔
3475
        // If this is a taproot channel, then we also need to send along our
38✔
3476
        // set of musig2 nonces as well.
38✔
3477
        if completeChan.ChanType.IsTaproot() {
45✔
3478
                log.Infof("ChanID(%v): generating musig2 nonces...",
7✔
3479
                        chanID)
7✔
3480

7✔
3481
                f.nonceMtx.Lock()
7✔
3482
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
3483
                if !ok {
14✔
3484
                        // If we don't have any nonces generated yet for this
7✔
3485
                        // first state, then we'll generate them now and stow
7✔
3486
                        // them away.  When we receive the funding locked
7✔
3487
                        // message, we'll then pass along this same set of
7✔
3488
                        // nonces.
7✔
3489
                        newNonce, err := channel.GenMusigNonces()
7✔
3490
                        if err != nil {
7✔
3491
                                f.nonceMtx.Unlock()
×
3492
                                return err
×
3493
                        }
×
3494

3495
                        // Now that we've generated the nonce for this channel,
3496
                        // we'll store it in the set of pending nonces.
3497
                        localNonce = newNonce
7✔
3498
                        f.pendingMusigNonces[chanID] = localNonce
7✔
3499
                }
3500
                f.nonceMtx.Unlock()
7✔
3501

7✔
3502
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
7✔
3503
                        localNonce.PubNonce,
7✔
3504
                )
7✔
3505
        }
3506

3507
        // If the channel negotiated the option-scid-alias feature bit, we'll
3508
        // send a TLV segment that includes an alias the peer can use in their
3509
        // invoice hop hints. We'll send the first alias we find for the
3510
        // channel since it does not matter which alias we send. We'll error
3511
        // out in the odd case that no aliases are found.
3512
        if completeChan.NegotiatedAliasFeature() {
47✔
3513
                aliases := f.cfg.AliasManager.GetAliases(
9✔
3514
                        completeChan.ShortChanID(),
9✔
3515
                )
9✔
3516
                if len(aliases) == 0 {
9✔
3517
                        return fmt.Errorf("no aliases found")
×
3518
                }
×
3519

3520
                // We can use a pointer to aliases since GetAliases returns a
3521
                // copy of the alias slice.
3522
                channelReadyMsg.AliasScid = &aliases[0]
9✔
3523
        }
3524

3525
        // If the peer has disconnected before we reach this point, we will need
3526
        // to wait for him to come back online before sending the channelReady
3527
        // message. This is special for channelReady, since failing to send any
3528
        // of the previous messages in the funding flow just cancels the flow.
3529
        // But now the funding transaction is confirmed, the channel is open
3530
        // and we have to make sure the peer gets the channelReady message when
3531
        // it comes back online. This is also crucial during restart of lnd,
3532
        // where we might try to resend the channelReady message before the
3533
        // server has had the time to connect to the peer. We keep trying to
3534
        // send channelReady until we succeed, or the fundingManager is shut
3535
        // down.
3536
        for {
76✔
3537
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
38✔
3538
                if err != nil {
39✔
3539
                        return err
1✔
3540
                }
1✔
3541

3542
                localAlias := peer.LocalFeatures().HasFeature(
37✔
3543
                        lnwire.ScidAliasOptional,
37✔
3544
                )
37✔
3545
                remoteAlias := peer.RemoteFeatures().HasFeature(
37✔
3546
                        lnwire.ScidAliasOptional,
37✔
3547
                )
37✔
3548

37✔
3549
                // We could also refresh the channel state instead of checking
37✔
3550
                // whether the feature was negotiated, but this saves us a
37✔
3551
                // database read.
37✔
3552
                if channelReadyMsg.AliasScid == nil && localAlias &&
37✔
3553
                        remoteAlias {
37✔
3554

×
3555
                        // If an alias was not assigned above and the scid
×
3556
                        // alias feature was negotiated, check if we already
×
3557
                        // have an alias stored in case handleChannelReady was
×
3558
                        // called before this. If an alias exists, use that in
×
3559
                        // channel_ready. Otherwise, request and store an
×
3560
                        // alias and use that.
×
3561
                        aliases := f.cfg.AliasManager.GetAliases(
×
3562
                                completeChan.ShortChannelID,
×
3563
                        )
×
3564
                        if len(aliases) == 0 {
×
3565
                                // No aliases were found.
×
3566
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3567
                                if err != nil {
×
3568
                                        return err
×
3569
                                }
×
3570

3571
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3572
                                        alias, completeChan.ShortChannelID,
×
3573
                                        false, false,
×
3574
                                )
×
3575
                                if err != nil {
×
3576
                                        return err
×
3577
                                }
×
3578

3579
                                channelReadyMsg.AliasScid = &alias
×
3580
                        } else {
×
3581
                                channelReadyMsg.AliasScid = &aliases[0]
×
3582
                        }
×
3583
                }
3584

3585
                log.Infof("Peer(%x) is online, sending ChannelReady "+
37✔
3586
                        "for ChannelID(%v)", peerKey, chanID)
37✔
3587

37✔
3588
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
74✔
3589
                        // Sending succeeded, we can break out and continue the
37✔
3590
                        // funding flow.
37✔
3591
                        break
37✔
3592
                }
3593

3594
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3595
                        "Will retry when online", peerKey, err)
×
3596
        }
3597

3598
        return nil
37✔
3599
}
3600

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

63✔
3606
        // If the funding manager has exited, return an error to stop looping.
63✔
3607
        // Note that the peer may appear as online while the funding manager
63✔
3608
        // has stopped due to the shutdown order in the server.
63✔
3609
        select {
63✔
UNCOV
3610
        case <-f.quit:
×
UNCOV
3611
                return false, ErrFundingManagerShuttingDown
×
3612
        default:
63✔
3613
        }
3614

3615
        // Avoid a tight loop if peer is offline.
3616
        if _, err := f.waitForPeerOnline(node); err != nil {
63✔
3617
                log.Errorf("Wait for peer online failed: %v", err)
×
3618
                return false, err
×
3619
        }
×
3620

3621
        // If we cannot find the channel, then we haven't processed the
3622
        // remote's channelReady message.
3623
        channel, err := f.cfg.FindChannel(node, chanID)
63✔
3624
        if err != nil {
63✔
3625
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3626
                        "ChannelReady was received", chanID)
×
3627
                return false, err
×
3628
        }
×
3629

3630
        // If we haven't insert the next revocation point, we haven't finished
3631
        // processing the channel ready message.
3632
        if channel.RemoteNextRevocation == nil {
102✔
3633
                return false, nil
39✔
3634
        }
39✔
3635

3636
        // Finally, the barrier signal is removed once we finish
3637
        // `handleChannelReady`. If we can still find the signal, we haven't
3638
        // finished processing it yet.
3639
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
27✔
3640

27✔
3641
        return !loaded, nil
27✔
3642
}
3643

3644
// extractAnnounceParams extracts the various channel announcement and update
3645
// parameters that will be needed to construct a ChannelAnnouncement and a
3646
// ChannelUpdate.
3647
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3648
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
29✔
3649

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

29✔
3656
        // We don't necessarily want to go as low as the remote party allows.
29✔
3657
        // Check it against our default forwarding policy.
29✔
3658
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
32✔
3659
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3660
        }
3✔
3661

3662
        // We'll obtain the max HTLC value we can forward in our direction, as
3663
        // we'll use this value within our ChannelUpdate. This value must be <=
3664
        // channel capacity and <= the maximum in-flight msats set by the peer.
3665
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
29✔
3666
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
29✔
3667
        if fwdMaxHTLC > capacityMSat {
29✔
3668
                fwdMaxHTLC = capacityMSat
×
3669
        }
×
3670

3671
        return fwdMinHTLC, fwdMaxHTLC
29✔
3672
}
3673

3674
// addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
3675
// gossiper so that the channel is added to the graph builder's internal graph.
3676
// These announcement messages are NOT broadcasted to the greater network,
3677
// only to the channel counter party. The proofs required to announce the
3678
// channel to the greater network will be created and sent in annAfterSixConfs.
3679
// The peerAlias is used for zero-conf channels to give the counter-party a
3680
// ChannelUpdate they understand. ourPolicy may be set for various
3681
// option-scid-alias channels to re-use the same policy.
3682
func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
3683
        shortChanID *lnwire.ShortChannelID,
3684
        peerAlias *lnwire.ShortChannelID,
3685
        ourPolicy *models.ChannelEdgePolicy) error {
29✔
3686

29✔
3687
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
29✔
3688

29✔
3689
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
29✔
3690

29✔
3691
        ann, err := f.newChanAnnouncement(
29✔
3692
                f.cfg.IDKey, completeChan.IdentityPub,
29✔
3693
                &completeChan.LocalChanCfg.MultiSigKey,
29✔
3694
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
29✔
3695
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
29✔
3696
                completeChan.ChanType,
29✔
3697
        )
29✔
3698
        if err != nil {
29✔
3699
                return fmt.Errorf("error generating channel "+
×
3700
                        "announcement: %v", err)
×
3701
        }
×
3702

3703
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3704
        // to the Router's topology.
3705
        errChan := f.cfg.SendAnnouncement(
29✔
3706
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
29✔
3707
                discovery.ChannelPoint(completeChan.FundingOutpoint),
29✔
3708
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
29✔
3709
        )
29✔
3710
        select {
29✔
3711
        case err := <-errChan:
29✔
3712
                if err != nil {
29✔
3713
                        if graph.IsError(err, graph.ErrOutdated,
×
3714
                                graph.ErrIgnored) {
×
3715

×
3716
                                log.Debugf("Graph rejected "+
×
3717
                                        "ChannelAnnouncement: %v", err)
×
3718
                        } else {
×
3719
                                return fmt.Errorf("error sending channel "+
×
3720
                                        "announcement: %v", err)
×
3721
                        }
×
3722
                }
3723
        case <-f.quit:
×
3724
                return ErrFundingManagerShuttingDown
×
3725
        }
3726

3727
        errChan = f.cfg.SendAnnouncement(
29✔
3728
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
29✔
3729
        )
29✔
3730
        select {
29✔
3731
        case err := <-errChan:
29✔
3732
                if err != nil {
29✔
3733
                        if graph.IsError(err, graph.ErrOutdated,
×
3734
                                graph.ErrIgnored) {
×
3735

×
3736
                                log.Debugf("Graph rejected "+
×
3737
                                        "ChannelUpdate: %v", err)
×
3738
                        } else {
×
3739
                                return fmt.Errorf("error sending channel "+
×
3740
                                        "update: %v", err)
×
3741
                        }
×
3742
                }
3743
        case <-f.quit:
×
3744
                return ErrFundingManagerShuttingDown
×
3745
        }
3746

3747
        return nil
29✔
3748
}
3749

3750
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3751
// the network after 6 confs. Should be called after the channelReady message
3752
// is sent and the channel is added to the graph (channelState is
3753
// 'addedToGraph') and the channel is ready to be used. This is the last
3754
// step in the channel opening process, and the opening state will be deleted
3755
// from the database if successful.
3756
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3757
        shortChanID *lnwire.ShortChannelID) error {
29✔
3758

29✔
3759
        // If this channel is not meant to be announced to the greater network,
29✔
3760
        // we'll only send our NodeAnnouncement1 to our counterparty to ensure
29✔
3761
        // we don't leak any of our information.
29✔
3762
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
29✔
3763
        if !announceChan {
40✔
3764
                log.Debugf("Will not announce private channel %v.",
11✔
3765
                        shortChanID.ToUint64())
11✔
3766

11✔
3767
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
11✔
3768
                if err != nil {
11✔
3769
                        return err
×
3770
                }
×
3771

3772
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
11✔
3773
                if err != nil {
11✔
3774
                        return fmt.Errorf("unable to retrieve current node "+
×
3775
                                "announcement: %v", err)
×
3776
                }
×
3777

3778
                chanID := lnwire.NewChanIDFromOutPoint(
11✔
3779
                        completeChan.FundingOutpoint,
11✔
3780
                )
11✔
3781
                pubKey := peer.PubKey()
11✔
3782
                log.Debugf("Sending our NodeAnnouncement1 for "+
11✔
3783
                        "ChannelID(%v) to %x", chanID, pubKey)
11✔
3784

11✔
3785
                // TODO(halseth): make reliable. If the peer is not online this
11✔
3786
                // will fail, and the opening process will stop. Should instead
11✔
3787
                // block here, waiting for the peer to come online.
11✔
3788
                if err := peer.SendMessage(true, &nodeAnn); err != nil {
11✔
3789
                        return fmt.Errorf("unable to send node announcement "+
×
3790
                                "to peer %x: %v", pubKey, err)
×
3791
                }
×
3792
        } else {
21✔
3793
                // Otherwise, we'll wait until the funding transaction has
21✔
3794
                // reached 6 confirmations before announcing it.
21✔
3795
                numConfs := uint32(completeChan.NumConfsRequired)
21✔
3796
                if numConfs < 6 {
42✔
3797
                        numConfs = 6
21✔
3798
                }
21✔
3799
                txid := completeChan.FundingOutpoint.Hash
21✔
3800
                log.Debugf("Will announce channel %v after ChannelPoint"+
21✔
3801
                        "(%v) has gotten %d confirmations",
21✔
3802
                        shortChanID.ToUint64(), completeChan.FundingOutpoint,
21✔
3803
                        numConfs)
21✔
3804

21✔
3805
                fundingScript, err := makeFundingScript(completeChan)
21✔
3806
                if err != nil {
21✔
3807
                        return fmt.Errorf("unable to create funding script "+
×
3808
                                "for ChannelPoint(%v): %v",
×
3809
                                completeChan.FundingOutpoint, err)
×
3810
                }
×
3811

3812
                // Register with the ChainNotifier for a notification once the
3813
                // funding transaction reaches at least 6 confirmations.
3814
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
21✔
3815
                        &txid, fundingScript, numConfs,
21✔
3816
                        completeChan.BroadcastHeight(),
21✔
3817
                )
21✔
3818
                if err != nil {
21✔
3819
                        return fmt.Errorf("unable to register for "+
×
3820
                                "confirmation of ChannelPoint(%v): %v",
×
3821
                                completeChan.FundingOutpoint, err)
×
3822
                }
×
3823

3824
                // Wait until 6 confirmations has been reached or the wallet
3825
                // signals a shutdown.
3826
                select {
21✔
3827
                case _, ok := <-confNtfn.Confirmed:
19✔
3828
                        if !ok {
19✔
3829
                                return fmt.Errorf("ChainNotifier shutting "+
×
3830
                                        "down, cannot complete funding flow "+
×
3831
                                        "for ChannelPoint(%v)",
×
3832
                                        completeChan.FundingOutpoint)
×
3833
                        }
×
3834
                        // Fallthrough.
3835

3836
                case <-f.quit:
5✔
3837
                        return fmt.Errorf("%v, stopping funding flow for "+
5✔
3838
                                "ChannelPoint(%v)",
5✔
3839
                                ErrFundingManagerShuttingDown,
5✔
3840
                                completeChan.FundingOutpoint)
5✔
3841
                }
3842

3843
                fundingPoint := completeChan.FundingOutpoint
19✔
3844
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
19✔
3845

19✔
3846
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
19✔
3847
                        &fundingPoint, shortChanID)
19✔
3848

19✔
3849
                // If this is a non-zero-conf option-scid-alias channel, we'll
19✔
3850
                // delete the mappings the gossiper uses so that ChannelUpdates
19✔
3851
                // with aliases won't be accepted. This is done elsewhere for
19✔
3852
                // zero-conf channels.
19✔
3853
                isScidFeature := completeChan.NegotiatedAliasFeature()
19✔
3854
                isZeroConf := completeChan.IsZeroConf()
19✔
3855
                if isScidFeature && !isZeroConf {
22✔
3856
                        baseScid := completeChan.ShortChanID()
3✔
3857
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
3✔
3858
                        if err != nil {
3✔
3859
                                return fmt.Errorf("failed deleting six confs "+
×
3860
                                        "maps: %v", err)
×
3861
                        }
×
3862

3863
                        // We'll delete the edge and add it again via
3864
                        // addToGraph. This is because the peer may have
3865
                        // sent us a ChannelUpdate with an alias and we don't
3866
                        // want to relay this.
3867
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
3✔
3868
                        if err != nil {
3✔
3869
                                return fmt.Errorf("failed deleting real edge "+
×
3870
                                        "for alias channel from graph: %v",
×
3871
                                        err)
×
3872
                        }
×
3873

3874
                        err = f.addToGraph(
3✔
3875
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3876
                        )
3✔
3877
                        if err != nil {
3✔
3878
                                return fmt.Errorf("failed to re-add to "+
×
3879
                                        "graph: %v", err)
×
3880
                        }
×
3881
                }
3882

3883
                // Create and broadcast the proofs required to make this channel
3884
                // public and usable for other nodes for routing.
3885
                err = f.announceChannel(
19✔
3886
                        f.cfg.IDKey, completeChan.IdentityPub,
19✔
3887
                        &completeChan.LocalChanCfg.MultiSigKey,
19✔
3888
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
19✔
3889
                        *shortChanID, chanID, completeChan.ChanType,
19✔
3890
                )
19✔
3891
                if err != nil {
22✔
3892
                        return fmt.Errorf("channel announcement failed: %w",
3✔
3893
                                err)
3✔
3894
                }
3✔
3895

3896
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
19✔
3897
                        "sent to gossiper", &fundingPoint, shortChanID)
19✔
3898
        }
3899

3900
        return nil
27✔
3901
}
3902

3903
// waitForZeroConfChannel is called when the state is addedToGraph with
3904
// a zero-conf channel. This will wait for the real confirmation, add the
3905
// confirmed SCID to the router graph, and then announce after six confs.
3906
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
9✔
3907
        // First we'll check whether the channel is confirmed on-chain. If it
9✔
3908
        // is already confirmed, the chainntnfs subsystem will return with the
9✔
3909
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
9✔
3910
        confChan, err := f.waitForFundingWithTimeout(c)
9✔
3911
        if err != nil {
14✔
3912
                return fmt.Errorf("error waiting for zero-conf funding "+
5✔
3913
                        "confirmation for ChannelPoint(%v): %v",
5✔
3914
                        c.FundingOutpoint, err)
5✔
3915
        }
5✔
3916

3917
        // We'll need to refresh the channel state so that things are properly
3918
        // populated when validating the channel state. Otherwise, a panic may
3919
        // occur due to inconsistency in the OpenChannel struct.
3920
        err = c.Refresh()
7✔
3921
        if err != nil {
10✔
3922
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3923
        }
3✔
3924

3925
        // Now that we have the confirmed transaction and the proper SCID,
3926
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3927
        // formatted.
3928
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
7✔
3929
        if err != nil {
7✔
3930
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3931
                        "%v", err)
×
3932
        }
×
3933

3934
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3935
        // the database and refresh the OpenChannel struct with it.
3936
        err = c.MarkRealScid(confChan.shortChanID)
7✔
3937
        if err != nil {
7✔
3938
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3939
                        "channel: %v", err)
×
3940
        }
×
3941

3942
        // Six confirmations have been reached. If this channel is public,
3943
        // we'll delete some of the alias mappings the gossiper uses.
3944
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
7✔
3945
        if isPublic {
12✔
3946
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
5✔
3947
                if err != nil {
5✔
3948
                        return fmt.Errorf("unable to delete base alias after "+
×
3949
                                "six confirmations: %v", err)
×
3950
                }
×
3951

3952
                // TODO: Make this atomic!
3953
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
5✔
3954
                if err != nil {
5✔
3955
                        return fmt.Errorf("unable to delete alias edge from "+
×
3956
                                "graph: %v", err)
×
3957
                }
×
3958

3959
                // We'll need to update the graph with the new ShortChannelID
3960
                // via an addToGraph call. We don't pass in the peer's
3961
                // alias since we'll be using the confirmed SCID from now on
3962
                // regardless if it's public or not.
3963
                err = f.addToGraph(
5✔
3964
                        c, &confChan.shortChanID, nil, ourPolicy,
5✔
3965
                )
5✔
3966
                if err != nil {
5✔
3967
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3968
                                "SCID to graph: %v", err)
×
3969
                }
×
3970
        }
3971

3972
        // Since we have now marked down the confirmed SCID, we'll also need to
3973
        // tell the Switch to refresh the relevant ChannelLink so that forwards
3974
        // under the confirmed SCID are possible if this is a public channel.
3975
        err = f.cfg.ReportShortChanID(c.FundingOutpoint)
7✔
3976
        if err != nil {
7✔
3977
                // This should only fail if the link is not found in the
×
3978
                // Switch's linkIndex map. If this is the case, then the peer
×
3979
                // has gone offline and the next time the link is loaded, it
×
3980
                // will have a refreshed state. Just log an error here.
×
3981
                log.Errorf("unable to report scid for zero-conf channel "+
×
3982
                        "channel: %v", err)
×
3983
        }
×
3984

3985
        // Update the confirmed transaction's label.
3986
        f.makeLabelForTx(c)
7✔
3987

7✔
3988
        return nil
7✔
3989
}
3990

3991
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3992
// is the verification nonce for the state created for us after the initial
3993
// commitment transaction signed as part of the funding flow.
3994
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3995
) (*musig2.Nonces, error) {
7✔
3996

7✔
3997
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
7✔
3998
                channel.RevocationProducer,
7✔
3999
        )
7✔
4000
        if err != nil {
7✔
4001
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4002
                        "nonces: %v", err)
×
4003
        }
×
4004

4005
        // We use the _next_ commitment height here as we need to generate the
4006
        // nonce for the next state the remote party will sign for us.
4007
        verNonce, err := channeldb.NewMusigVerificationNonce(
7✔
4008
                channel.LocalChanCfg.MultiSigKey.PubKey,
7✔
4009
                channel.LocalCommitment.CommitHeight+1,
7✔
4010
                musig2ShaChain,
7✔
4011
        )
7✔
4012
        if err != nil {
7✔
4013
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4014
                        "nonces: %v", err)
×
4015
        }
×
4016

4017
        return verNonce, nil
7✔
4018
}
4019

4020
// handleChannelReady finalizes the channel funding process and enables the
4021
// channel to enter normal operating mode.
4022
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
4023
        msg *lnwire.ChannelReady) {
31✔
4024

31✔
4025
        defer f.wg.Done()
31✔
4026

31✔
4027
        // Notify the aux hook that the specified peer just established a
31✔
4028
        // channel with us, identified by the given channel ID.
31✔
4029
        f.cfg.AuxChannelNegotiator.WhenSome(
31✔
4030
                func(acn lnwallet.AuxChannelNegotiator) {
31✔
4031
                        acn.ProcessChannelReady(msg.ChanID, peer.PubKey())
×
4032
                },
×
4033
        )
4034

4035
        // If we are in development mode, we'll wait for specified duration
4036
        // before processing the channel ready message.
4037
        if f.cfg.Dev != nil {
34✔
4038
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
4039
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
4040
                        "channel_ready", msg.ChanID, duration)
3✔
4041

3✔
4042
                select {
3✔
4043
                case <-time.After(duration):
3✔
4044
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
4045
                                "channel_ready", msg.ChanID, duration)
3✔
4046
                case <-f.quit:
×
4047
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
4048
                        return
×
4049
                }
4050
        }
4051

4052
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
31✔
4053
                "peer %x", msg.ChanID,
31✔
4054
                peer.IdentityKey().SerializeCompressed())
31✔
4055

31✔
4056
        // We now load or create a new channel barrier for this channel.
31✔
4057
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
31✔
4058
                msg.ChanID, struct{}{},
31✔
4059
        )
31✔
4060

31✔
4061
        // If we are currently in the process of handling a channel_ready
31✔
4062
        // message for this channel, ignore.
31✔
4063
        if loaded {
35✔
4064
                log.Infof("Already handling channelReady for "+
4✔
4065
                        "ChannelID(%v), ignoring.", msg.ChanID)
4✔
4066
                return
4✔
4067
        }
4✔
4068

4069
        // If not already handling channelReady for this channel, then the
4070
        // `LoadOrStore` has set up a barrier, and it will be removed once this
4071
        // function exits.
4072
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
30✔
4073

30✔
4074
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
30✔
4075
        if ok {
58✔
4076
                // Before we proceed with processing the channel_ready
28✔
4077
                // message, we'll wait for the local waitForFundingConfirmation
28✔
4078
                // goroutine to signal that it has the necessary state in
28✔
4079
                // place. Otherwise, we may be missing critical information
28✔
4080
                // required to handle forwarded HTLC's.
28✔
4081
                select {
28✔
4082
                case <-localDiscoverySignal:
28✔
4083
                        // Fallthrough
4084
                case <-f.quit:
3✔
4085
                        return
3✔
4086
                }
4087

4088
                // With the signal received, we can now safely delete the entry
4089
                // from the map.
4090
                f.localDiscoverySignals.Delete(msg.ChanID)
28✔
4091
        }
4092

4093
        // First, we'll attempt to locate the channel whose funding workflow is
4094
        // being finalized by this message. We go to the database rather than
4095
        // our reservation map as we may have restarted, mid funding flow. Also
4096
        // provide the node's public key to make the search faster.
4097
        chanID := msg.ChanID
30✔
4098
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
30✔
4099
        if err != nil {
30✔
4100
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
4101
                        "funding", chanID)
×
4102
                return
×
4103
        }
×
4104

4105
        // If this is a taproot channel, then we can generate the set of nonces
4106
        // the remote party needs to send the next remote commitment here.
4107
        var firstVerNonce *musig2.Nonces
30✔
4108
        if channel.ChanType.IsTaproot() {
37✔
4109
                firstVerNonce, err = genFirstStateMusigNonce(channel)
7✔
4110
                if err != nil {
7✔
4111
                        log.Error(err)
×
4112
                        return
×
4113
                }
×
4114
        }
4115

4116
        // We'll need to store the received TLV alias if the option_scid_alias
4117
        // feature was negotiated. This will be used to provide route hints
4118
        // during invoice creation. In the zero-conf case, it is also used to
4119
        // provide a ChannelUpdate to the remote peer. This is done before the
4120
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
4121
        // If it were to fail on the first call to handleChannelReady, we
4122
        // wouldn't want the channel to be usable yet.
4123
        if channel.NegotiatedAliasFeature() {
39✔
4124
                // If the AliasScid field is nil, we must fail out. We will
9✔
4125
                // most likely not be able to route through the peer.
9✔
4126
                if msg.AliasScid == nil {
9✔
4127
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
4128
                                "does not implement the option-scid-alias "+
×
4129
                                "feature properly", chanID)
×
4130
                        return
×
4131
                }
×
4132

4133
                // We'll store the AliasScid so that invoice creation can use
4134
                // it.
4135
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
9✔
4136
                if err != nil {
9✔
4137
                        log.Errorf("unable to store peer's alias: %v", err)
×
4138
                        return
×
4139
                }
×
4140

4141
                // If we do not have an alias stored, we'll create one now.
4142
                // This is only used in the upgrade case where a user toggles
4143
                // the option-scid-alias feature-bit to on. We'll also send the
4144
                // channel_ready message here in case the link is created
4145
                // before sendChannelReady is called.
4146
                aliases := f.cfg.AliasManager.GetAliases(
9✔
4147
                        channel.ShortChannelID,
9✔
4148
                )
9✔
4149
                if len(aliases) == 0 {
9✔
4150
                        // No aliases were found so we'll request and store an
×
4151
                        // alias and use it in the channel_ready message.
×
4152
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
4153
                        if err != nil {
×
4154
                                log.Errorf("unable to request alias: %v", err)
×
4155
                                return
×
4156
                        }
×
4157

4158
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4159
                                alias, channel.ShortChannelID, false, false,
×
4160
                        )
×
4161
                        if err != nil {
×
4162
                                log.Errorf("unable to add local alias: %v",
×
4163
                                        err)
×
4164
                                return
×
4165
                        }
×
4166

4167
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4168
                        if err != nil {
×
4169
                                log.Errorf("unable to fetch second "+
×
4170
                                        "commitment point: %v", err)
×
4171
                                return
×
4172
                        }
×
4173

4174
                        channelReadyMsg := lnwire.NewChannelReady(
×
4175
                                chanID, secondPoint,
×
4176
                        )
×
4177
                        channelReadyMsg.AliasScid = &alias
×
4178

×
4179
                        if firstVerNonce != nil {
×
4180
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4181
                                        firstVerNonce.PubNonce,
×
4182
                                )
×
4183
                        }
×
4184

4185
                        err = peer.SendMessage(true, channelReadyMsg)
×
4186
                        if err != nil {
×
4187
                                log.Errorf("unable to send channel_ready: %v",
×
4188
                                        err)
×
4189
                                return
×
4190
                        }
×
4191
                }
4192
        }
4193

4194
        // If the RemoteNextRevocation is non-nil, it means that we have
4195
        // already processed channelReady for this channel, so ignore. This
4196
        // check is after the alias logic so we store the peer's most recent
4197
        // alias. The spec requires us to validate that subsequent
4198
        // channel_ready messages use the same per commitment point (the
4199
        // second), but it is not actually necessary since we'll just end up
4200
        // ignoring it. We are, however, required to *send* the same per
4201
        // commitment point, since another pedantic implementation might
4202
        // verify it.
4203
        if channel.RemoteNextRevocation != nil {
34✔
4204
                log.Infof("Received duplicate channelReady for "+
4✔
4205
                        "ChannelID(%v), ignoring.", chanID)
4✔
4206
                return
4✔
4207
        }
4✔
4208

4209
        // If this is a taproot channel, then we'll need to map the received
4210
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4211
        // required in order to make the channel whole.
4212
        var chanOpts []lnwallet.ChannelOpt
29✔
4213
        if channel.ChanType.IsTaproot() {
36✔
4214
                f.nonceMtx.Lock()
7✔
4215
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
4216
                if !ok {
10✔
4217
                        // If there's no pending nonce for this channel ID,
3✔
4218
                        // we'll use the one generated above.
3✔
4219
                        localNonce = firstVerNonce
3✔
4220
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4221
                }
3✔
4222
                f.nonceMtx.Unlock()
7✔
4223

7✔
4224
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
7✔
4225
                        chanID)
7✔
4226

7✔
4227
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
7✔
4228
                        errNoLocalNonce,
7✔
4229
                )
7✔
4230
                if err != nil {
7✔
4231
                        cid := newChanIdentifier(msg.ChanID)
×
4232
                        f.sendWarning(peer, cid, err)
×
4233

×
4234
                        return
×
4235
                }
×
4236

4237
                chanOpts = append(
7✔
4238
                        chanOpts,
7✔
4239
                        lnwallet.WithLocalMusigNonces(localNonce),
7✔
4240
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
7✔
4241
                                PubNonce: remoteNonce,
7✔
4242
                        }),
7✔
4243
                )
7✔
4244

7✔
4245
                // Inform the aux funding controller that the liquidity in the
7✔
4246
                // custom channel is now ready to be advertised. We potentially
7✔
4247
                // haven't sent our own channel ready message yet, but other
7✔
4248
                // than that the channel is ready to count toward available
7✔
4249
                // liquidity.
7✔
4250
                err = fn.MapOptionZ(
7✔
4251
                        f.cfg.AuxFundingController,
7✔
4252
                        func(controller AuxFundingController) error {
7✔
4253
                                return controller.ChannelReady(
×
4254
                                        lnwallet.NewAuxChanState(channel),
×
4255
                                )
×
4256
                        },
×
4257
                )
4258
                if err != nil {
7✔
4259
                        cid := newChanIdentifier(msg.ChanID)
×
4260
                        f.sendWarning(peer, cid, err)
×
4261

×
4262
                        return
×
4263
                }
×
4264
        }
4265

4266
        // The channel_ready message contains the next commitment point we'll
4267
        // need to create the next commitment state for the remote party. So
4268
        // we'll insert that into the channel now before passing it along to
4269
        // other sub-systems.
4270
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
29✔
4271
        if err != nil {
29✔
4272
                log.Errorf("unable to insert next commitment point: %v", err)
×
4273
                return
×
4274
        }
×
4275

4276
        // Before we can add the channel to the peer, we'll need to ensure that
4277
        // we have an initial forwarding policy set.
4278
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
29✔
4279
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4280
                        err)
×
4281
        }
×
4282

4283
        err = peer.AddNewChannel(&lnpeer.NewChannel{
29✔
4284
                OpenChannel: channel,
29✔
4285
                ChanOpts:    chanOpts,
29✔
4286
        }, f.quit)
29✔
4287
        if err != nil {
29✔
4288
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4289
                        channel.FundingOutpoint,
×
4290
                        peer.IdentityKey().SerializeCompressed(), err,
×
4291
                )
×
4292
        }
×
4293
}
4294

4295
// handleChannelReadyReceived is called once the remote's channelReady message
4296
// is received and processed. At this stage, we must have sent out our
4297
// channelReady message, once the remote's channelReady is processed, the
4298
// channel is now active, thus we change its state to `addedToGraph` to
4299
// let the channel start handling routing.
4300
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4301
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4302
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
27✔
4303

27✔
4304
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
27✔
4305

27✔
4306
        // Since we've sent+received funding locked at this point, we
27✔
4307
        // can clean up the pending musig2 nonce state.
27✔
4308
        f.nonceMtx.Lock()
27✔
4309
        delete(f.pendingMusigNonces, chanID)
27✔
4310
        f.nonceMtx.Unlock()
27✔
4311

27✔
4312
        var peerAlias *lnwire.ShortChannelID
27✔
4313
        if channel.IsZeroConf() {
34✔
4314
                // We'll need to wait until channel_ready has been received and
7✔
4315
                // the peer lets us know the alias they want to use for the
7✔
4316
                // channel. With this information, we can then construct a
7✔
4317
                // ChannelUpdate for them.  If an alias does not yet exist,
7✔
4318
                // we'll just return, letting the next iteration of the loop
7✔
4319
                // check again.
7✔
4320
                var defaultAlias lnwire.ShortChannelID
7✔
4321
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
7✔
4322
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
7✔
4323
                if foundAlias == defaultAlias {
7✔
4324
                        return nil
×
4325
                }
×
4326

4327
                peerAlias = &foundAlias
7✔
4328
        }
4329

4330
        err := f.addToGraph(channel, scid, peerAlias, nil)
27✔
4331
        if err != nil {
27✔
4332
                return fmt.Errorf("failed adding to graph: %w", err)
×
4333
        }
×
4334

4335
        // As the channel is now added to the ChannelRouter's topology, the
4336
        // channel is moved to the next state of the state machine. It will be
4337
        // moved to the last state (actually deleted from the database) after
4338
        // the channel is finally announced.
4339
        err = f.saveChannelOpeningState(
27✔
4340
                &channel.FundingOutpoint, addedToGraph, scid,
27✔
4341
        )
27✔
4342
        if err != nil {
27✔
4343
                return fmt.Errorf("error setting channel state to"+
×
4344
                        " addedToGraph: %w", err)
×
4345
        }
×
4346

4347
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
4348
                "added to graph", chanID, scid)
27✔
4349

27✔
4350
        err = fn.MapOptionZ(
27✔
4351
                f.cfg.AuxFundingController,
27✔
4352
                func(controller AuxFundingController) error {
27✔
4353
                        return controller.ChannelReady(
×
4354
                                lnwallet.NewAuxChanState(channel),
×
4355
                        )
×
4356
                },
×
4357
        )
4358
        if err != nil {
27✔
4359
                return fmt.Errorf("failed notifying aux funding controller "+
×
4360
                        "about channel ready: %w", err)
×
4361
        }
×
4362

4363
        // Give the caller a final update notifying them that the channel is
4364
        fundingPoint := channel.FundingOutpoint
27✔
4365
        cp := &lnrpc.ChannelPoint{
27✔
4366
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
27✔
4367
                        FundingTxidBytes: fundingPoint.Hash[:],
27✔
4368
                },
27✔
4369
                OutputIndex: fundingPoint.Index,
27✔
4370
        }
27✔
4371

27✔
4372
        if updateChan != nil {
40✔
4373
                upd := &lnrpc.OpenStatusUpdate{
13✔
4374
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
13✔
4375
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
13✔
4376
                                        ChannelPoint: cp,
13✔
4377
                                },
13✔
4378
                        },
13✔
4379
                        PendingChanId: pendingChanID[:],
13✔
4380
                }
13✔
4381

13✔
4382
                select {
13✔
4383
                case updateChan <- upd:
13✔
4384
                case <-f.quit:
×
4385
                        return ErrFundingManagerShuttingDown
×
4386
                }
4387
        }
4388

4389
        return nil
27✔
4390
}
4391

4392
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4393
// policy set for the given channel. If we don't, we'll fall back to the default
4394
// values.
4395
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4396
        channel *channeldb.OpenChannel) error {
29✔
4397

29✔
4398
        // Before we can add the channel to the peer, we'll need to ensure that
29✔
4399
        // we have an initial forwarding policy set. This should always be the
29✔
4400
        // case except for a channel that was created with lnd <= 0.15.5 and
29✔
4401
        // is still pending while updating to this version.
29✔
4402
        var needDBUpdate bool
29✔
4403
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
29✔
4404
        if err != nil {
29✔
4405
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4406
                        "falling back to default values: %v", err)
×
4407

×
4408
                forwardingPolicy = f.defaultForwardingPolicy(
×
4409
                        channel.LocalChanCfg.ChannelStateBounds,
×
4410
                )
×
4411
                needDBUpdate = true
×
4412
        }
×
4413

4414
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4415
        // after 0.16.x, so if a channel was opened with such a version and is
4416
        // still pending while updating to this version, we'll need to set the
4417
        // values to the default values.
4418
        if forwardingPolicy.MinHTLCOut == 0 {
45✔
4419
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
16✔
4420
                needDBUpdate = true
16✔
4421
        }
16✔
4422
        if forwardingPolicy.MaxHTLC == 0 {
45✔
4423
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
16✔
4424
                needDBUpdate = true
16✔
4425
        }
16✔
4426

4427
        // And finally, if we found that the values currently stored aren't
4428
        // sufficient for the link, we'll update the database.
4429
        if needDBUpdate {
45✔
4430
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
16✔
4431
                if err != nil {
16✔
4432
                        return fmt.Errorf("unable to update initial "+
×
4433
                                "forwarding policy: %v", err)
×
4434
                }
×
4435
        }
4436

4437
        return nil
29✔
4438
}
4439

4440
// chanAnnouncement encapsulates the two authenticated announcements that we
4441
// send out to the network after a new channel has been created locally.
4442
type chanAnnouncement struct {
4443
        chanAnn       *lnwire.ChannelAnnouncement1
4444
        chanUpdateAnn *lnwire.ChannelUpdate1
4445
        chanProof     *lnwire.AnnounceSignatures1
4446
}
4447

4448
// newChanAnnouncement creates the authenticated channel announcement messages
4449
// required to broadcast a newly created channel to the network. The
4450
// announcement is two part: the first part authenticates the existence of the
4451
// channel and contains four signatures binding the funding pub keys and
4452
// identity pub keys of both parties to the channel, and the second segment is
4453
// authenticated only by us and contains our directional routing policy for the
4454
// channel. ourPolicy may be set in order to re-use an existing, non-default
4455
// policy.
4456
func (f *Manager) newChanAnnouncement(localPubKey,
4457
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4458
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4459
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4460
        ourPolicy *models.ChannelEdgePolicy,
4461
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
45✔
4462

45✔
4463
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
45✔
4464

45✔
4465
        // The unconditional section of the announcement is the ShortChannelID
45✔
4466
        // itself which compactly encodes the location of the funding output
45✔
4467
        // within the blockchain.
45✔
4468
        chanAnn := &lnwire.ChannelAnnouncement1{
45✔
4469
                ShortChannelID: shortChanID,
45✔
4470
                Features:       lnwire.NewRawFeatureVector(),
45✔
4471
                ChainHash:      chainHash,
45✔
4472
        }
45✔
4473

45✔
4474
        // If this is a taproot channel, then we'll set a special bit in the
45✔
4475
        // feature vector to indicate to the routing layer that this needs a
45✔
4476
        // slightly different type of validation.
45✔
4477
        //
45✔
4478
        // TODO(roasbeef): temp, remove after gossip 1.5
45✔
4479
        if chanType.IsTaproot() {
52✔
4480
                log.Debugf("Applying taproot feature bit to "+
7✔
4481
                        "ChannelAnnouncement for %v", chanID)
7✔
4482

7✔
4483
                chanAnn.Features.Set(
7✔
4484
                        lnwire.SimpleTaprootChannelsRequiredStaging,
7✔
4485
                )
7✔
4486
        }
7✔
4487

4488
        // The chanFlags field indicates which directed edge of the channel is
4489
        // being updated within the ChannelUpdateAnnouncement announcement
4490
        // below. A value of zero means it's the edge of the "first" node and 1
4491
        // being the other node.
4492
        var chanFlags lnwire.ChanUpdateChanFlags
45✔
4493

45✔
4494
        // The lexicographical ordering of the two identity public keys of the
45✔
4495
        // nodes indicates which of the nodes is "first". If our serialized
45✔
4496
        // identity key is lower than theirs then we're the "first" node and
45✔
4497
        // second otherwise.
45✔
4498
        selfBytes := localPubKey.SerializeCompressed()
45✔
4499
        remoteBytes := remotePubKey.SerializeCompressed()
45✔
4500
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
69✔
4501
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
24✔
4502
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
24✔
4503
                copy(
24✔
4504
                        chanAnn.BitcoinKey1[:],
24✔
4505
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4506
                )
24✔
4507
                copy(
24✔
4508
                        chanAnn.BitcoinKey2[:],
24✔
4509
                        remoteFundingKey.SerializeCompressed(),
24✔
4510
                )
24✔
4511

24✔
4512
                // If we're the first node then update the chanFlags to
24✔
4513
                // indicate the "direction" of the update.
24✔
4514
                chanFlags = 0
24✔
4515
        } else {
48✔
4516
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
24✔
4517
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
24✔
4518
                copy(
24✔
4519
                        chanAnn.BitcoinKey1[:],
24✔
4520
                        remoteFundingKey.SerializeCompressed(),
24✔
4521
                )
24✔
4522
                copy(
24✔
4523
                        chanAnn.BitcoinKey2[:],
24✔
4524
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4525
                )
24✔
4526

24✔
4527
                // If we're the second node then update the chanFlags to
24✔
4528
                // indicate the "direction" of the update.
24✔
4529
                chanFlags = 1
24✔
4530
        }
24✔
4531

4532
        // Our channel update message flags will signal that we support the
4533
        // max_htlc field.
4534
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
45✔
4535

45✔
4536
        // We announce the channel with the default values. Some of
45✔
4537
        // these values can later be changed by crafting a new ChannelUpdate.
45✔
4538
        chanUpdateAnn := &lnwire.ChannelUpdate1{
45✔
4539
                ShortChannelID: shortChanID,
45✔
4540
                ChainHash:      chainHash,
45✔
4541
                Timestamp:      uint32(time.Now().Unix()),
45✔
4542
                MessageFlags:   msgFlags,
45✔
4543
                ChannelFlags:   chanFlags,
45✔
4544
                TimeLockDelta: uint16(
45✔
4545
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
45✔
4546
                ),
45✔
4547
                HtlcMinimumMsat: fwdMinHTLC,
45✔
4548
                HtlcMaximumMsat: fwdMaxHTLC,
45✔
4549
        }
45✔
4550

45✔
4551
        // The caller of newChanAnnouncement is expected to provide the initial
45✔
4552
        // forwarding policy to be announced. If no persisted initial policy
45✔
4553
        // values are found, then we will use the default policy values in the
45✔
4554
        // channel announcement.
45✔
4555
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
45✔
4556
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
45✔
4557
                return nil, fmt.Errorf("unable to generate channel "+
×
4558
                        "update announcement: %w", err)
×
4559
        }
×
4560

4561
        switch {
45✔
4562
        case ourPolicy != nil:
3✔
4563
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4564
                // ChannelUpdate.
3✔
4565
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4566
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4567
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4568
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4569
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4570
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4571
                chanUpdateAnn.FeeRate = uint32(
3✔
4572
                        ourPolicy.FeeProportionalMillionths,
3✔
4573
                )
3✔
4574

4575
        case storedFwdingPolicy != nil:
45✔
4576
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
45✔
4577
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
45✔
4578

4579
        default:
×
4580
                log.Infof("No channel forwarding policy specified for channel "+
×
4581
                        "announcement of ChannelID(%v). "+
×
4582
                        "Assuming default fee parameters.", chanID)
×
4583
                chanUpdateAnn.BaseFee = uint32(
×
4584
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4585
                )
×
4586
                chanUpdateAnn.FeeRate = uint32(
×
4587
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4588
                )
×
4589
        }
4590

4591
        // With the channel update announcement constructed, we'll generate a
4592
        // signature that signs a double-sha digest of the announcement.
4593
        // This'll serve to authenticate this announcement and any other future
4594
        // updates we may send.
4595
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
45✔
4596
        if err != nil {
45✔
4597
                return nil, err
×
4598
        }
×
4599
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
45✔
4600
        if err != nil {
45✔
4601
                return nil, fmt.Errorf("unable to generate channel "+
×
4602
                        "update announcement signature: %w", err)
×
4603
        }
×
4604
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
45✔
4605
        if err != nil {
45✔
4606
                return nil, fmt.Errorf("unable to generate channel "+
×
4607
                        "update announcement signature: %w", err)
×
4608
        }
×
4609

4610
        // The channel existence proofs itself is currently announced in
4611
        // distinct message. In order to properly authenticate this message, we
4612
        // need two signatures: one under the identity public key used which
4613
        // signs the message itself and another signature of the identity
4614
        // public key under the funding key itself.
4615
        //
4616
        // TODO(roasbeef): use SignAnnouncement here instead?
4617
        chanAnnMsg, err := chanAnn.DataToSign()
45✔
4618
        if err != nil {
45✔
4619
                return nil, err
×
4620
        }
×
4621
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
45✔
4622
        if err != nil {
45✔
4623
                return nil, fmt.Errorf("unable to generate node "+
×
4624
                        "signature for channel announcement: %w", err)
×
4625
        }
×
4626
        bitcoinSig, err := f.cfg.SignMessage(
45✔
4627
                localFundingKey.KeyLocator, chanAnnMsg, true,
45✔
4628
        )
45✔
4629
        if err != nil {
45✔
4630
                return nil, fmt.Errorf("unable to generate bitcoin "+
×
4631
                        "signature for node public key: %w", err)
×
4632
        }
×
4633

4634
        // Finally, we'll generate the announcement proof which we'll use to
4635
        // provide the other side with the necessary signatures required to
4636
        // allow them to reconstruct the full channel announcement.
4637
        proof := &lnwire.AnnounceSignatures1{
45✔
4638
                ChannelID:      chanID,
45✔
4639
                ShortChannelID: shortChanID,
45✔
4640
        }
45✔
4641
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
45✔
4642
        if err != nil {
45✔
4643
                return nil, err
×
4644
        }
×
4645
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
45✔
4646
        if err != nil {
45✔
4647
                return nil, err
×
4648
        }
×
4649

4650
        return &chanAnnouncement{
45✔
4651
                chanAnn:       chanAnn,
45✔
4652
                chanUpdateAnn: chanUpdateAnn,
45✔
4653
                chanProof:     proof,
45✔
4654
        }, nil
45✔
4655
}
4656

4657
// announceChannel announces a newly created channel to the rest of the network
4658
// by crafting the two authenticated announcements required for the peers on
4659
// the network to recognize the legitimacy of the channel. The crafted
4660
// announcements are then sent to the channel router to handle broadcasting to
4661
// the network during its next trickle.
4662
// This method is synchronous and will return when all the network requests
4663
// finish, either successfully or with an error.
4664
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4665
        localFundingKey *keychain.KeyDescriptor,
4666
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4667
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
19✔
4668

19✔
4669
        // First, we'll create the batch of announcements to be sent upon
19✔
4670
        // initial channel creation. This includes the channel announcement
19✔
4671
        // itself, the channel update announcement, and our half of the channel
19✔
4672
        // proof needed to fully authenticate the channel.
19✔
4673
        //
19✔
4674
        // We can pass in zeroes for the min and max htlc policy, because we
19✔
4675
        // only use the channel announcement message from the returned struct.
19✔
4676
        ann, err := f.newChanAnnouncement(
19✔
4677
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
19✔
4678
                shortChanID, chanID, 0, 0, nil, chanType,
19✔
4679
        )
19✔
4680
        if err != nil {
19✔
4681
                log.Errorf("can't generate channel announcement: %v", err)
×
4682
                return err
×
4683
        }
×
4684

4685
        // We only send the channel proof announcement and the node announcement
4686
        // because addToGraph previously sent the ChannelAnnouncement and
4687
        // the ChannelUpdate announcement messages. The channel proof and node
4688
        // announcements are broadcast to the greater network.
4689
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
19✔
4690
        select {
19✔
4691
        case err := <-errChan:
19✔
4692
                if err != nil {
22✔
4693
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4694
                                graph.ErrIgnored) {
3✔
4695

×
4696
                                log.Debugf("Graph rejected "+
×
4697
                                        "AnnounceSignatures: %v", err)
×
4698
                        } else {
3✔
4699
                                log.Errorf("Unable to send channel "+
3✔
4700
                                        "proof: %v", err)
3✔
4701
                                return err
3✔
4702
                        }
3✔
4703
                }
4704

4705
        case <-f.quit:
×
4706
                return ErrFundingManagerShuttingDown
×
4707
        }
4708

4709
        // Now that the channel is announced to the network, we will also
4710
        // obtain and send a node announcement. This is done since a node
4711
        // announcement is only accepted after a channel is known for that
4712
        // particular node, and this might be our first channel.
4713
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
19✔
4714
        if err != nil {
19✔
4715
                log.Errorf("can't generate node announcement: %v", err)
×
4716
                return err
×
4717
        }
×
4718

4719
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
19✔
4720
        select {
19✔
4721
        case err := <-errChan:
19✔
4722
                if err != nil {
22✔
4723
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4724
                                graph.ErrIgnored) {
6✔
4725

3✔
4726
                                log.Debugf("Graph rejected "+
3✔
4727
                                        "NodeAnnouncement1: %v", err)
3✔
4728
                        } else {
3✔
4729
                                log.Errorf("Unable to send node "+
×
4730
                                        "announcement: %v", err)
×
4731
                                return err
×
4732
                        }
×
4733
                }
4734

4735
        case <-f.quit:
×
4736
                return ErrFundingManagerShuttingDown
×
4737
        }
4738

4739
        return nil
19✔
4740
}
4741

4742
// InitFundingWorkflow sends a message to the funding manager instructing it
4743
// to initiate a single funder workflow with the source peer.
4744
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
60✔
4745
        f.fundingRequests <- msg
60✔
4746
}
60✔
4747

4748
// getUpfrontShutdownScript takes a user provided script and a getScript
4749
// function which can be used to generate an upfront shutdown script. If our
4750
// peer does not support the feature, this function will error if a non-zero
4751
// script was provided by the user, and return an empty script otherwise. If
4752
// our peer does support the feature, we will return the user provided script
4753
// if non-zero, or a freshly generated script if our node is configured to set
4754
// upfront shutdown scripts automatically.
4755
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4756
        script lnwire.DeliveryAddress,
4757
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4758
        error) {
113✔
4759

113✔
4760
        // Check whether the remote peer supports upfront shutdown scripts.
113✔
4761
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
113✔
4762
                lnwire.UpfrontShutdownScriptOptional,
113✔
4763
        )
113✔
4764

113✔
4765
        // If the peer does not support upfront shutdown scripts, and one has been
113✔
4766
        // provided, return an error because the feature is not supported.
113✔
4767
        if !remoteUpfrontShutdown && len(script) != 0 {
114✔
4768
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4769
        }
1✔
4770

4771
        // If the peer does not support upfront shutdown, return an empty address.
4772
        if !remoteUpfrontShutdown {
217✔
4773
                return nil, nil
105✔
4774
        }
105✔
4775

4776
        // If the user has provided an script and the peer supports the feature,
4777
        // return it. Note that user set scripts override the enable upfront
4778
        // shutdown flag.
4779
        if len(script) > 0 {
12✔
4780
                return script, nil
5✔
4781
        }
5✔
4782

4783
        // If we do not have setting of upfront shutdown script enabled, return
4784
        // an empty script.
4785
        if !enableUpfrontShutdown {
9✔
4786
                return nil, nil
4✔
4787
        }
4✔
4788

4789
        // We can safely send a taproot address iff, both sides have negotiated
4790
        // the shutdown-any-segwit feature.
4791
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4792
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4793

1✔
4794
        return getScript(taprootOK)
1✔
4795
}
4796

4797
// handleInitFundingMsg creates a channel reservation within the daemon's
4798
// wallet, then sends a funding request to the remote peer kicking off the
4799
// funding workflow.
4800
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
60✔
4801
        var (
60✔
4802
                peerKey        = msg.Peer.IdentityKey()
60✔
4803
                localAmt       = msg.LocalFundingAmt
60✔
4804
                baseFee        = msg.BaseFee
60✔
4805
                feeRate        = msg.FeeRate
60✔
4806
                minHtlcIn      = msg.MinHtlcIn
60✔
4807
                remoteCsvDelay = msg.RemoteCsvDelay
60✔
4808
                maxValue       = msg.MaxValueInFlight
60✔
4809
                maxHtlcs       = msg.MaxHtlcs
60✔
4810
                maxCSV         = msg.MaxLocalCsv
60✔
4811
                chanReserve    = msg.RemoteChanReserve
60✔
4812
                outpoints      = msg.Outpoints
60✔
4813
        )
60✔
4814

60✔
4815
        // If no maximum CSV delay was set for this channel, we use our default
60✔
4816
        // value.
60✔
4817
        if maxCSV == 0 {
120✔
4818
                maxCSV = f.cfg.MaxLocalCSVDelay
60✔
4819
        }
60✔
4820

4821
        log.Infof("Initiating fundingRequest(local_amt=%v "+
60✔
4822
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
60✔
4823
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
60✔
4824
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
60✔
4825

60✔
4826
        // We set the channel flags to indicate whether we want this channel to
60✔
4827
        // be announced to the network.
60✔
4828
        var channelFlags lnwire.FundingFlag
60✔
4829
        if !msg.Private {
115✔
4830
                // This channel will be announced.
55✔
4831
                channelFlags = lnwire.FFAnnounceChannel
55✔
4832
        }
55✔
4833

4834
        // If the caller specified their own channel ID, then we'll use that.
4835
        // Otherwise we'll generate a fresh one as normal.  This will be used
4836
        // to track this reservation throughout its lifetime.
4837
        var chanID PendingChanID
60✔
4838
        if msg.PendingChanID == zeroID {
120✔
4839
                chanID = f.nextPendingChanID()
60✔
4840
        } else {
63✔
4841
                // If the user specified their own pending channel ID, then
3✔
4842
                // we'll ensure it doesn't collide with any existing pending
3✔
4843
                // channel ID.
3✔
4844
                chanID = msg.PendingChanID
3✔
4845
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
3✔
4846
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4847
                                "already present", chanID[:])
×
4848
                        return
×
4849
                }
×
4850
        }
4851

4852
        // Check whether the peer supports upfront shutdown, and get an address
4853
        // which should be used (either a user specified address or a new
4854
        // address from the wallet if our node is configured to set shutdown
4855
        // address by default).
4856
        shutdown, err := getUpfrontShutdownScript(
60✔
4857
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
60✔
4858
                f.selectShutdownScript,
60✔
4859
        )
60✔
4860
        if err != nil {
60✔
4861
                msg.Err <- err
×
4862
                return
×
4863
        }
×
4864

4865
        // Initialize a funding reservation with the local wallet. If the
4866
        // wallet doesn't have enough funds to commit to this channel, then the
4867
        // request will fail, and be aborted.
4868
        //
4869
        // Before we init the channel, we'll also check to see what commitment
4870
        // format we can use with this peer. This is dependent on *both* us and
4871
        // the remote peer are signaling the proper feature bit.
4872
        chanType, commitType, err := negotiateCommitmentType(
60✔
4873
                msg.ChannelType, msg.Peer.LocalFeatures(),
60✔
4874
                msg.Peer.RemoteFeatures(),
60✔
4875
        )
60✔
4876
        if err != nil {
63✔
4877
                log.Errorf("channel type negotiation failed: %v", err)
3✔
4878
                msg.Err <- err
3✔
4879
                return
3✔
4880
        }
3✔
4881

4882
        var (
60✔
4883
                zeroConf bool
60✔
4884
                scid     bool
60✔
4885
        )
60✔
4886

60✔
4887
        if chanType != nil {
67✔
4888
                // Check if the returned chanType includes either the zero-conf
7✔
4889
                // or scid-alias bits.
7✔
4890
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
4891
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
4892
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
4893

7✔
4894
                // The option-scid-alias channel type for a public channel is
7✔
4895
                // disallowed.
7✔
4896
                if scid && !msg.Private {
7✔
4897
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4898
                                "public channel")
×
4899
                        log.Error(err)
×
4900
                        msg.Err <- err
×
4901

×
4902
                        return
×
4903
                }
×
4904
        }
4905

4906
        // First, we'll query the fee estimator for a fee that should get the
4907
        // commitment transaction confirmed by the next few blocks (conf target
4908
        // of 3). We target the near blocks here to ensure that we'll be able
4909
        // to execute a timely unilateral channel closure if needed.
4910
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
60✔
4911
        if err != nil {
60✔
4912
                msg.Err <- err
×
4913
                return
×
4914
        }
×
4915

4916
        // For anchor channels cap the initial commit fee rate at our defined
4917
        // maximum.
4918
        if commitType.HasAnchors() &&
60✔
4919
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
67✔
4920

7✔
4921
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
7✔
4922
        }
7✔
4923

4924
        var scidFeatureVal bool
60✔
4925
        if hasFeatures(
60✔
4926
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
60✔
4927
                lnwire.ScidAliasOptional,
60✔
4928
        ) {
66✔
4929

6✔
4930
                scidFeatureVal = true
6✔
4931
        }
6✔
4932

4933
        // At this point, if we have an AuxFundingController active, we'll check
4934
        // to see if we have a special tapscript root to use in our MuSig2
4935
        // funding output.
4936
        tapscriptRoot, err := fn.MapOptionZ(
60✔
4937
                f.cfg.AuxFundingController,
60✔
4938
                func(c AuxFundingController) AuxTapscriptResult {
60✔
4939
                        return c.DeriveTapscriptRoot(chanID)
×
4940
                },
×
4941
        ).Unpack()
4942
        if err != nil {
60✔
4943
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4944
                log.Error(err)
×
4945
                msg.Err <- err
×
4946

×
4947
                return
×
4948
        }
×
4949

4950
        req := &lnwallet.InitFundingReserveMsg{
60✔
4951
                ChainHash:         &msg.ChainHash,
60✔
4952
                PendingChanID:     chanID,
60✔
4953
                NodeID:            peerKey,
60✔
4954
                NodeAddr:          msg.Peer.Address(),
60✔
4955
                SubtractFees:      msg.SubtractFees,
60✔
4956
                LocalFundingAmt:   localAmt,
60✔
4957
                RemoteFundingAmt:  0,
60✔
4958
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
60✔
4959
                MinFundAmt:        msg.MinFundAmt,
60✔
4960
                RemoteChanReserve: chanReserve,
60✔
4961
                Outpoints:         outpoints,
60✔
4962
                CommitFeePerKw:    commitFeePerKw,
60✔
4963
                FundingFeePerKw:   msg.FundingFeePerKw,
60✔
4964
                PushMSat:          msg.PushAmt,
60✔
4965
                Flags:             channelFlags,
60✔
4966
                MinConfs:          msg.MinConfs,
60✔
4967
                CommitType:        commitType,
60✔
4968
                ChanFunder:        msg.ChanFunder,
60✔
4969
                // Unconfirmed Utxos which are marked by the sweeper subsystem
60✔
4970
                // are excluded from the coin selection because they are not
60✔
4971
                // final and can be RBFed by the sweeper subsystem.
60✔
4972
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
121✔
4973
                        // Utxos with at least 1 confirmation are safe to use
61✔
4974
                        // for channel openings because they don't bare the risk
61✔
4975
                        // of being replaced (BIP 125 RBF).
61✔
4976
                        if u.Confirmations > 0 {
64✔
4977
                                return true
3✔
4978
                        }
3✔
4979

4980
                        // Query the sweeper storage to make sure we don't use
4981
                        // an unconfirmed utxo still in use by the sweeper
4982
                        // subsystem.
4983
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
61✔
4984
                },
4985
                ZeroConf:         zeroConf,
4986
                OptionScidAlias:  scid,
4987
                ScidAliasFeature: scidFeatureVal,
4988
                Memo:             msg.Memo,
4989
                TapscriptRoot:    tapscriptRoot,
4990
        }
4991

4992
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
60✔
4993
        if err != nil {
63✔
4994
                msg.Err <- err
3✔
4995
                return
3✔
4996
        }
3✔
4997

4998
        if zeroConf {
65✔
4999
                // Store the alias for zero-conf channels in the underlying
5✔
5000
                // partial channel state.
5✔
5001
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
5002
                if err != nil {
5✔
5003
                        msg.Err <- err
×
5004
                        return
×
5005
                }
×
5006

5007
                reservation.AddAlias(aliasScid)
5✔
5008
        }
5009

5010
        // Set our upfront shutdown address in the existing reservation.
5011
        reservation.SetOurUpfrontShutdown(shutdown)
60✔
5012

60✔
5013
        // Now that we have successfully reserved funds for this channel in the
60✔
5014
        // wallet, we can fetch the final channel capacity. This is done at
60✔
5015
        // this point since the final capacity might change in case of
60✔
5016
        // SubtractFees=true.
60✔
5017
        capacity := reservation.Capacity()
60✔
5018

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

60✔
5022
        // If the remote CSV delay was not set in the open channel request,
60✔
5023
        // we'll use the RequiredRemoteDelay closure to compute the delay we
60✔
5024
        // require given the total amount of funds within the channel.
60✔
5025
        if remoteCsvDelay == 0 {
119✔
5026
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
59✔
5027
        }
59✔
5028

5029
        // If no minimum HTLC value was specified, use the default one.
5030
        if minHtlcIn == 0 {
119✔
5031
                minHtlcIn = f.cfg.DefaultMinHtlcIn
59✔
5032
        }
59✔
5033

5034
        // If no max value was specified, use the default one.
5035
        if maxValue == 0 {
119✔
5036
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
59✔
5037
        }
59✔
5038

5039
        if maxHtlcs == 0 {
120✔
5040
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
60✔
5041
        }
60✔
5042

5043
        // Once the reservation has been created, and indexed, queue a funding
5044
        // request to the remote peer, kicking off the funding workflow.
5045
        ourContribution := reservation.OurContribution()
60✔
5046

60✔
5047
        // Prepare the optional channel fee values from the initFundingMsg. If
60✔
5048
        // useBaseFee or useFeeRate are false the client did not provide fee
60✔
5049
        // values hence we assume default fee settings from the config.
60✔
5050
        forwardingPolicy := f.defaultForwardingPolicy(
60✔
5051
                ourContribution.ChannelStateBounds,
60✔
5052
        )
60✔
5053
        if baseFee != nil {
64✔
5054
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
4✔
5055
        }
4✔
5056

5057
        if feeRate != nil {
64✔
5058
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
4✔
5059
        }
4✔
5060

5061
        // Fetch our dust limit which is part of the default channel
5062
        // constraints, and log it.
5063
        ourDustLimit := ourContribution.DustLimit
60✔
5064

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

60✔
5067
        // If the channel reserve is not specified, then we calculate an
60✔
5068
        // appropriate amount here.
60✔
5069
        if chanReserve == 0 {
116✔
5070
                chanReserve = f.cfg.RequiredRemoteChanReserve(
56✔
5071
                        capacity, ourDustLimit,
56✔
5072
                )
56✔
5073
        }
56✔
5074

5075
        // If a pending channel map for this peer isn't already created, then
5076
        // we create one, ultimately allowing us to track this pending
5077
        // reservation within the target peer.
5078
        peerIDKey := newSerializedKey(peerKey)
60✔
5079
        f.resMtx.Lock()
60✔
5080
        if _, ok := f.activeReservations[peerIDKey]; !ok {
113✔
5081
                f.activeReservations[peerIDKey] = make(pendingChannels)
53✔
5082
        }
53✔
5083

5084
        resCtx := &reservationWithCtx{
60✔
5085
                chanAmt:           capacity,
60✔
5086
                forwardingPolicy:  *forwardingPolicy,
60✔
5087
                remoteCsvDelay:    remoteCsvDelay,
60✔
5088
                remoteMinHtlc:     minHtlcIn,
60✔
5089
                remoteMaxValue:    maxValue,
60✔
5090
                remoteMaxHtlcs:    maxHtlcs,
60✔
5091
                remoteChanReserve: chanReserve,
60✔
5092
                maxLocalCsv:       maxCSV,
60✔
5093
                channelType:       chanType,
60✔
5094
                reservation:       reservation,
60✔
5095
                peer:              msg.Peer,
60✔
5096
                updates:           msg.Updates,
60✔
5097
                err:               msg.Err,
60✔
5098
        }
60✔
5099
        f.activeReservations[peerIDKey][chanID] = resCtx
60✔
5100
        f.resMtx.Unlock()
60✔
5101

60✔
5102
        // Update the timestamp once the InitFundingMsg has been handled.
60✔
5103
        defer resCtx.updateTimestamp()
60✔
5104

60✔
5105
        // Check the sanity of the selected channel constraints.
60✔
5106
        bounds := &channeldb.ChannelStateBounds{
60✔
5107
                ChanReserve:      chanReserve,
60✔
5108
                MaxPendingAmount: maxValue,
60✔
5109
                MinHTLC:          minHtlcIn,
60✔
5110
                MaxAcceptedHtlcs: maxHtlcs,
60✔
5111
        }
60✔
5112
        commitParams := &channeldb.CommitmentParams{
60✔
5113
                DustLimit: ourDustLimit,
60✔
5114
                CsvDelay:  remoteCsvDelay,
60✔
5115
        }
60✔
5116
        err = lnwallet.VerifyConstraints(
60✔
5117
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
60✔
5118
        )
60✔
5119
        if err != nil {
62✔
5120
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
2✔
5121
                if reserveErr != nil {
2✔
5122
                        log.Errorf("unable to cancel reservation: %v",
×
5123
                                reserveErr)
×
5124
                }
×
5125

5126
                msg.Err <- err
2✔
5127
                return
2✔
5128
        }
5129

5130
        // When opening a script enforced channel lease, include the required
5131
        // expiry TLV record in our proposal.
5132
        var leaseExpiry *lnwire.LeaseExpiry
58✔
5133
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
61✔
5134
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5135
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5136
        }
3✔
5137

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

58✔
5141
        reservation.SetState(lnwallet.SentOpenChannel)
58✔
5142

58✔
5143
        fundingOpen := lnwire.OpenChannel{
58✔
5144
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
58✔
5145
                PendingChannelID:      chanID,
58✔
5146
                FundingAmount:         capacity,
58✔
5147
                PushAmount:            msg.PushAmt,
58✔
5148
                DustLimit:             ourDustLimit,
58✔
5149
                MaxValueInFlight:      maxValue,
58✔
5150
                ChannelReserve:        chanReserve,
58✔
5151
                HtlcMinimum:           minHtlcIn,
58✔
5152
                FeePerKiloWeight:      uint32(commitFeePerKw),
58✔
5153
                CsvDelay:              remoteCsvDelay,
58✔
5154
                MaxAcceptedHTLCs:      maxHtlcs,
58✔
5155
                FundingKey:            ourContribution.MultiSigKey.PubKey,
58✔
5156
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
58✔
5157
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
58✔
5158
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
58✔
5159
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
58✔
5160
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
58✔
5161
                ChannelFlags:          channelFlags,
58✔
5162
                UpfrontShutdownScript: shutdown,
58✔
5163
                ChannelType:           chanType,
58✔
5164
                LeaseExpiry:           leaseExpiry,
58✔
5165
        }
58✔
5166

58✔
5167
        if commitType.IsTaproot() {
63✔
5168
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
5169
                        ourContribution.LocalNonce.PubNonce,
5✔
5170
                )
5✔
5171
        }
5✔
5172

5173
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
58✔
5174
                e := fmt.Errorf("unable to send funding request message: %w",
×
5175
                        err)
×
5176
                log.Errorf(e.Error())
×
5177

×
5178
                // Since we were unable to send the initial message to the peer
×
5179
                // and start the funding flow, we'll cancel this reservation.
×
5180
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5181
                if err != nil {
×
5182
                        log.Errorf("unable to cancel reservation: %v", err)
×
5183
                }
×
5184

5185
                msg.Err <- e
×
5186
                return
×
5187
        }
5188
}
5189

5190
// handleWarningMsg processes the warning which was received from remote peer.
5191
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
44✔
5192
        log.Warnf("received warning message from peer %x: %v",
44✔
5193
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
44✔
5194
}
44✔
5195

5196
// handleErrorMsg processes the error which was received from remote peer,
5197
// depending on the type of error we should do different clean up steps and
5198
// inform the user about it.
5199
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
3✔
5200
        chanID := msg.ChanID
3✔
5201
        peerKey := peer.IdentityKey()
3✔
5202

3✔
5203
        // First, we'll attempt to retrieve and cancel the funding workflow
3✔
5204
        // that this error was tied to. If we're unable to do so, then we'll
3✔
5205
        // exit early as this was an unwarranted error.
3✔
5206
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
3✔
5207
        if err != nil {
3✔
5208
                log.Warnf("Received error for non-existent funding "+
×
5209
                        "flow: %v (%v)", err, msg.Error())
×
5210
                return
×
5211
        }
×
5212

5213
        // If we did indeed find the funding workflow, then we'll return the
5214
        // error back to the caller (if any), and cancel the workflow itself.
5215
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5216
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5217
        )
3✔
5218
        log.Errorf(fundingErr.Error())
3✔
5219

3✔
5220
        // If this was a PSBT funding flow, the remote likely timed out because
3✔
5221
        // we waited too long. Return a nice error message to the user in that
3✔
5222
        // case so the user knows what's the problem.
3✔
5223
        if resCtx.reservation.IsPsbt() {
6✔
5224
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
3✔
5225
                        fundingErr)
3✔
5226
        }
3✔
5227

5228
        resCtx.err <- fundingErr
3✔
5229
}
5230

5231
// pruneZombieReservations loops through all pending reservations and fails the
5232
// funding flow for any reservations that have not been updated since the
5233
// ReservationTimeout and are not locked waiting for the funding transaction.
5234
func (f *Manager) pruneZombieReservations() {
6✔
5235
        zombieReservations := make(pendingChannels)
6✔
5236

6✔
5237
        f.resMtx.RLock()
6✔
5238
        for _, pendingReservations := range f.activeReservations {
12✔
5239
                for pendingChanID, resCtx := range pendingReservations {
12✔
5240
                        if resCtx.isLocked() {
6✔
5241
                                continue
×
5242
                        }
5243

5244
                        // We don't want to expire PSBT funding reservations.
5245
                        // These reservations are always initiated by us and the
5246
                        // remote peer is likely going to cancel them after some
5247
                        // idle time anyway. So no need for us to also prune
5248
                        // them.
5249
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
6✔
5250
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
6✔
5251
                        if !resCtx.reservation.IsPsbt() && isExpired {
12✔
5252
                                zombieReservations[pendingChanID] = resCtx
6✔
5253
                        }
6✔
5254
                }
5255
        }
5256
        f.resMtx.RUnlock()
6✔
5257

6✔
5258
        for pendingChanID, resCtx := range zombieReservations {
12✔
5259
                err := fmt.Errorf("reservation timed out waiting for peer "+
6✔
5260
                        "(peer_id:%x, chan_id:%x)",
6✔
5261
                        resCtx.peer.IdentityKey().SerializeCompressed(),
6✔
5262
                        pendingChanID[:])
6✔
5263
                log.Warnf(err.Error())
6✔
5264

6✔
5265
                chanID := lnwire.NewChanIDFromOutPoint(
6✔
5266
                        *resCtx.reservation.FundingOutpoint(),
6✔
5267
                )
6✔
5268

6✔
5269
                // Create channel identifier and set the channel ID.
6✔
5270
                cid := newChanIdentifier(pendingChanID)
6✔
5271
                cid.setChanID(chanID)
6✔
5272

6✔
5273
                f.failFundingFlow(resCtx.peer, cid, err)
6✔
5274
        }
6✔
5275
}
5276

5277
// cancelReservationCtx does all needed work in order to securely cancel the
5278
// reservation.
5279
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5280
        pendingChanID PendingChanID,
5281
        byRemote bool) (*reservationWithCtx, error) {
26✔
5282

26✔
5283
        log.Infof("Cancelling funding reservation for node_key=%x, "+
26✔
5284
                "chan_id=%x", peerKey.SerializeCompressed(), pendingChanID[:])
26✔
5285

26✔
5286
        peerIDKey := newSerializedKey(peerKey)
26✔
5287
        f.resMtx.Lock()
26✔
5288
        defer f.resMtx.Unlock()
26✔
5289

26✔
5290
        nodeReservations, ok := f.activeReservations[peerIDKey]
26✔
5291
        if !ok {
36✔
5292
                // No reservations for this node.
10✔
5293
                return nil, fmt.Errorf("no active reservations for peer(%x)",
10✔
5294
                        peerIDKey[:])
10✔
5295
        }
10✔
5296

5297
        ctx, ok := nodeReservations[pendingChanID]
19✔
5298
        if !ok {
21✔
5299
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
2✔
5300
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5301
        }
2✔
5302

5303
        // If the reservation was a PSBT funding flow and it was canceled by the
5304
        // remote peer, then we need to thread through a different error message
5305
        // to the subroutine that's waiting for the user input so it can return
5306
        // a nice error message to the user.
5307
        if ctx.reservation.IsPsbt() && byRemote {
20✔
5308
                ctx.reservation.RemoteCanceled()
3✔
5309
        }
3✔
5310

5311
        if err := ctx.reservation.Cancel(); err != nil {
17✔
5312
                return nil, fmt.Errorf("unable to cancel reservation: %w", err)
×
5313
        }
×
5314

5315
        delete(nodeReservations, pendingChanID)
17✔
5316

17✔
5317
        // If this was the last active reservation for this peer, delete the
17✔
5318
        // peer's entry altogether.
17✔
5319
        if len(nodeReservations) == 0 {
34✔
5320
                delete(f.activeReservations, peerIDKey)
17✔
5321
        }
17✔
5322
        return ctx, nil
17✔
5323
}
5324

5325
// deleteReservationCtx deletes the reservation uniquely identified by the
5326
// target public key of the peer, and the specified pending channel ID.
5327
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5328
        pendingChanID PendingChanID) {
59✔
5329

59✔
5330
        peerIDKey := newSerializedKey(peerKey)
59✔
5331
        f.resMtx.Lock()
59✔
5332
        defer f.resMtx.Unlock()
59✔
5333

59✔
5334
        nodeReservations, ok := f.activeReservations[peerIDKey]
59✔
5335
        if !ok {
59✔
5336
                // No reservations for this node.
×
5337
                return
×
5338
        }
×
5339
        delete(nodeReservations, pendingChanID)
59✔
5340

59✔
5341
        // If this was the last active reservation for this peer, delete the
59✔
5342
        // peer's entry altogether.
59✔
5343
        if len(nodeReservations) == 0 {
111✔
5344
                delete(f.activeReservations, peerIDKey)
52✔
5345
        }
52✔
5346
}
5347

5348
// getReservationCtx returns the reservation context for a particular pending
5349
// channel ID for a target peer.
5350
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5351
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
94✔
5352

94✔
5353
        peerIDKey := newSerializedKey(peerKey)
94✔
5354
        f.resMtx.RLock()
94✔
5355
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
94✔
5356
        f.resMtx.RUnlock()
94✔
5357

94✔
5358
        if !ok {
97✔
5359
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
3✔
5360
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5361
        }
3✔
5362

5363
        return resCtx, nil
94✔
5364
}
5365

5366
// IsPendingChannel returns a boolean indicating whether the channel identified
5367
// by the pendingChanID and given peer is pending, meaning it is in the process
5368
// of being funded. After the funding transaction has been confirmed, the
5369
// channel will receive a new, permanent channel ID, and will no longer be
5370
// considered pending.
5371
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5372
        peer lnpeer.Peer) bool {
3✔
5373

3✔
5374
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5375
        f.resMtx.RLock()
3✔
5376
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5377
        f.resMtx.RUnlock()
3✔
5378

3✔
5379
        return ok
3✔
5380
}
3✔
5381

5382
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
388✔
5383
        var tmp btcec.JacobianPoint
388✔
5384
        pub.AsJacobian(&tmp)
388✔
5385
        tmp.ToAffine()
388✔
5386
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
388✔
5387
}
388✔
5388

5389
// defaultForwardingPolicy returns the default forwarding policy based on the
5390
// default routing policy and our local channel constraints.
5391
func (f *Manager) defaultForwardingPolicy(
5392
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
107✔
5393

107✔
5394
        return &models.ForwardingPolicy{
107✔
5395
                MinHTLCOut:    bounds.MinHTLC,
107✔
5396
                MaxHTLC:       bounds.MaxPendingAmount,
107✔
5397
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
107✔
5398
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
107✔
5399
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
107✔
5400
        }
107✔
5401
}
107✔
5402

5403
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5404
// chanPoint in the channelOpeningStateBucket.
5405
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5406
        forwardingPolicy *models.ForwardingPolicy) error {
72✔
5407

72✔
5408
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
72✔
5409
                chanID, forwardingPolicy,
72✔
5410
        )
72✔
5411
}
72✔
5412

5413
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5414
// channel id from the database which will be applied during the channel
5415
// announcement phase.
5416
func (f *Manager) getInitialForwardingPolicy(
5417
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
97✔
5418

97✔
5419
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
97✔
5420
}
97✔
5421

5422
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5423
// the database.
5424
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
27✔
5425
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
27✔
5426
}
27✔
5427

5428
// saveChannelOpeningState saves the channelOpeningState for the provided
5429
// chanPoint to the channelOpeningStateBucket.
5430
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5431
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
95✔
5432

95✔
5433
        var outpointBytes bytes.Buffer
95✔
5434
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
95✔
5435
                return err
×
5436
        }
×
5437

5438
        // Save state and the uint64 representation of the shortChanID
5439
        // for later use.
5440
        scratch := make([]byte, 10)
95✔
5441
        byteOrder.PutUint16(scratch[:2], uint16(state))
95✔
5442
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
95✔
5443

95✔
5444
        return f.cfg.ChannelDB.SaveChannelOpeningState(
95✔
5445
                outpointBytes.Bytes(), scratch,
95✔
5446
        )
95✔
5447
}
5448

5449
// getChannelOpeningState fetches the channelOpeningState for the provided
5450
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5451
// is not found.
5452
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5453
        channelOpeningState, *lnwire.ShortChannelID, error) {
257✔
5454

257✔
5455
        var outpointBytes bytes.Buffer
257✔
5456
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
257✔
5457
                return 0, nil, err
×
5458
        }
×
5459

5460
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
257✔
5461
                outpointBytes.Bytes(),
257✔
5462
        )
257✔
5463
        if err != nil {
309✔
5464
                return 0, nil, err
52✔
5465
        }
52✔
5466

5467
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
208✔
5468
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
208✔
5469
        return state, &shortChanID, nil
208✔
5470
}
5471

5472
// deleteChannelOpeningState removes any state for chanPoint from the database.
5473
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
27✔
5474
        var outpointBytes bytes.Buffer
27✔
5475
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
27✔
5476
                return err
×
5477
        }
×
5478

5479
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
27✔
5480
                outpointBytes.Bytes(),
27✔
5481
        )
27✔
5482
}
5483

5484
// selectShutdownScript selects the shutdown script we should send to the peer.
5485
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5486
// script.
5487
func (f *Manager) selectShutdownScript(taprootOK bool,
5488
) (lnwire.DeliveryAddress, error) {
×
5489

×
5490
        addrType := lnwallet.WitnessPubKey
×
5491
        if taprootOK {
×
5492
                addrType = lnwallet.TaprootPubkey
×
5493
        }
×
5494

5495
        addr, err := f.cfg.Wallet.NewAddress(
×
5496
                addrType, false, lnwallet.DefaultAccountName,
×
5497
        )
×
5498
        if err != nil {
×
5499
                return nil, err
×
5500
        }
×
5501

5502
        return txscript.PayToAddrScript(addr)
×
5503
}
5504

5505
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5506
// and then returns the online peer.
5507
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5508
        error) {
108✔
5509

108✔
5510
        peerChan := make(chan lnpeer.Peer, 1)
108✔
5511

108✔
5512
        var peerKey [33]byte
108✔
5513
        copy(peerKey[:], peerPubkey.SerializeCompressed())
108✔
5514

108✔
5515
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
108✔
5516

108✔
5517
        var peer lnpeer.Peer
108✔
5518
        select {
108✔
5519
        case peer = <-peerChan:
107✔
5520
        case <-f.quit:
1✔
5521
                return peer, ErrFundingManagerShuttingDown
1✔
5522
        }
5523
        return peer, nil
107✔
5524
}
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