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

lightningnetwork / lnd / 18016273007

25 Sep 2025 05:55PM UTC coverage: 54.653% (-12.0%) from 66.622%
18016273007

Pull #10248

github

web-flow
Merge 128443298 into b09b20c69
Pull Request #10248: Enforce TLV when creating a Route

25 of 30 new or added lines in 4 files covered. (83.33%)

23906 existing lines in 281 files now uncovered.

109536 of 200421 relevant lines covered (54.65%)

21816.97 hits per line

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

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

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

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

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

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

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

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

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

102
        msgBufferSize = 50
103

104
        // 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 {
3✔
174
        r.updateMtx.RLock()
3✔
175
        defer r.updateMtx.RUnlock()
3✔
176

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

398
        // CurrentNodeAnnouncement should return the latest, fully signed node
399
        // announcement from the backing Lightning Network node with a fresh
400
        // timestamp.
401
        CurrentNodeAnnouncement func() (lnwire.NodeAnnouncement, error)
402

403
        // SendAnnouncement is used by the FundingManager to send announcement
404
        // messages to the Gossiper to possibly broadcast to the greater
405
        // network. A set of optional message fields can be provided to populate
406
        // any information within the graph that is not included in the gossip
407
        // message.
408
        SendAnnouncement func(msg lnwire.Message,
409
                optionalFields ...discovery.OptionalMsgField) chan error
410

411
        // NotifyWhenOnline allows the FundingManager to register with a
412
        // subsystem that will notify it when the peer comes online. This is
413
        // used when sending the channelReady message, since it MUST be
414
        // delivered after the funding transaction is confirmed.
415
        //
416
        // NOTE: The peerChan channel must be buffered.
417
        NotifyWhenOnline func(peer [33]byte, peerChan chan<- lnpeer.Peer)
418

419
        // FindChannel queries the database for the channel with the given
420
        // channel ID. Providing the node's public key is an optimization that
421
        // prevents deserializing and scanning through all possible channels.
422
        FindChannel func(node *btcec.PublicKey,
423
                chanID lnwire.ChannelID) (*channeldb.OpenChannel, error)
424

425
        // TempChanIDSeed is a cryptographically random string of bytes that's
426
        // used as a seed to generate pending channel ID's.
427
        TempChanIDSeed [32]byte
428

429
        // DefaultRoutingPolicy is the default routing policy used when
430
        // initially announcing channels.
431
        DefaultRoutingPolicy models.ForwardingPolicy
432

433
        // DefaultMinHtlcIn is the default minimum incoming htlc value that is
434
        // set as a channel parameter.
435
        DefaultMinHtlcIn lnwire.MilliSatoshi
436

437
        // NumRequiredConfs is a function closure that helps the funding
438
        // manager decide how many confirmations it should require for a
439
        // channel extended to it. The function is able to take into account
440
        // the amount of the channel, and any funds we'll be pushed in the
441
        // process to determine how many confirmations we'll require.
442
        NumRequiredConfs func(btcutil.Amount, lnwire.MilliSatoshi) uint16
443

444
        // RequiredRemoteDelay is a function that maps the total amount in a
445
        // proposed channel to the CSV delay that we'll require for the remote
446
        // party. Naturally a larger channel should require a higher CSV delay
447
        // in order to give us more time to claim funds in the case of a
448
        // contract breach.
449
        RequiredRemoteDelay func(btcutil.Amount) uint16
450

451
        // RequiredRemoteChanReserve is a function closure that, given the
452
        // channel capacity and dust limit, will return an appropriate amount
453
        // for the remote peer's required channel reserve that is to be adhered
454
        // to at all times.
455
        RequiredRemoteChanReserve func(capacity,
456
                dustLimit btcutil.Amount) btcutil.Amount
457

458
        // RequiredRemoteMaxValue is a function closure that, given the channel
459
        // capacity, returns the amount of MilliSatoshis that our remote peer
460
        // can have in total outstanding HTLCs with us.
461
        RequiredRemoteMaxValue func(btcutil.Amount) lnwire.MilliSatoshi
462

463
        // RequiredRemoteMaxHTLCs is a function closure that, given the channel
464
        // capacity, returns the number of maximum HTLCs the remote peer can
465
        // offer us.
466
        RequiredRemoteMaxHTLCs func(btcutil.Amount) uint16
467

468
        // WatchNewChannel is to be called once a new channel enters the final
469
        // funding stage: waiting for on-chain confirmation. This method sends
470
        // the channel to the ChainArbitrator so it can watch for any on-chain
471
        // events related to the channel. We also provide the public key of the
472
        // node we're establishing a channel with for reconnection purposes.
473
        WatchNewChannel func(*channeldb.OpenChannel, *btcec.PublicKey) error
474

475
        // ReportShortChanID allows the funding manager to report the confirmed
476
        // short channel ID of a formerly pending zero-conf channel to outside
477
        // sub-systems.
478
        ReportShortChanID func(wire.OutPoint) error
479

480
        // ZombieSweeperInterval is the periodic time interval in which the
481
        // zombie sweeper is run.
482
        ZombieSweeperInterval time.Duration
483

484
        // ReservationTimeout is the length of idle time that must pass before
485
        // a reservation is considered a zombie.
486
        ReservationTimeout time.Duration
487

488
        // MinChanSize is the smallest channel size that we'll accept as an
489
        // inbound channel. We have such a parameter, as otherwise, nodes could
490
        // flood us with very small channels that would never really be usable
491
        // due to fees.
492
        MinChanSize btcutil.Amount
493

494
        // MaxChanSize is the largest channel size that we'll accept as an
495
        // inbound channel. We have such a parameter, so that you may decide how
496
        // WUMBO you would like your channel.
497
        MaxChanSize btcutil.Amount
498

499
        // MaxPendingChannels is the maximum number of pending channels we
500
        // allow for each peer.
501
        MaxPendingChannels int
502

503
        // RejectPush is set true if the fundingmanager should reject any
504
        // incoming channels having a non-zero push amount.
505
        RejectPush bool
506

507
        // MaxLocalCSVDelay is the maximum csv delay we will allow for our
508
        // commit output. Channels that exceed this value will be failed.
509
        MaxLocalCSVDelay uint16
510

511
        // NotifyOpenChannelEvent informs the ChannelNotifier when channels
512
        // transition from pending open to open.
513
        NotifyOpenChannelEvent func(wire.OutPoint, *btcec.PublicKey)
514

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

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

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

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

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

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

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

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

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

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

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

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

572
        // 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

UNCOV
671
func (c channelOpeningState) String() string {
×
UNCOV
672
        switch c {
×
UNCOV
673
        case markedOpen:
×
UNCOV
674
                return "markedOpen"
×
UNCOV
675
        case channelReadySent:
×
UNCOV
676
                return "channelReadySent"
×
UNCOV
677
        case addedToGraph:
×
UNCOV
678
                return "addedToGraph"
×
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) {
109✔
687
        return &Manager{
109✔
688
                cfg:       &cfg,
109✔
689
                chanIDKey: cfg.TempChanIDSeed,
109✔
690
                activeReservations: make(
109✔
691
                        map[serializedPubKey]pendingChannels,
109✔
692
                ),
109✔
693
                signedReservations: make(
109✔
694
                        map[lnwire.ChannelID][32]byte,
109✔
695
                ),
109✔
696
                fundingMsgs: make(
109✔
697
                        chan *fundingMsg, msgBufferSize,
109✔
698
                ),
109✔
699
                fundingRequests: make(
109✔
700
                        chan *InitFundingMsg, msgBufferSize,
109✔
701
                ),
109✔
702
                localDiscoverySignals: &lnutils.SyncMap[
109✔
703
                        lnwire.ChannelID, chan struct{},
109✔
704
                ]{},
109✔
705
                handleChannelReadyBarriers: &lnutils.SyncMap[
109✔
706
                        lnwire.ChannelID, struct{},
109✔
707
                ]{},
109✔
708
                pendingMusigNonces: make(
109✔
709
                        map[lnwire.ChannelID]*musig2.Nonces,
109✔
710
                ),
109✔
711
                quit: make(chan struct{}),
109✔
712
        }, nil
109✔
713
}
109✔
714

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

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

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

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

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

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

1✔
762
                                f.rebroadcastFundingTx(channel)
1✔
763
                        }
1✔
764
                } else if channel.ChanType.IsSingleFunder() &&
8✔
765
                        channel.ChanType.HasFundingTx() &&
8✔
766
                        channel.IsZeroConf() && channel.IsInitiator &&
8✔
767
                        !channel.ZeroConfConfirmed() {
10✔
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)
9✔
780
                go f.advanceFundingState(channel, chanID, nil)
9✔
781
        }
782

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

109✔
786
        return nil
109✔
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 {
106✔
792
        f.stopped.Do(func() {
211✔
793
                log.Info("Funding manager shutting down...")
105✔
794
                defer log.Debug("Funding manager shutdown complete")
105✔
795

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

800
        return nil
106✔
801
}
802

803
// rebroadcastFundingTx publishes the funding tx on startup for each
804
// unconfirmed channel.
805
func (f *Manager) rebroadcastFundingTx(c *channeldb.OpenChannel) {
3✔
806
        var fundingTxBuf bytes.Buffer
3✔
807
        err := c.FundingTxn.Serialize(&fundingTxBuf)
3✔
808
        if err != nil {
3✔
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 {
3✔
817
                log.Debugf("Rebroadcasting funding tx for ChannelPoint(%v): "+
3✔
818
                        "%x", c.FundingOutpoint, fundingTxBuf.Bytes())
3✔
819
        }
3✔
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)
3✔
824

3✔
825
        err = f.cfg.PublishTransaction(c.FundingTxn, label)
3✔
826
        if err != nil {
3✔
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 {
57✔
840
        // Obtain a fresh nonce. We do this by encoding the incremented nonce.
57✔
841
        nextNonce := f.chanIDNonce.Add(1)
57✔
842

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

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

57✔
856
        return nextChanID
57✔
857
}
57✔
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.
UNCOV
862
func (f *Manager) CancelPeerReservations(nodePub [33]byte) {
×
UNCOV
863
        log.Debugf("Cancelling all reservations for peer %x", nodePub[:])
×
UNCOV
864

×
UNCOV
865
        f.resMtx.Lock()
×
UNCOV
866
        defer f.resMtx.Unlock()
×
UNCOV
867

×
UNCOV
868
        // We'll attempt to look up this node in the set of active
×
UNCOV
869
        // reservations.  If they don't have any, then there's no further work
×
UNCOV
870
        // to be done.
×
UNCOV
871
        nodeReservations, ok := f.activeReservations[nodePub]
×
UNCOV
872
        if !ok {
×
UNCOV
873
                log.Debugf("No active reservations for node: %x", nodePub[:])
×
UNCOV
874
                return
×
UNCOV
875
        }
×
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 {
148✔
920
        return &chanIdentifier{
148✔
921
                tempChanID: tempChanID,
148✔
922
        }
148✔
923
}
148✔
924

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

931
// hasChanID returns true if the active channel ID has been set.
932
func (c *chanIdentifier) hasChanID() bool {
21✔
933
        return c.chanIDSet
21✔
934
}
21✔
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) {
21✔
945

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

21✔
949
        // First, notify Brontide to remove the pending channel.
21✔
950
        //
21✔
951
        // NOTE: depending on where we fail the flow, we may not have the
21✔
952
        // active channel ID yet.
21✔
953
        if cid.hasChanID() {
26✔
954
                err := peer.RemovePendingChannel(cid.chanID)
5✔
955
                if err != nil {
5✔
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(
21✔
963
                peer.IdentityKey(), cid.tempChanID, false,
21✔
964
        )
21✔
965
        if err != nil {
30✔
966
                log.Errorf("unable to cancel reservation: %v", err)
9✔
967
        }
9✔
968

969
        // In case the case where the reservation existed, send the funding
970
        // error on the error channel.
971
        if ctx != nil {
33✔
972
                ctx.err <- fundingErr
12✔
973
        }
12✔
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
21✔
978
        switch e := fundingErr.(type) {
21✔
979
        // Let the actual error message be sent to the remote for the
980
        // whitelisted types.
981
        case lnwallet.ReservationError:
5✔
982
                msg = lnwire.ErrorData(e.Error())
5✔
983
        case lnwire.FundingError:
4✔
984
                msg = lnwire.ErrorData(e.Error())
4✔
UNCOV
985
        case chanacceptor.ChanAcceptError:
×
UNCOV
986
                msg = lnwire.ErrorData(e.Error())
×
987

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

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

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

21✔
1002
        if err := peer.SendMessage(false, errMsg); err != nil {
21✔
1003
                log.Errorf("unable to send error message to peer %v", err)
×
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() {
109✔
1034
        defer f.wg.Done()
109✔
1035

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

109✔
1039
        for {
490✔
1040
                select {
381✔
1041
                case fmsg := <-f.fundingMsgs:
215✔
1042
                        switch msg := fmsg.msg.(type) {
215✔
1043
                        case *lnwire.OpenChannel:
54✔
1044
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
54✔
1045

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

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

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

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

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

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

UNCOV
1068
                case <-zombieSweepTicker.C:
×
UNCOV
1069
                        f.pruneZombieReservations()
×
1070

1071
                case <-f.quit:
105✔
1072
                        return
105✔
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) {
65✔
1088

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

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

1103
        var chanOpts []lnwallet.ChannelOpt
42✔
1104
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
84✔
1105
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
42✔
1106
        })
42✔
1107
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
84✔
1108
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
42✔
1109
        })
42✔
1110
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
42✔
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(
42✔
1116
                nil, channel, nil, chanOpts...,
42✔
1117
        )
42✔
1118
        if err != nil {
42✔
1119
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1120
                        channel.FundingOutpoint, err)
×
1121
                return
×
1122
        }
×
1123

1124
        for {
189✔
1125
                channelState, shortChanID, err := f.getChannelOpeningState(
147✔
1126
                        &channel.FundingOutpoint,
147✔
1127
                )
147✔
1128
                if err == channeldb.ErrChannelNotFound {
172✔
1129
                        // Channel not in fundingManager's opening database,
25✔
1130
                        // meaning it was successfully announced to the
25✔
1131
                        // network.
25✔
1132
                        // TODO(halseth): could do graph consistency check
25✔
1133
                        // here, and re-add the edge if missing.
25✔
1134
                        log.Debugf("ChannelPoint(%v) with chan_id=%x not "+
25✔
1135
                                "found in opening database, assuming already "+
25✔
1136
                                "announced to the network",
25✔
1137
                                channel.FundingOutpoint, pendingChanID)
25✔
1138
                        return
25✔
1139
                } else if err != nil {
147✔
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(
122✔
1151
                        channel, lnChannel, shortChanID, pendingChanID,
122✔
1152
                        channelState, updateChan,
122✔
1153
                )
122✔
1154
                if err != nil {
139✔
1155
                        log.Errorf("Unable to advance state(%v): %v",
17✔
1156
                                channel.FundingOutpoint, err)
17✔
1157
                        return
17✔
1158
                }
17✔
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 {
122✔
1171

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

122✔
1176
        switch channelState {
122✔
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:
35✔
1180
                err := f.sendChannelReady(channel, lnChannel)
35✔
1181
                if err != nil {
36✔
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(
34✔
1191
                        &channel.FundingOutpoint, channelReadySent,
34✔
1192
                        shortChanID,
34✔
1193
                )
34✔
1194
                if err != nil {
34✔
1195
                        return fmt.Errorf("error setting channel state to"+
×
1196
                                " channelReadySent: %w", err)
×
1197
                }
×
1198

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

34✔
1202
                return nil
34✔
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:
59✔
1207
                // We must wait until we've received the peer's channel_ready
59✔
1208
                // before sending a channel_update according to BOLT#07.
59✔
1209
                received, err := f.receivedChannelReady(
59✔
1210
                        channel.IdentityPub, chanID,
59✔
1211
                )
59✔
1212
                if err != nil {
59✔
1213
                        return fmt.Errorf("failed to check if channel_ready "+
×
1214
                                "was received: %v", err)
×
1215
                }
×
1216

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

1227
                        return nil
23✔
1228
                }
1229

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

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

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

1253
                err := f.annAfterSixConfs(channel, shortChanID)
26✔
1254
                if err != nil {
28✔
1255
                        return fmt.Errorf("error sending channel "+
2✔
1256
                                "announcement: %v", err)
2✔
1257
                }
2✔
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)
24✔
1265
                if err != nil {
24✔
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)
24✔
1275
                if err != nil {
24✔
1276
                        log.Infof("Could not delete initial policy for chanId "+
×
1277
                                "%x", chanID)
×
1278
                }
×
1279

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

24✔
1283
                return nil
24✔
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 {
57✔
1293

57✔
1294
        if channel.IsZeroConf() {
61✔
1295
                // Persist the alias to the alias database.
4✔
1296
                baseScid := channel.ShortChannelID
4✔
1297
                err := f.cfg.AliasManager.AddLocalAlias(
4✔
1298
                        baseScid, baseScid, true, false,
4✔
1299
                )
4✔
1300
                if err != nil {
4✔
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(
4✔
1310
                        &channel.FundingOutpoint, markedOpen,
4✔
1311
                        &channel.ShortChannelID,
4✔
1312
                )
4✔
1313
                if err != nil {
4✔
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)
4✔
1321
                if err != nil {
4✔
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(
4✔
1329
                        channel.FundingOutpoint, channel.IdentityPub,
4✔
1330
                )
4✔
1331

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

1340
                return nil
4✔
1341
        }
1342

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

1352
        if blockchain.IsCoinBaseTx(confChannel.fundingTx) {
32✔
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)
30✔
1401
        log.Debugf("ChannelID(%v) is now fully confirmed! "+
30✔
1402
                "(shortChanID=%v)", chanID, confChannel.shortChanID)
30✔
1403

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

1411
        return nil
30✔
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) {
216✔
1417
        select {
216✔
1418
        case f.fundingMsgs <- &fundingMsg{msg, peer}:
216✔
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) {
54✔
1434

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

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

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

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

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

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

1470
        for _, c := range channels {
66✔
1471
                // Pending channels that have a non-zero thaw height were also
12✔
1472
                // created through a canned funding shim. Those also don't
12✔
1473
                // count towards the DoS protection limit.
12✔
1474
                //
12✔
1475
                // TODO(guggero): Properly store the funding type (wallet, shim,
12✔
1476
                // PSBT) on the channel so we don't need to use the thaw height.
12✔
1477
                if c.IsPending && c.ThawHeight == 0 {
20✔
1478
                        numPending++
8✔
1479
                }
8✔
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 {
58✔
1485
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
4✔
1486

4✔
1487
                return
4✔
1488
        }
4✔
1489

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

1497
        if len(pendingChans) > pendingChansLimit {
50✔
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()
50✔
1506
        if err != nil || !isSynced {
50✔
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 {
52✔
1517
                f.failFundingFlow(
2✔
1518
                        peer, cid,
2✔
1519
                        lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
2✔
1520
                )
2✔
1521
                return
2✔
1522
        }
2✔
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 {
48✔
UNCOV
1527
                f.failFundingFlow(
×
UNCOV
1528
                        peer, cid,
×
UNCOV
1529
                        lnwallet.ErrChanTooSmall(amt, f.cfg.MinChanSize),
×
UNCOV
1530
                )
×
UNCOV
1531
                return
×
UNCOV
1532
        }
×
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 {
49✔
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{
47✔
1544
                Node:        peer.IdentityKey(),
47✔
1545
                OpenChanMsg: msg,
47✔
1546
        }
47✔
1547

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

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

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

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

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

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

4✔
1605
                // If the zero-conf channel type was negotiated, ensure that
4✔
1606
                // the acceptor allows it.
4✔
1607
                if zeroConf && !acceptorResp.ZeroConf {
4✔
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 {
4✔
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
47✔
1640
        switch {
47✔
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(
47✔
1667
                f.cfg.AuxFundingController,
47✔
1668
                func(c AuxFundingController) AuxTapscriptResult {
47✔
1669
                        return c.DeriveTapscriptRoot(msg.PendingChannelID)
×
1670
                },
×
1671
        ).Unpack()
1672
        if err != nil {
47✔
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{
47✔
1681
                ChainHash:        &msg.ChainHash,
47✔
1682
                PendingChanID:    msg.PendingChannelID,
47✔
1683
                NodeID:           peer.IdentityKey(),
47✔
1684
                NodeAddr:         peer.Address(),
47✔
1685
                LocalFundingAmt:  0,
47✔
1686
                RemoteFundingAmt: amt,
47✔
1687
                CommitFeePerKw:   chainfee.SatPerKWeight(msg.FeePerKiloWeight),
47✔
1688
                FundingFeePerKw:  0,
47✔
1689
                PushMSat:         msg.PushAmount,
47✔
1690
                Flags:            msg.ChannelFlags,
47✔
1691
                MinConfs:         1,
47✔
1692
                CommitType:       commitType,
47✔
1693
                ZeroConf:         zeroConf,
47✔
1694
                OptionScidAlias:  scid,
47✔
1695
                ScidAliasFeature: scidFeatureVal,
47✔
1696
                TapscriptRoot:    tapscriptRoot,
47✔
1697
        }
47✔
1698

47✔
1699
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
47✔
1700
        if err != nil {
47✔
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, "+
47✔
1707
                "cannedShim=%v", reservation.IsZeroConf(),
47✔
1708
                reservation.IsPsbt(), reservation.IsCannedShim())
47✔
1709

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

1720
                reservation.AddAlias(aliasScid)
2✔
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)
47✔
1730
        if acceptorResp.MinAcceptDepth != 0 {
47✔
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 {
49✔
1737
                numConfsReq = 0
2✔
1738
        }
2✔
1739

1740
        reservation.SetNumConfsRequired(numConfsReq)
47✔
1741

47✔
1742
        // We'll also validate and apply all the constraints the initiating
47✔
1743
        // party is attempting to dictate for our commitment transaction.
47✔
1744
        stateBounds := &channeldb.ChannelStateBounds{
47✔
1745
                ChanReserve:      msg.ChannelReserve,
47✔
1746
                MaxPendingAmount: msg.MaxValueInFlight,
47✔
1747
                MinHTLC:          msg.HtlcMinimum,
47✔
1748
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
47✔
1749
        }
47✔
1750
        commitParams := &channeldb.CommitmentParams{
47✔
1751
                DustLimit: msg.DustLimit,
47✔
1752
                CsvDelay:  msg.CsvDelay,
47✔
1753
        }
47✔
1754
        err = reservation.CommitConstraints(
47✔
1755
                stateBounds, commitParams, f.cfg.MaxLocalCSVDelay, true,
47✔
1756
        )
47✔
1757
        if err != nil {
47✔
1758
                log.Errorf("Unacceptable channel constraints: %v", err)
×
1759
                f.failFundingFlow(peer, cid, err)
×
1760
                return
×
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(
47✔
1768
                f.cfg.EnableUpfrontShutdown, peer, acceptorResp.UpfrontShutdown,
47✔
1769
                f.selectShutdownScript,
47✔
1770
        )
47✔
1771
        if err != nil {
47✔
1772
                f.failFundingFlow(
×
1773
                        peer, cid,
×
1774
                        fmt.Errorf("getUpfrontShutdownScript error: %w", err),
×
1775
                )
×
1776
                return
×
1777
        }
×
1778
        reservation.SetOurUpfrontShutdown(shutdown)
47✔
1779

47✔
1780
        // If a script enforced channel lease is being proposed, we'll need to
47✔
1781
        // validate its custom TLV records.
47✔
1782
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
47✔
UNCOV
1783
                if msg.LeaseExpiry == nil {
×
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.
UNCOV
1793
                if reservation.LeaseExpiry() != 0 {
×
UNCOV
1794
                        if uint32(*msg.LeaseExpiry) !=
×
UNCOV
1795
                                reservation.LeaseExpiry() {
×
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): "+
47✔
1805
                "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
47✔
1806
                numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
47✔
1807
                commitType, msg.UpfrontShutdownScript)
47✔
1808

47✔
1809
        // Generate our required constraints for the remote party, using the
47✔
1810
        // values provided by the channel acceptor if they are non-zero.
47✔
1811
        remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
47✔
1812
        if acceptorResp.CSVDelay != 0 {
47✔
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
47✔
1824
        if msg.DustLimit > maxDustLimit {
47✔
1825
                maxDustLimit = msg.DustLimit
×
1826
        }
×
1827

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

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

1838
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
47✔
1839
        if acceptorResp.HtlcLimit != 0 {
47✔
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
47✔
1846
        if acceptorResp.MinHtlcIn != 0 {
47✔
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()
47✔
1854
        forwardingPolicy := f.defaultForwardingPolicy(
47✔
1855
                ourContribution.ChannelStateBounds,
47✔
1856
        )
47✔
1857

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

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

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

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

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

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

×
1929
                        return
×
1930
                }
×
1931

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

1937
        err = reservation.ProcessSingleContribution(remoteContribution)
47✔
1938
        if err != nil {
53✔
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)",
41✔
1945
                msg.PendingChannelID)
41✔
1946
        bounds := remoteContribution.ChannelConfig.ChannelStateBounds
41✔
1947
        log.Debugf("Remote party accepted channel state space bounds: %v",
41✔
1948
                lnutils.SpewLogClosure(bounds))
41✔
1949
        params := remoteContribution.ChannelConfig.CommitmentParams
41✔
1950
        log.Debugf("Remote party accepted commitment rendering params: %v",
41✔
1951
                lnutils.SpewLogClosure(params))
41✔
1952

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

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

41✔
1977
        if commitType.IsTaproot() {
43✔
1978
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
2✔
1979
                        ourContribution.LocalNonce.PubNonce,
2✔
1980
                )
2✔
1981
        }
2✔
1982

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

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

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

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

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

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

33✔
2025
        // Perform some basic validation of any custom TLV records included.
33✔
2026
        //
33✔
2027
        // TODO: Return errors as funding.Error to give context to remote peer?
33✔
2028
        if resCtx.channelType != nil {
37✔
2029
                // We'll want to quickly check that the ChannelType echoed by
4✔
2030
                // the channel request recipient matches what we proposed.
4✔
2031
                if msg.ChannelType == nil {
5✔
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)
3✔
2038
                ackedFeatures := lnwire.RawFeatureVector(*msg.ChannelType)
3✔
2039
                if !proposedFeatures.Equals(&ackedFeatures) {
3✔
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 {
3✔
UNCOV
2048
                        if msg.LeaseExpiry == nil {
×
2049
                                err := errors.New("lease expiry not echoed " +
×
2050
                                        "back")
×
2051
                                f.failFundingFlow(peer, cid, err)
×
2052
                                return
×
2053
                        }
×
UNCOV
2054
                        if uint32(*msg.LeaseExpiry) !=
×
UNCOV
2055
                                resCtx.reservation.LeaseExpiry() {
×
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 {
33✔
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 {
31✔
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
31✔
2112
        if !resCtx.reservation.IsZeroConf() && minDepth == 0 {
31✔
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))
31✔
2125
        bounds := channeldb.ChannelStateBounds{
31✔
2126
                ChanReserve:      msg.ChannelReserve,
31✔
2127
                MaxPendingAmount: msg.MaxValueInFlight,
31✔
2128
                MinHTLC:          msg.HtlcMinimum,
31✔
2129
                MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
31✔
2130
        }
31✔
2131
        commitParams := channeldb.CommitmentParams{
31✔
2132
                DustLimit: msg.DustLimit,
31✔
2133
                CsvDelay:  msg.CsvDelay,
31✔
2134
        }
31✔
2135
        err = resCtx.reservation.CommitConstraints(
31✔
2136
                &bounds, &commitParams, resCtx.maxLocalCsv, false,
31✔
2137
        )
31✔
2138
        if err != nil {
32✔
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{
30✔
2145
                ChannelStateBounds: channeldb.ChannelStateBounds{
30✔
2146
                        MaxPendingAmount: resCtx.remoteMaxValue,
30✔
2147
                        ChanReserve:      resCtx.remoteChanReserve,
30✔
2148
                        MinHTLC:          resCtx.remoteMinHtlc,
30✔
2149
                        MaxAcceptedHtlcs: resCtx.remoteMaxHtlcs,
30✔
2150
                },
30✔
2151
                CommitmentParams: channeldb.CommitmentParams{
30✔
2152
                        DustLimit: msg.DustLimit,
30✔
2153
                        CsvDelay:  resCtx.remoteCsvDelay,
30✔
2154
                },
30✔
2155
                MultiSigKey: keychain.KeyDescriptor{
30✔
2156
                        PubKey: copyPubKey(msg.FundingKey),
30✔
2157
                },
30✔
2158
                RevocationBasePoint: keychain.KeyDescriptor{
30✔
2159
                        PubKey: copyPubKey(msg.RevocationPoint),
30✔
2160
                },
30✔
2161
                PaymentBasePoint: keychain.KeyDescriptor{
30✔
2162
                        PubKey: copyPubKey(msg.PaymentPoint),
30✔
2163
                },
30✔
2164
                DelayBasePoint: keychain.KeyDescriptor{
30✔
2165
                        PubKey: copyPubKey(msg.DelayedPaymentPoint),
30✔
2166
                },
30✔
2167
                HtlcBasePoint: keychain.KeyDescriptor{
30✔
2168
                        PubKey: copyPubKey(msg.HtlcPoint),
30✔
2169
                },
30✔
2170
        }
30✔
2171

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

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

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

×
2189
                        return
×
2190
                }
×
2191

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

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

30✔
2199
        // The wallet has detected that a PSBT funding process was requested by
30✔
2200
        // the user and has halted the funding process after negotiating the
30✔
2201
        // multisig keys. We now have everything that is needed for the user to
30✔
2202
        // start constructing a PSBT that sends to the multisig funding address.
30✔
2203
        var psbtIntent *chanfunding.PsbtIntent
30✔
2204
        if psbtErr, ok := err.(*lnwallet.PsbtFundingRequired); ok {
30✔
UNCOV
2205
                // Return the information that is needed by the user to
×
UNCOV
2206
                // construct the PSBT back to the caller.
×
UNCOV
2207
                addr, amt, packet, err := psbtErr.Intent.FundingParams()
×
UNCOV
2208
                if err != nil {
×
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
                }
×
UNCOV
2215
                var buf bytes.Buffer
×
UNCOV
2216
                err = packet.Serialize(&buf)
×
UNCOV
2217
                if err != nil {
×
2218
                        log.Errorf("Unable to serialize PSBT for "+
×
2219
                                "contribution from %x: %v", peerKeyBytes, err)
×
2220
                        f.failFundingFlow(peer, cid, err)
×
2221
                        return
×
2222
                }
×
UNCOV
2223
                resCtx.updates <- &lnrpc.OpenStatusUpdate{
×
UNCOV
2224
                        PendingChanId: pendingChanID[:],
×
UNCOV
2225
                        Update: &lnrpc.OpenStatusUpdate_PsbtFund{
×
UNCOV
2226
                                PsbtFund: &lnrpc.ReadyForPsbtFunding{
×
UNCOV
2227
                                        FundingAddress: addr.EncodeAddress(),
×
UNCOV
2228
                                        FundingAmount:  amt,
×
UNCOV
2229
                                        Psbt:           buf.Bytes(),
×
UNCOV
2230
                                },
×
UNCOV
2231
                        },
×
UNCOV
2232
                }
×
UNCOV
2233
                psbtIntent = psbtErr.Intent
×
2234
        } else if err != nil {
30✔
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, "+
30✔
2242
                "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
30✔
2243
                msg.CsvDelay)
30✔
2244
        bounds = remoteContribution.ChannelConfig.ChannelStateBounds
30✔
2245
        log.Debugf("Remote party accepted channel state space bounds: %v",
30✔
2246
                lnutils.SpewLogClosure(bounds))
30✔
2247
        commitParams = remoteContribution.ChannelConfig.CommitmentParams
30✔
2248
        log.Debugf("Remote party accepted commitment rendering params: %v",
30✔
2249
                lnutils.SpewLogClosure(commitParams))
30✔
2250

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

×
UNCOV
2260
                        f.waitForPsbt(psbtIntent, resCtx, cid)
×
UNCOV
2261
                }()
×
2262

2263
                // With the new goroutine spawned, we can now exit to unblock
2264
                // the main event loop.
UNCOV
2265
                return
×
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)
30✔
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,
UNCOV
2279
        resCtx *reservationWithCtx, cid *chanIdentifier) {
×
UNCOV
2280

×
UNCOV
2281
        // failFlow is a helper that logs an error message with the current
×
UNCOV
2282
        // context and then fails the funding flow.
×
UNCOV
2283
        peerKey := resCtx.peer.IdentityKey()
×
UNCOV
2284
        failFlow := func(errMsg string, cause error) {
×
UNCOV
2285
                log.Errorf("Unable to handle funding accept message "+
×
UNCOV
2286
                        "for peer_key=%x, pending_chan_id=%x: %s: %v",
×
UNCOV
2287
                        peerKey.SerializeCompressed(), cid.tempChanID, errMsg,
×
UNCOV
2288
                        cause)
×
UNCOV
2289
                f.failFundingFlow(resCtx.peer, cid, cause)
×
UNCOV
2290
        }
×
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.
UNCOV
2295
        select {
×
UNCOV
2296
        case err := <-intent.PsbtReady:
×
UNCOV
2297
                switch err {
×
2298
                // If the user canceled the funding reservation, we need to
2299
                // inform the other peer about us canceling the reservation.
UNCOV
2300
                case chanfunding.ErrUserCanceled:
×
UNCOV
2301
                        failFlow("aborting PSBT flow", err)
×
UNCOV
2302
                        return
×
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.
UNCOV
2307
                case chanfunding.ErrRemoteCanceled:
×
UNCOV
2308
                        log.Infof("Remote canceled, aborting PSBT flow "+
×
UNCOV
2309
                                "for peer_key=%x, pending_chan_id=%x",
×
UNCOV
2310
                                peerKey.SerializeCompressed(), cid.tempChanID)
×
UNCOV
2311
                        return
×
2312

2313
                // Nil error means the flow continues normally now.
UNCOV
2314
                case nil:
×
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.
UNCOV
2325
                auxFundingDesc, err := fn.MapOptionZ(
×
UNCOV
2326
                        f.cfg.AuxFundingController,
×
UNCOV
2327
                        func(c AuxFundingController) AuxFundingDescResult {
×
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()
UNCOV
2338
                if err != nil {
×
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.
UNCOV
2349
                err = resCtx.reservation.ProcessPsbt(auxFundingDesc)
×
UNCOV
2350
                if err != nil {
×
2351
                        failFlow("error continuing PSBT flow", err)
×
2352
                        return
×
2353
                }
×
2354

2355
                // We are now ready to continue the funding flow.
UNCOV
2356
                f.continueFundingAccept(resCtx, cid)
×
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) {
30✔
2374

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

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

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

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

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

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

30✔
2419
        // If this is a taproot channel, then we'll need to populate the musig2
30✔
2420
        // partial sig field instead of the regular commit sig field.
30✔
2421
        if resCtx.reservation.IsTaproot() {
32✔
2422
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
2✔
2423
                if !ok {
2✔
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(
2✔
2433
                        partialSig.ToWireSig(),
2✔
2434
                )
2✔
2435
        } else {
28✔
2436
                fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
28✔
2437
                if err != nil {
28✔
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)
30✔
2445

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

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

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

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

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

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

×
2497
                        return
×
2498
                }
×
2499

2500
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
2✔
2501
                        &partialSig,
2✔
2502
                )
2✔
2503
        } else {
26✔
2504
                commitSig, err = msg.CommitSig.ToSignature()
26✔
2505
                if err != nil {
26✔
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(
28✔
2515
                f.cfg.AuxFundingController,
28✔
2516
                func(c AuxFundingController) AuxFundingDescResult {
28✔
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 {
28✔
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(
28✔
2541
                &fundingOut, commitSig, auxFundingDesc,
28✔
2542
        )
28✔
2543
        if err != nil {
28✔
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
28✔
2551

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

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

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

28✔
2592
        // For taproot channels, we'll need to send over a partial signature
28✔
2593
        // that includes the nonce along side the signature.
28✔
2594
        _, sig := resCtx.reservation.OurSignatures()
28✔
2595
        if resCtx.reservation.IsTaproot() {
30✔
2596
                partialSig, ok := sig.(*lnwallet.MusigPartialSig)
2✔
2597
                if !ok {
2✔
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(
2✔
2608
                        partialSig.ToWireSig(),
2✔
2609
                )
2✔
2610
        } else {
26✔
2611
                fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
26✔
2612
                if err != nil {
26✔
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 {
28✔
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)
28✔
2633

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

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

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

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

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

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

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

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

28✔
2761
        // We have to store the forwardingPolicy before the reservation context
28✔
2762
        // is deleted. The policy will then be read and applied in
28✔
2763
        // newChanAnnouncement.
28✔
2764
        err = f.saveInitialForwardingPolicy(
28✔
2765
                permChanID, &resCtx.forwardingPolicy,
28✔
2766
        )
28✔
2767
        if err != nil {
28✔
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
28✔
2775
        if resCtx.reservation.IsTaproot() {
30✔
2776
                partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
2✔
2777
                if err != nil {
2✔
2778
                        f.failFundingFlow(peer, cid, err)
×
2779

×
2780
                        return
×
2781
                }
×
2782

2783
                commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
2✔
2784
                        &partialSig,
2✔
2785
                )
2✔
2786
        } else {
26✔
2787
                commitSig, err = msg.CommitSig.ToSignature()
26✔
2788
                if err != nil {
26✔
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(
28✔
2796
                nil, commitSig,
28✔
2797
        )
28✔
2798
        if err != nil {
28✔
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)
28✔
2808

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

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

27✔
2833
                err = f.cfg.PublishTransaction(fundingTx, label)
27✔
2834
                if err != nil {
27✔
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(
28✔
2853
                f.cfg.AuxFundingController,
28✔
2854
                func(controller AuxFundingController) error {
28✔
2855
                        return controller.ChannelFinalized(cid.tempChanID)
×
2856
                },
×
2857
        )
2858
        if err != nil {
28✔
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 {
28✔
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), "+
28✔
2874
                "waiting for channel open on-chain", pendingChanID[:],
28✔
2875
                fundingPoint)
28✔
2876

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

28✔
2889
        select {
28✔
2890
        case resCtx.updates <- upd:
28✔
2891
                // Inform the ChannelNotifier that the channel has entered
28✔
2892
                // pending open state.
28✔
2893
                f.cfg.NotifyPendingOpenChannelEvent(
28✔
2894
                        *fundingPoint, completeChan, completeChan.IdentityPub,
28✔
2895
                )
28✔
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)
28✔
2904
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
28✔
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 {
2✔
2926

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

2✔
2943
        // Close the channel with us as the initiator because we are timing the
2✔
2944
        // channel out.
2✔
2945
        if err := c.CloseChannel(
2✔
2946
                closeInfo, channeldb.ChanStatusLocalCloseInitiator,
2✔
2947
        ); err != nil {
2✔
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)
2✔
2954

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

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

2✔
2964
                peer, err := f.waitForPeerOnline(c.IdentityPub)
2✔
2965
                switch err {
2✔
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:
2✔
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)
2✔
2982
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
2✔
2983

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

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

2992
        return timeoutErr
2✔
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) {
59✔
3002

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

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

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

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

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

3031
        case confirmedChannel, ok := <-confChan:
34✔
3032
                if !ok {
34✔
3033
                        return nil, fmt.Errorf("waiting for funding" +
×
3034
                                "confirmation failed")
×
3035
                }
×
3036
                return confirmedChannel, nil
34✔
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) {
79✔
3043
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
79✔
3044
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
79✔
3045

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

3055
                return pkScript, nil
5✔
3056
        }
3057

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

3066
        return input.WitnessScriptHash(multiSigScript)
74✔
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) {
59✔
3082

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

59✔
3086
        // Register with the ChainNotifier for a notification once the funding
59✔
3087
        // transaction reaches `numConfs` confirmations.
59✔
3088
        txid := completeChan.FundingOutpoint.Hash
59✔
3089
        fundingScript, err := makeFundingScript(completeChan)
59✔
3090
        if err != nil {
59✔
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)
59✔
3097

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

3104
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
59✔
3105
                &txid, fundingScript, numConfs,
59✔
3106
                completeChan.BroadcastHeight(),
59✔
3107
        )
59✔
3108
        if err != nil {
59✔
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",
59✔
3116
                txid, numConfs)
59✔
3117

59✔
3118
        // Wait until the specified number of confirmations has been reached,
59✔
3119
        // we get a cancel signal, or the wallet signals a shutdown.
59✔
3120
        for {
145✔
3121
                select {
86✔
3122
                case updDetails, ok := <-confNtfn.Updates:
25✔
3123
                        if !ok {
25✔
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 "+
25✔
3133
                                "block %d, %d confirmations left", txid,
25✔
3134
                                updDetails.BlockHeight, updDetails.NumConfsLeft)
25✔
3135

25✔
3136
                        // Only update the ConfirmationHeight the first time a
25✔
3137
                        // confirmation is received, since on subsequent
25✔
3138
                        // confirmations the block height will remain the same.
25✔
3139
                        if completeChan.ConfirmationHeight == 0 {
50✔
3140
                                err := completeChan.MarkConfirmationHeight(
25✔
3141
                                        updDetails.BlockHeight,
25✔
3142
                                )
25✔
3143
                                if err != nil {
25✔
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:
2✔
3155
                        if !ok {
2✔
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 "+
2✔
3165
                                "point: %s", txid, completeChan.FundingOutpoint)
2✔
3166

2✔
3167
                        // Reset the confirmation height to 0 because the
2✔
3168
                        // funding transaction was reorged out.
2✔
3169
                        err := completeChan.MarkConfirmationHeight(uint32(0))
2✔
3170
                        if err != nil {
2✔
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:
34✔
3179
                        if !ok {
34✔
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) "+
34✔
3189
                                "confirmed in block %d", txid,
34✔
3190
                                completeChan.FundingOutpoint,
34✔
3191
                                confDetails.BlockHeight)
34✔
3192

34✔
3193
                        // In the case of requiring a single confirmation, it
34✔
3194
                        // can happen that the `Confirmed` channel is read
34✔
3195
                        // from first, in which case the confirmation height
34✔
3196
                        // will not be set. If this happens, we take the
34✔
3197
                        // confirmation height from the `Confirmed` channel.
34✔
3198
                        if completeChan.ConfirmationHeight == 0 {
47✔
3199
                                err := completeChan.MarkConfirmationHeight(
13✔
3200
                                        confDetails.BlockHeight,
13✔
3201
                                )
13✔
3202
                                if err != nil {
13✔
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(
34✔
3214
                                confDetails, completeChan, confChan,
34✔
3215
                        )
34✔
3216
                        if err != nil {
34✔
3217
                                log.Errorf("Error handling confirmation for "+
×
3218
                                        "ChannelPoint(%v), txid=%v: %v",
×
3219
                                        completeChan.FundingOutpoint, txid, err)
×
3220
                        }
×
3221

3222
                        return
34✔
3223

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

5✔
3229
                        return
5✔
3230

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

20✔
3236
                        return
20✔
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 {
34✔
3247

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

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

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

3270
        return nil
34✔
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) {
26✔
3282

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

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

3292
        defer epochClient.Cancel()
26✔
3293

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

26✔
3301
        if lncfg.IsDevBuild() {
26✔
UNCOV
3302
                waitBlocksForFundingConf =
×
UNCOV
3303
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
×
UNCOV
3304
        }
×
3305

3306
        // On block maxHeight we will cancel the funding confirmation wait.
3307
        broadcastHeight := completeChan.BroadcastHeight()
26✔
3308
        maxHeight := broadcastHeight + waitBlocksForFundingConf
26✔
3309
        for {
54✔
3310
                select {
28✔
3311
                case epoch, ok := <-epochClient.Epochs:
4✔
3312
                        if !ok {
4✔
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 {
6✔
3321
                                log.Warnf("Waited for %v blocks without "+
2✔
3322
                                        "seeing funding transaction confirmed,"+
2✔
3323
                                        " cancelling.",
2✔
3324
                                        waitBlocksForFundingConf)
2✔
3325

2✔
3326
                                // Notify the caller of the timeout.
2✔
3327
                                close(timeoutChan)
2✔
3328
                                return
2✔
3329
                        }
2✔
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:
15✔
3336
                        return
15✔
3337

3338
                case <-f.quit:
9✔
3339
                        // The fundingManager is shutting down, will resume
9✔
3340
                        // waiting for the funding transaction on startup.
9✔
3341
                        return
9✔
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) {
34✔
3353
        if c.IsInitiator && c.ChanType.HasFundingTx() {
50✔
3354
                shortChanID := c.ShortChanID()
16✔
3355

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

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

16✔
3366
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
16✔
3367
                if err != nil {
16✔
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 {
30✔
3380

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

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

30✔
3387
        // Now that that the channel has been fully confirmed, we'll request
30✔
3388
        // that the wallet fully verify this channel to ensure that it can be
30✔
3389
        // used.
30✔
3390
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
30✔
3391
        if err != nil {
30✔
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() {
32✔
3399
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
2✔
3400
                if err != nil {
2✔
3401
                        return fmt.Errorf("unable to request alias: %w", err)
×
3402
                }
×
3403

3404
                err = f.cfg.AliasManager.AddLocalAlias(
2✔
3405
                        aliasScid, confChannel.shortChanID, true, false,
2✔
3406
                )
2✔
3407
                if err != nil {
2✔
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(
30✔
3419
                &fundingPoint, markedOpen, &confChannel.shortChanID,
30✔
3420
        )
30✔
3421
        if err != nil {
30✔
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)
30✔
3429
        if err != nil {
30✔
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)
30✔
3436

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

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

3451
        return nil
30✔
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 {
35✔
3459

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

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

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

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

4✔
3481
                f.nonceMtx.Lock()
4✔
3482
                localNonce, ok := f.pendingMusigNonces[chanID]
4✔
3483
                if !ok {
8✔
3484
                        // If we don't have any nonces generated yet for this
4✔
3485
                        // first state, then we'll generate them now and stow
4✔
3486
                        // them away.  When we receive the funding locked
4✔
3487
                        // message, we'll then pass along this same set of
4✔
3488
                        // nonces.
4✔
3489
                        newNonce, err := channel.GenMusigNonces()
4✔
3490
                        if err != nil {
4✔
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
4✔
3498
                        f.pendingMusigNonces[chanID] = localNonce
4✔
3499
                }
3500
                f.nonceMtx.Unlock()
4✔
3501

4✔
3502
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
4✔
3503
                        localNonce.PubNonce,
4✔
3504
                )
4✔
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() {
41✔
3513
                aliases := f.cfg.AliasManager.GetAliases(
6✔
3514
                        completeChan.ShortChanID(),
6✔
3515
                )
6✔
3516
                if len(aliases) == 0 {
6✔
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]
6✔
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 {
70✔
3537
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
35✔
3538
                if err != nil {
36✔
3539
                        return err
1✔
3540
                }
1✔
3541

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

34✔
3549
                // We could also refresh the channel state instead of checking
34✔
3550
                // whether the feature was negotiated, but this saves us a
34✔
3551
                // database read.
34✔
3552
                if channelReadyMsg.AliasScid == nil && localAlias &&
34✔
3553
                        remoteAlias {
34✔
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 "+
34✔
3586
                        "for ChannelID(%v)", peerKey, chanID)
34✔
3587

34✔
3588
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
68✔
3589
                        // Sending succeeded, we can break out and continue the
34✔
3590
                        // funding flow.
34✔
3591
                        break
34✔
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
34✔
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) {
59✔
3605

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

3615
        // Avoid a tight loop if peer is offline.
3616
        if _, err := f.waitForPeerOnline(node); err != nil {
59✔
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)
59✔
3624
        if err != nil {
59✔
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 {
92✔
3633
                return false, nil
33✔
3634
        }
33✔
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)
26✔
3640

26✔
3641
        return !loaded, nil
26✔
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) {
26✔
3649

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

26✔
3656
        // We don't necessarily want to go as low as the remote party allows.
26✔
3657
        // Check it against our default forwarding policy.
26✔
3658
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
26✔
UNCOV
3659
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
×
UNCOV
3660
        }
×
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
26✔
3666
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
26✔
3667
        if fwdMaxHTLC > capacityMSat {
26✔
3668
                fwdMaxHTLC = capacityMSat
×
3669
        }
×
3670

3671
        return fwdMinHTLC, fwdMaxHTLC
26✔
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 {
26✔
3686

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

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

26✔
3691
        ann, err := f.newChanAnnouncement(
26✔
3692
                f.cfg.IDKey, completeChan.IdentityPub,
26✔
3693
                &completeChan.LocalChanCfg.MultiSigKey,
26✔
3694
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
26✔
3695
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
26✔
3696
                completeChan.ChanType,
26✔
3697
        )
26✔
3698
        if err != nil {
26✔
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(
26✔
3706
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
26✔
3707
                discovery.ChannelPoint(completeChan.FundingOutpoint),
26✔
3708
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
26✔
3709
        )
26✔
3710
        select {
26✔
3711
        case err := <-errChan:
26✔
3712
                if err != nil {
26✔
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(
26✔
3728
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
26✔
3729
        )
26✔
3730
        select {
26✔
3731
        case err := <-errChan:
26✔
3732
                if err != nil {
26✔
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
26✔
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 {
26✔
3758

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

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

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

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

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

18✔
3805
                fundingScript, err := makeFundingScript(completeChan)
18✔
3806
                if err != nil {
18✔
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(
18✔
3815
                        &txid, fundingScript, numConfs,
18✔
3816
                        completeChan.BroadcastHeight(),
18✔
3817
                )
18✔
3818
                if err != nil {
18✔
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 {
18✔
3827
                case _, ok := <-confNtfn.Confirmed:
16✔
3828
                        if !ok {
16✔
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:
2✔
3837
                        return fmt.Errorf("%v, stopping funding flow for "+
2✔
3838
                                "ChannelPoint(%v)",
2✔
3839
                                ErrFundingManagerShuttingDown,
2✔
3840
                                completeChan.FundingOutpoint)
2✔
3841
                }
3842

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

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

16✔
3849
                // If this is a non-zero-conf option-scid-alias channel, we'll
16✔
3850
                // delete the mappings the gossiper uses so that ChannelUpdates
16✔
3851
                // with aliases won't be accepted. This is done elsewhere for
16✔
3852
                // zero-conf channels.
16✔
3853
                isScidFeature := completeChan.NegotiatedAliasFeature()
16✔
3854
                isZeroConf := completeChan.IsZeroConf()
16✔
3855
                if isScidFeature && !isZeroConf {
16✔
UNCOV
3856
                        baseScid := completeChan.ShortChanID()
×
UNCOV
3857
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
×
UNCOV
3858
                        if err != nil {
×
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.
UNCOV
3867
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
×
UNCOV
3868
                        if err != nil {
×
3869
                                return fmt.Errorf("failed deleting real edge "+
×
3870
                                        "for alias channel from graph: %v",
×
3871
                                        err)
×
3872
                        }
×
3873

UNCOV
3874
                        err = f.addToGraph(
×
UNCOV
3875
                                completeChan, &baseScid, nil, ourPolicy,
×
UNCOV
3876
                        )
×
UNCOV
3877
                        if err != nil {
×
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(
16✔
3886
                        f.cfg.IDKey, completeChan.IdentityPub,
16✔
3887
                        &completeChan.LocalChanCfg.MultiSigKey,
16✔
3888
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
16✔
3889
                        *shortChanID, chanID, completeChan.ChanType,
16✔
3890
                )
16✔
3891
                if err != nil {
16✔
UNCOV
3892
                        return fmt.Errorf("channel announcement failed: %w",
×
UNCOV
3893
                                err)
×
UNCOV
3894
                }
×
3895

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

3900
        return nil
24✔
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 {
6✔
3907
        // First we'll check whether the channel is confirmed on-chain. If it
6✔
3908
        // is already confirmed, the chainntnfs subsystem will return with the
6✔
3909
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
6✔
3910
        confChan, err := f.waitForFundingWithTimeout(c)
6✔
3911
        if err != nil {
8✔
3912
                return fmt.Errorf("error waiting for zero-conf funding "+
2✔
3913
                        "confirmation for ChannelPoint(%v): %v",
2✔
3914
                        c.FundingOutpoint, err)
2✔
3915
        }
2✔
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()
4✔
3921
        if err != nil {
4✔
UNCOV
3922
                return fmt.Errorf("unable to refresh channel state: %w", err)
×
UNCOV
3923
        }
×
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)
4✔
3929
        if err != nil {
4✔
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)
4✔
3937
        if err != nil {
4✔
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
4✔
3945
        if isPublic {
6✔
3946
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
2✔
3947
                if err != nil {
2✔
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())
2✔
3954
                if err != nil {
2✔
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(
2✔
3964
                        c, &confChan.shortChanID, nil, ourPolicy,
2✔
3965
                )
2✔
3966
                if err != nil {
2✔
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)
4✔
3976
        if err != nil {
4✔
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)
4✔
3987

4✔
3988
        return nil
4✔
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) {
4✔
3996

4✔
3997
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
4✔
3998
                channel.RevocationProducer,
4✔
3999
        )
4✔
4000
        if err != nil {
4✔
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(
4✔
4008
                channel.LocalChanCfg.MultiSigKey.PubKey,
4✔
4009
                channel.LocalCommitment.CommitHeight+1,
4✔
4010
                musig2ShaChain,
4✔
4011
        )
4✔
4012
        if err != nil {
4✔
4013
                return nil, fmt.Errorf("unable to generate musig channel "+
×
4014
                        "nonces: %v", err)
×
4015
        }
×
4016

4017
        return verNonce, nil
4✔
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) {
28✔
4024

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

28✔
4027
        // Notify the aux hook that the specified peer just established a
28✔
4028
        // channel with us, identified by the given channel ID.
28✔
4029
        f.cfg.AuxChannelNegotiator.WhenSome(
28✔
4030
                func(acn lnwallet.AuxChannelNegotiator) {
28✔
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 {
28✔
UNCOV
4038
                duration := f.cfg.Dev.ProcessChannelReadyWait
×
UNCOV
4039
                log.Warnf("Channel(%v): sleeping %v before processing "+
×
UNCOV
4040
                        "channel_ready", msg.ChanID, duration)
×
UNCOV
4041

×
UNCOV
4042
                select {
×
UNCOV
4043
                case <-time.After(duration):
×
UNCOV
4044
                        log.Warnf("Channel(%v): slept %v before processing "+
×
UNCOV
4045
                                "channel_ready", msg.ChanID, duration)
×
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 "+
28✔
4053
                "peer %x", msg.ChanID,
28✔
4054
                peer.IdentityKey().SerializeCompressed())
28✔
4055

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

28✔
4061
        // If we are currently in the process of handling a channel_ready
28✔
4062
        // message for this channel, ignore.
28✔
4063
        if loaded {
29✔
4064
                log.Infof("Already handling channelReady for "+
1✔
4065
                        "ChannelID(%v), ignoring.", msg.ChanID)
1✔
4066
                return
1✔
4067
        }
1✔
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)
27✔
4073

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

4088
                // With the signal received, we can now safely delete the entry
4089
                // from the map.
4090
                f.localDiscoverySignals.Delete(msg.ChanID)
25✔
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
27✔
4098
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
27✔
4099
        if err != nil {
27✔
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
27✔
4108
        if channel.ChanType.IsTaproot() {
31✔
4109
                firstVerNonce, err = genFirstStateMusigNonce(channel)
4✔
4110
                if err != nil {
4✔
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() {
33✔
4124
                // If the AliasScid field is nil, we must fail out. We will
6✔
4125
                // most likely not be able to route through the peer.
6✔
4126
                if msg.AliasScid == nil {
6✔
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)
6✔
4136
                if err != nil {
6✔
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(
6✔
4147
                        channel.ShortChannelID,
6✔
4148
                )
6✔
4149
                if len(aliases) == 0 {
6✔
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 {
28✔
4204
                log.Infof("Received duplicate channelReady for "+
1✔
4205
                        "ChannelID(%v), ignoring.", chanID)
1✔
4206
                return
1✔
4207
        }
1✔
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
26✔
4213
        if channel.ChanType.IsTaproot() {
30✔
4214
                f.nonceMtx.Lock()
4✔
4215
                localNonce, ok := f.pendingMusigNonces[chanID]
4✔
4216
                if !ok {
4✔
UNCOV
4217
                        // If there's no pending nonce for this channel ID,
×
UNCOV
4218
                        // we'll use the one generated above.
×
UNCOV
4219
                        localNonce = firstVerNonce
×
UNCOV
4220
                        f.pendingMusigNonces[chanID] = firstVerNonce
×
UNCOV
4221
                }
×
4222
                f.nonceMtx.Unlock()
4✔
4223

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

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

×
4234
                        return
×
4235
                }
×
4236

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

4✔
4245
                // Inform the aux funding controller that the liquidity in the
4✔
4246
                // custom channel is now ready to be advertised. We potentially
4✔
4247
                // haven't sent our own channel ready message yet, but other
4✔
4248
                // than that the channel is ready to count toward available
4✔
4249
                // liquidity.
4✔
4250
                err = fn.MapOptionZ(
4✔
4251
                        f.cfg.AuxFundingController,
4✔
4252
                        func(controller AuxFundingController) error {
4✔
4253
                                return controller.ChannelReady(
×
4254
                                        lnwallet.NewAuxChanState(channel),
×
4255
                                )
×
4256
                        },
×
4257
                )
4258
                if err != nil {
4✔
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)
26✔
4271
        if err != nil {
26✔
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 {
26✔
4279
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4280
                        err)
×
4281
        }
×
4282

4283
        err = peer.AddNewChannel(&lnpeer.NewChannel{
26✔
4284
                OpenChannel: channel,
26✔
4285
                ChanOpts:    chanOpts,
26✔
4286
        }, f.quit)
26✔
4287
        if err != nil {
26✔
UNCOV
4288
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
UNCOV
4289
                        channel.FundingOutpoint,
×
UNCOV
4290
                        peer.IdentityKey().SerializeCompressed(), err,
×
UNCOV
4291
                )
×
UNCOV
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 {
24✔
4303

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

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

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

4327
                peerAlias = &foundAlias
4✔
4328
        }
4329

4330
        err := f.addToGraph(channel, scid, peerAlias, nil)
24✔
4331
        if err != nil {
24✔
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(
24✔
4340
                &channel.FundingOutpoint, addedToGraph, scid,
24✔
4341
        )
24✔
4342
        if err != nil {
24✔
4343
                return fmt.Errorf("error setting channel state to"+
×
4344
                        " addedToGraph: %w", err)
×
4345
        }
×
4346

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

24✔
4350
        err = fn.MapOptionZ(
24✔
4351
                f.cfg.AuxFundingController,
24✔
4352
                func(controller AuxFundingController) error {
24✔
4353
                        return controller.ChannelReady(
×
4354
                                lnwallet.NewAuxChanState(channel),
×
4355
                        )
×
4356
                },
×
4357
        )
4358
        if err != nil {
24✔
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
24✔
4365
        cp := &lnrpc.ChannelPoint{
24✔
4366
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
24✔
4367
                        FundingTxidBytes: fundingPoint.Hash[:],
24✔
4368
                },
24✔
4369
                OutputIndex: fundingPoint.Index,
24✔
4370
        }
24✔
4371

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

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

4389
        return nil
24✔
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 {
26✔
4397

26✔
4398
        // Before we can add the channel to the peer, we'll need to ensure that
26✔
4399
        // we have an initial forwarding policy set. This should always be the
26✔
4400
        // case except for a channel that was created with lnd <= 0.15.5 and
26✔
4401
        // is still pending while updating to this version.
26✔
4402
        var needDBUpdate bool
26✔
4403
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
26✔
4404
        if err != nil {
26✔
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 {
39✔
4419
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
13✔
4420
                needDBUpdate = true
13✔
4421
        }
13✔
4422
        if forwardingPolicy.MaxHTLC == 0 {
39✔
4423
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
13✔
4424
                needDBUpdate = true
13✔
4425
        }
13✔
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 {
39✔
4430
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
13✔
4431
                if err != nil {
13✔
4432
                        return fmt.Errorf("unable to update initial "+
×
4433
                                "forwarding policy: %v", err)
×
4434
                }
×
4435
        }
4436

4437
        return nil
26✔
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) {
42✔
4462

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

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

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

4✔
4483
                chanAnn.Features.Set(
4✔
4484
                        lnwire.SimpleTaprootChannelsRequiredStaging,
4✔
4485
                )
4✔
4486
        }
4✔
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
42✔
4493

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

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

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

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

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

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

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

4575
        case storedFwdingPolicy != nil:
42✔
4576
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
42✔
4577
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
42✔
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()
42✔
4596
        if err != nil {
42✔
4597
                return nil, err
×
4598
        }
×
4599
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
42✔
4600
        if err != nil {
42✔
4601
                return nil, fmt.Errorf("unable to generate channel "+
×
4602
                        "update announcement signature: %w", err)
×
4603
        }
×
4604
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
42✔
4605
        if err != nil {
42✔
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()
42✔
4618
        if err != nil {
42✔
4619
                return nil, err
×
4620
        }
×
4621
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
42✔
4622
        if err != nil {
42✔
4623
                return nil, fmt.Errorf("unable to generate node "+
×
4624
                        "signature for channel announcement: %w", err)
×
4625
        }
×
4626
        bitcoinSig, err := f.cfg.SignMessage(
42✔
4627
                localFundingKey.KeyLocator, chanAnnMsg, true,
42✔
4628
        )
42✔
4629
        if err != nil {
42✔
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{
42✔
4638
                ChannelID:      chanID,
42✔
4639
                ShortChannelID: shortChanID,
42✔
4640
        }
42✔
4641
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
42✔
4642
        if err != nil {
42✔
4643
                return nil, err
×
4644
        }
×
4645
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
42✔
4646
        if err != nil {
42✔
4647
                return nil, err
×
4648
        }
×
4649

4650
        return &chanAnnouncement{
42✔
4651
                chanAnn:       chanAnn,
42✔
4652
                chanUpdateAnn: chanUpdateAnn,
42✔
4653
                chanProof:     proof,
42✔
4654
        }, nil
42✔
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 {
16✔
4668

16✔
4669
        // First, we'll create the batch of announcements to be sent upon
16✔
4670
        // initial channel creation. This includes the channel announcement
16✔
4671
        // itself, the channel update announcement, and our half of the channel
16✔
4672
        // proof needed to fully authenticate the channel.
16✔
4673
        //
16✔
4674
        // We can pass in zeroes for the min and max htlc policy, because we
16✔
4675
        // only use the channel announcement message from the returned struct.
16✔
4676
        ann, err := f.newChanAnnouncement(
16✔
4677
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
16✔
4678
                shortChanID, chanID, 0, 0, nil, chanType,
16✔
4679
        )
16✔
4680
        if err != nil {
16✔
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)
16✔
4690
        select {
16✔
4691
        case err := <-errChan:
16✔
4692
                if err != nil {
16✔
UNCOV
4693
                        if graph.IsError(err, graph.ErrOutdated,
×
UNCOV
4694
                                graph.ErrIgnored) {
×
4695

×
4696
                                log.Debugf("Graph rejected "+
×
4697
                                        "AnnounceSignatures: %v", err)
×
UNCOV
4698
                        } else {
×
UNCOV
4699
                                log.Errorf("Unable to send channel "+
×
UNCOV
4700
                                        "proof: %v", err)
×
UNCOV
4701
                                return err
×
UNCOV
4702
                        }
×
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()
16✔
4714
        if err != nil {
16✔
4715
                log.Errorf("can't generate node announcement: %v", err)
×
4716
                return err
×
4717
        }
×
4718

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

×
UNCOV
4726
                                log.Debugf("Graph rejected "+
×
UNCOV
4727
                                        "NodeAnnouncement: %v", err)
×
UNCOV
4728
                        } else {
×
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
16✔
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) {
57✔
4745
        f.fundingRequests <- msg
57✔
4746
}
57✔
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) {
110✔
4759

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

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

4771
        // If the peer does not support upfront shutdown, return an empty address.
4772
        if !remoteUpfrontShutdown {
214✔
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 {
6✔
4780
                return script, nil
2✔
4781
        }
2✔
4782

4783
        // If we do not have setting of upfront shutdown script enabled, return
4784
        // an empty script.
4785
        if !enableUpfrontShutdown {
3✔
4786
                return nil, nil
1✔
4787
        }
1✔
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) {
57✔
4801
        var (
57✔
4802
                peerKey        = msg.Peer.IdentityKey()
57✔
4803
                localAmt       = msg.LocalFundingAmt
57✔
4804
                baseFee        = msg.BaseFee
57✔
4805
                feeRate        = msg.FeeRate
57✔
4806
                minHtlcIn      = msg.MinHtlcIn
57✔
4807
                remoteCsvDelay = msg.RemoteCsvDelay
57✔
4808
                maxValue       = msg.MaxValueInFlight
57✔
4809
                maxHtlcs       = msg.MaxHtlcs
57✔
4810
                maxCSV         = msg.MaxLocalCsv
57✔
4811
                chanReserve    = msg.RemoteChanReserve
57✔
4812
                outpoints      = msg.Outpoints
57✔
4813
        )
57✔
4814

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

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

57✔
4826
        // We set the channel flags to indicate whether we want this channel to
57✔
4827
        // be announced to the network.
57✔
4828
        var channelFlags lnwire.FundingFlag
57✔
4829
        if !msg.Private {
109✔
4830
                // This channel will be announced.
52✔
4831
                channelFlags = lnwire.FFAnnounceChannel
52✔
4832
        }
52✔
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
57✔
4838
        if msg.PendingChanID == zeroID {
114✔
4839
                chanID = f.nextPendingChanID()
57✔
4840
        } else {
57✔
UNCOV
4841
                // If the user specified their own pending channel ID, then
×
UNCOV
4842
                // we'll ensure it doesn't collide with any existing pending
×
UNCOV
4843
                // channel ID.
×
UNCOV
4844
                chanID = msg.PendingChanID
×
UNCOV
4845
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
×
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(
57✔
4857
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
57✔
4858
                f.selectShutdownScript,
57✔
4859
        )
57✔
4860
        if err != nil {
57✔
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(
57✔
4873
                msg.ChannelType, msg.Peer.LocalFeatures(),
57✔
4874
                msg.Peer.RemoteFeatures(),
57✔
4875
        )
57✔
4876
        if err != nil {
57✔
UNCOV
4877
                log.Errorf("channel type negotiation failed: %v", err)
×
UNCOV
4878
                msg.Err <- err
×
UNCOV
4879
                return
×
UNCOV
4880
        }
×
4881

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

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

4✔
4894
                // The option-scid-alias channel type for a public channel is
4✔
4895
                // disallowed.
4✔
4896
                if scid && !msg.Private {
4✔
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)
57✔
4911
        if err != nil {
57✔
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() &&
57✔
4919
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
61✔
4920

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

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

3✔
4930
                scidFeatureVal = true
3✔
4931
        }
3✔
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(
57✔
4937
                f.cfg.AuxFundingController,
57✔
4938
                func(c AuxFundingController) AuxTapscriptResult {
57✔
4939
                        return c.DeriveTapscriptRoot(chanID)
×
4940
                },
×
4941
        ).Unpack()
4942
        if err != nil {
57✔
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{
57✔
4951
                ChainHash:         &msg.ChainHash,
57✔
4952
                PendingChanID:     chanID,
57✔
4953
                NodeID:            peerKey,
57✔
4954
                NodeAddr:          msg.Peer.Address(),
57✔
4955
                SubtractFees:      msg.SubtractFees,
57✔
4956
                LocalFundingAmt:   localAmt,
57✔
4957
                RemoteFundingAmt:  0,
57✔
4958
                FundUpToMaxAmt:    msg.FundUpToMaxAmt,
57✔
4959
                MinFundAmt:        msg.MinFundAmt,
57✔
4960
                RemoteChanReserve: chanReserve,
57✔
4961
                Outpoints:         outpoints,
57✔
4962
                CommitFeePerKw:    commitFeePerKw,
57✔
4963
                FundingFeePerKw:   msg.FundingFeePerKw,
57✔
4964
                PushMSat:          msg.PushAmt,
57✔
4965
                Flags:             channelFlags,
57✔
4966
                MinConfs:          msg.MinConfs,
57✔
4967
                CommitType:        commitType,
57✔
4968
                ChanFunder:        msg.ChanFunder,
57✔
4969
                // Unconfirmed Utxos which are marked by the sweeper subsystem
57✔
4970
                // are excluded from the coin selection because they are not
57✔
4971
                // final and can be RBFed by the sweeper subsystem.
57✔
4972
                AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
115✔
4973
                        // Utxos with at least 1 confirmation are safe to use
58✔
4974
                        // for channel openings because they don't bare the risk
58✔
4975
                        // of being replaced (BIP 125 RBF).
58✔
4976
                        if u.Confirmations > 0 {
58✔
UNCOV
4977
                                return true
×
UNCOV
4978
                        }
×
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)
58✔
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)
57✔
4993
        if err != nil {
57✔
UNCOV
4994
                msg.Err <- err
×
UNCOV
4995
                return
×
UNCOV
4996
        }
×
4997

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

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

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

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

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

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

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

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

5039
        if maxHtlcs == 0 {
114✔
5040
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
57✔
5041
        }
57✔
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()
57✔
5046

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

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

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

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

57✔
5067
        // If the channel reserve is not specified, then we calculate an
57✔
5068
        // appropriate amount here.
57✔
5069
        if chanReserve == 0 {
110✔
5070
                chanReserve = f.cfg.RequiredRemoteChanReserve(
53✔
5071
                        capacity, ourDustLimit,
53✔
5072
                )
53✔
5073
        }
53✔
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)
57✔
5079
        f.resMtx.Lock()
57✔
5080
        if _, ok := f.activeReservations[peerIDKey]; !ok {
107✔
5081
                f.activeReservations[peerIDKey] = make(pendingChannels)
50✔
5082
        }
50✔
5083

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

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

57✔
5105
        // Check the sanity of the selected channel constraints.
57✔
5106
        bounds := &channeldb.ChannelStateBounds{
57✔
5107
                ChanReserve:      chanReserve,
57✔
5108
                MaxPendingAmount: maxValue,
57✔
5109
                MinHTLC:          minHtlcIn,
57✔
5110
                MaxAcceptedHtlcs: maxHtlcs,
57✔
5111
        }
57✔
5112
        commitParams := &channeldb.CommitmentParams{
57✔
5113
                DustLimit: ourDustLimit,
57✔
5114
                CsvDelay:  remoteCsvDelay,
57✔
5115
        }
57✔
5116
        err = lnwallet.VerifyConstraints(
57✔
5117
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
57✔
5118
        )
57✔
5119
        if err != nil {
59✔
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
55✔
5133
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
55✔
UNCOV
5134
                leaseExpiry = new(lnwire.LeaseExpiry)
×
UNCOV
5135
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
×
UNCOV
5136
        }
×
5137

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

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

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

55✔
5167
        if commitType.IsTaproot() {
57✔
5168
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
2✔
5169
                        ourContribution.LocalNonce.PubNonce,
2✔
5170
                )
2✔
5171
        }
2✔
5172

5173
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
55✔
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.
UNCOV
5199
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
×
UNCOV
5200
        chanID := msg.ChanID
×
UNCOV
5201
        peerKey := peer.IdentityKey()
×
UNCOV
5202

×
UNCOV
5203
        // First, we'll attempt to retrieve and cancel the funding workflow
×
UNCOV
5204
        // that this error was tied to. If we're unable to do so, then we'll
×
UNCOV
5205
        // exit early as this was an unwarranted error.
×
UNCOV
5206
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
×
UNCOV
5207
        if err != nil {
×
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.
UNCOV
5215
        fundingErr := fmt.Errorf("received funding error from %x: %v",
×
UNCOV
5216
                peerKey.SerializeCompressed(), msg.Error(),
×
UNCOV
5217
        )
×
UNCOV
5218
        log.Errorf(fundingErr.Error())
×
UNCOV
5219

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

UNCOV
5228
        resCtx.err <- fundingErr
×
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() {
3✔
5235
        zombieReservations := make(pendingChannels)
3✔
5236

3✔
5237
        f.resMtx.RLock()
3✔
5238
        for _, pendingReservations := range f.activeReservations {
6✔
5239
                for pendingChanID, resCtx := range pendingReservations {
6✔
5240
                        if resCtx.isLocked() {
3✔
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)
3✔
5250
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
3✔
5251
                        if !resCtx.reservation.IsPsbt() && isExpired {
6✔
5252
                                zombieReservations[pendingChanID] = resCtx
3✔
5253
                        }
3✔
5254
                }
5255
        }
5256
        f.resMtx.RUnlock()
3✔
5257

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

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

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

3✔
5273
                f.failFundingFlow(resCtx.peer, cid, err)
3✔
5274
        }
3✔
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) {
23✔
5282

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

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

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

5297
        ctx, ok := nodeReservations[pendingChanID]
16✔
5298
        if !ok {
18✔
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 {
14✔
UNCOV
5308
                ctx.reservation.RemoteCanceled()
×
UNCOV
5309
        }
×
5310

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

5315
        delete(nodeReservations, pendingChanID)
14✔
5316

14✔
5317
        // If this was the last active reservation for this peer, delete the
14✔
5318
        // peer's entry altogether.
14✔
5319
        if len(nodeReservations) == 0 {
28✔
5320
                delete(f.activeReservations, peerIDKey)
14✔
5321
        }
14✔
5322
        return ctx, nil
14✔
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) {
56✔
5329

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

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

56✔
5341
        // If this was the last active reservation for this peer, delete the
56✔
5342
        // peer's entry altogether.
56✔
5343
        if len(nodeReservations) == 0 {
105✔
5344
                delete(f.activeReservations, peerIDKey)
49✔
5345
        }
49✔
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) {
91✔
5352

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

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

5363
        return resCtx, nil
91✔
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,
UNCOV
5372
        peer lnpeer.Peer) bool {
×
UNCOV
5373

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

×
UNCOV
5379
        return ok
×
UNCOV
5380
}
×
5381

5382
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
385✔
5383
        var tmp btcec.JacobianPoint
385✔
5384
        pub.AsJacobian(&tmp)
385✔
5385
        tmp.ToAffine()
385✔
5386
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
385✔
5387
}
385✔
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 {
104✔
5393

104✔
5394
        return &models.ForwardingPolicy{
104✔
5395
                MinHTLCOut:    bounds.MinHTLC,
104✔
5396
                MaxHTLC:       bounds.MaxPendingAmount,
104✔
5397
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
104✔
5398
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
104✔
5399
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
104✔
5400
        }
104✔
5401
}
104✔
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 {
69✔
5407

69✔
5408
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
69✔
5409
                chanID, forwardingPolicy,
69✔
5410
        )
69✔
5411
}
69✔
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) {
94✔
5418

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

5422
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5423
// the database.
5424
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
24✔
5425
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
24✔
5426
}
24✔
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 {
92✔
5432

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

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

92✔
5444
        return f.cfg.ChannelDB.SaveChannelOpeningState(
92✔
5445
                outpointBytes.Bytes(), scratch,
92✔
5446
        )
92✔
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) {
252✔
5454

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

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

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

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

5479
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
24✔
5480
                outpointBytes.Bytes(),
24✔
5481
        )
24✔
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) {
104✔
5509

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

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

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

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