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

lightningnetwork / lnd / 15561477203

10 Jun 2025 01:54PM UTC coverage: 58.351% (-10.1%) from 68.487%
15561477203

Pull #9356

github

web-flow
Merge 6440b25db into c6d6d4c0b
Pull Request #9356: lnrpc: add incoming/outgoing channel ids filter to forwarding history request

33 of 36 new or added lines in 2 files covered. (91.67%)

28366 existing lines in 455 files now uncovered.

97715 of 167461 relevant lines covered (58.35%)

1.81 hits per line

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

71.5
/funding/manager.go
1
package funding
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

103
        msgBufferSize = 50
104

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

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

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

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

130
        zeroID [32]byte
131
)
132

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

146
        chanAmt btcutil.Amount
147

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

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

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

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

165
        updateMtx   sync.RWMutex
166
        lastUpdated time.Time
167

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

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

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

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

3✔
187
        r.lastUpdated = time.Now()
3✔
188
}
3✔
189

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

734
        for _, channel := range allChannels {
6✔
735
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
736

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

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

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

3✔
758
                                f.rebroadcastFundingTx(channel)
3✔
759
                        }
3✔
760
                } else if channel.ChanType.IsSingleFunder() &&
3✔
761
                        channel.ChanType.HasFundingTx() &&
3✔
762
                        channel.IsZeroConf() && channel.IsInitiator &&
3✔
763
                        !channel.ZeroConfConfirmed() {
3✔
UNCOV
764

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

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

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

3✔
782
        return nil
3✔
783
}
784

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

3✔
792
                close(f.quit)
3✔
793
                f.wg.Wait()
3✔
794
        })
3✔
795

796
        return nil
3✔
797
}
798

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

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

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

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

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

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

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

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

3✔
852
        return nextChanID
3✔
853
}
3✔
854

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
994
        log.Debugf("Sending funding error to peer (%x): %v",
3✔
995
                peer.IdentityKey().SerializeCompressed(), spew.Sdump(errMsg))
3✔
996
        if err := peer.SendMessage(false, errMsg); err != nil {
3✔
997
                log.Errorf("unable to send error message to peer %v", err)
×
998
        }
×
999
}
1000

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

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

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

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

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

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

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

3✔
1033
        for {
6✔
1034
                select {
3✔
1035
                case fmsg := <-f.fundingMsgs:
3✔
1036
                        switch msg := fmsg.msg.(type) {
3✔
1037
                        case *lnwire.OpenChannel:
3✔
1038
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
3✔
1039

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

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

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

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

UNCOV
1053
                        case *lnwire.Warning:
×
UNCOV
1054
                                f.handleWarningMsg(fmsg.peer, msg)
×
1055

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

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

1065
                case <-f.quit:
3✔
1066
                        return
3✔
1067
                }
1068
        }
1069
}
1070

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

3✔
1083
        defer f.wg.Done()
3✔
1084

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

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

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

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

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

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

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

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

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

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

3✔
1196
                return nil
3✔
1197

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

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

1221
                        return nil
3✔
1222
                }
1223

1224
                return f.handleChannelReadyReceived(
3✔
1225
                        channel, shortChanID, pendingChanID, updateChan,
3✔
1226
                )
3✔
1227

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

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

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

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

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

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

3✔
1277
                return nil
3✔
1278
        }
1279

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

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

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

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

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

1320
                // Inform the ChannelNotifier that the channel has transitioned
1321
                // from pending open to open.
1322
                if err := f.cfg.NotifyOpenChannelEvent(
3✔
1323
                        channel.FundingOutpoint, channel.IdentityPub,
3✔
1324
                ); err != nil {
3✔
1325
                        log.Errorf("Unable to notify open channel event for "+
×
1326
                                "ChannelPoint(%v): %v",
×
1327
                                channel.FundingOutpoint, err)
×
1328
                }
×
1329

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

1338
                return nil
3✔
1339
        }
1340

1341
        confChannel, err := f.waitForFundingWithTimeout(channel)
3✔
1342
        if err == ErrConfirmationTimeout {
6✔
1343
                return f.fundingTimeout(channel, pendingChanID)
3✔
1344
        } else if err != nil {
9✔
1345
                return fmt.Errorf("error waiting for funding "+
3✔
1346
                        "confirmation for ChannelPoint(%v): %v",
3✔
1347
                        channel.FundingOutpoint, err)
3✔
1348
        }
3✔
1349

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

×
UNCOV
1357
                if channel.NumConfsRequired > maturity {
×
1358
                        numCoinbaseConfs = uint32(channel.NumConfsRequired)
×
1359
                }
×
1360

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

×
1368
                        return err
×
1369
                }
×
1370

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

×
1380
                        return err
×
1381
                }
×
1382

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

1392
                case <-f.quit:
×
1393
                        return ErrFundingManagerShuttingDown
×
1394
                }
1395
        }
1396

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

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

1409
        return nil
3✔
1410
}
1411

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

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

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

3✔
1439
        amt := msg.FundingAmount
3✔
1440

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

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

3✔
1457
        // Create the channel identifier.
3✔
1458
        cid := newChanIdentifier(msg.PendingChannelID)
3✔
1459

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

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

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

3✔
1485
                return
3✔
1486
        }
3✔
1487

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

1495
        if len(pendingChans) > pendingChansLimit {
3✔
1496
                f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
×
1497
                return
×
1498
        }
×
1499

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

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

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

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

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

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

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

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

1580
        var scidFeatureVal bool
3✔
1581
        if hasFeatures(
3✔
1582
                peer.LocalFeatures(), peer.RemoteFeatures(),
3✔
1583
                lnwire.ScidAliasOptional,
3✔
1584
        ) {
6✔
1585

3✔
1586
                scidFeatureVal = true
3✔
1587
        }
3✔
1588

1589
        var (
3✔
1590
                zeroConf bool
3✔
1591
                scid     bool
3✔
1592
        )
3✔
1593

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

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

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

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

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

×
1648
                return
×
1649

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

×
1658
                return
×
1659
        }
1660

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

×
1675
                return
×
1676
        }
×
1677

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

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

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

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

1718
                reservation.AddAlias(aliasScid)
3✔
1719
        }
1720

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

1732
        // We'll ignore the min_depth calculated above if this is a zero-conf
1733
        // channel.
1734
        if zeroConf {
6✔
1735
                numConfsReq = 0
3✔
1736
        }
3✔
1737

1738
        reservation.SetNumConfsRequired(numConfsReq)
3✔
1739

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

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

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

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

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

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

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

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

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

1831
        remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
3✔
1832
        if acceptorResp.InFlightTotal != 0 {
3✔
1833
                remoteMaxValue = acceptorResp.InFlightTotal
×
1834
        }
×
1835

1836
        maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
3✔
1837
        if acceptorResp.HtlcLimit != 0 {
3✔
1838
                maxHtlcs = acceptorResp.HtlcLimit
×
1839
        }
×
1840

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

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

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

3✔
1880
        // Update the timestamp once the fundingOpenMsg has been handled.
3✔
1881
        defer resCtx.updateTimestamp()
3✔
1882

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

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

3✔
1920
        if resCtx.reservation.IsTaproot() {
6✔
1921
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
3✔
1922
                if err != nil {
3✔
1923
                        log.Error(errNoLocalNonce)
×
1924

×
1925
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
1926

×
1927
                        return
×
1928
                }
×
1929

1930
                remoteContribution.LocalNonce = &musig2.Nonces{
3✔
1931
                        PubNonce: localNonce,
3✔
1932
                }
3✔
1933
        }
1934

1935
        err = reservation.ProcessSingleContribution(remoteContribution)
3✔
1936
        if err != nil {
3✔
UNCOV
1937
                log.Errorf("unable to add contribution reservation: %v", err)
×
UNCOV
1938
                f.failFundingFlow(peer, cid, err)
×
UNCOV
1939
                return
×
UNCOV
1940
        }
×
1941

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

3✔
1951
        reservation.SetState(lnwallet.SentAcceptChannel)
3✔
1952

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

3✔
1975
        if commitType.IsTaproot() {
6✔
1976
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
3✔
1977
                        ourContribution.LocalNonce.PubNonce,
3✔
1978
                )
3✔
1979
        }
3✔
1980

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

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

3✔
1996
        pendingChanID := msg.PendingChannelID
3✔
1997
        peerKey := peer.IdentityKey()
3✔
1998
        var peerKeyBytes []byte
3✔
1999
        if peerKey != nil {
6✔
2000
                peerKeyBytes = peerKey.SerializeCompressed()
3✔
2001
        }
3✔
2002

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

2010
        // Update the timestamp once the fundingAcceptMsg has been handled.
2011
        defer resCtx.updateTimestamp()
3✔
2012

3✔
2013
        if resCtx.reservation.State() != lnwallet.SentOpenChannel {
3✔
2014
                return
×
2015
        }
×
2016

2017
        log.Infof("Recv'd fundingResponse for pending_id(%x)",
3✔
2018
                pendingChanID[:])
3✔
2019

3✔
2020
        // Create the channel identifier.
3✔
2021
        cid := newChanIdentifier(msg.PendingChannelID)
3✔
2022

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

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

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

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

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

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

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

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

×
2116
                minDepth = 1
×
2117
        }
×
2118

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

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

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

3✔
2180
        if resCtx.reservation.IsTaproot() {
6✔
2181
                localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
3✔
2182
                if err != nil {
3✔
2183
                        log.Error(errNoLocalNonce)
×
2184

×
2185
                        f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
×
2186

×
2187
                        return
×
2188
                }
×
2189

2190
                remoteContribution.LocalNonce = &musig2.Nonces{
3✔
2191
                        PubNonce: localNonce,
3✔
2192
                }
3✔
2193
        }
2194

2195
        err = resCtx.reservation.ProcessContribution(remoteContribution)
3✔
2196

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

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

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

3✔
2258
                        f.waitForPsbt(psbtIntent, resCtx, cid)
3✔
2259
                }()
3✔
2260

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
2394
        log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
3✔
2395
                cid.tempChanID[:])
3✔
2396

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

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

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

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

×
2427
                        return
×
2428
                }
×
2429

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

2442
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
3✔
2443

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

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

3✔
2461
        peerKey := peer.IdentityKey()
3✔
2462
        pendingChanID := msg.PendingChannelID
3✔
2463

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

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

3✔
2479
        if resCtx.reservation.State() != lnwallet.SentAcceptChannel {
3✔
2480
                return
×
2481
        }
×
2482

2483
        // Create the channel identifier without setting the active channel ID.
2484
        cid := newChanIdentifier(pendingChanID)
3✔
2485

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

×
2495
                        return
×
2496
                }
×
2497

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

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

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

2547
        // Get forwarding policy before deleting the reservation context.
2548
        forwardingPolicy := resCtx.forwardingPolicy
3✔
2549

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

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

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

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

3✔
2588
        fundingSigned := &lnwire.FundingSigned{}
3✔
2589

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

×
2602
                        return
×
2603
                }
×
2604

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

×
2615
                        return
×
2616
                }
×
2617
        }
2618

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

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

3✔
2632
        fundingSigned.ChanID = cid.chanID
3✔
2633

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

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

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

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

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

3✔
2667
        // Inform the ChannelNotifier that the channel has entered
3✔
2668
        // pending open state.
3✔
2669
        if err := f.cfg.NotifyPendingOpenChannelEvent(
3✔
2670
                fundingOut, completeChan, completeChan.IdentityPub,
3✔
2671
        ); err != nil {
3✔
2672
                log.Errorf("Unable to send pending-open channel event for "+
×
2673
                        "ChannelPoint(%v) %v", fundingOut, err)
×
2674
        }
×
2675

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

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

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

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

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

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

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

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

×
2752
                return
×
2753
        }
×
2754

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

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

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

×
2781
                        return
×
2782
                }
×
2783

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
2890
        select {
3✔
2891
        case resCtx.updates <- upd:
3✔
2892
                // Inform the ChannelNotifier that the channel has entered
3✔
2893
                // pending open state.
3✔
2894
                if err := f.cfg.NotifyPendingOpenChannelEvent(
3✔
2895
                        *fundingPoint, completeChan, completeChan.IdentityPub,
3✔
2896
                ); err != nil {
3✔
2897
                        log.Errorf("Unable to send pending-open channel "+
×
2898
                                "event for ChannelPoint(%v) %v", fundingPoint,
×
2899
                                err)
×
2900
                }
×
2901

2902
        case <-f.quit:
×
2903
                return
×
2904
        }
2905

2906
        // At this point we have broadcast the funding transaction and done all
2907
        // necessary processing.
2908
        f.wg.Add(1)
3✔
2909
        go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
3✔
2910
}
2911

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

2921
        // fundingTx is the funding transaction that created the channel.
2922
        fundingTx *wire.MsgTx
2923
}
2924

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

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

3✔
2948
        // Close the channel with us as the initiator because we are timing the
3✔
2949
        // channel out.
3✔
2950
        if err := c.CloseChannel(
3✔
2951
                closeInfo, channeldb.ChanStatusLocalCloseInitiator,
3✔
2952
        ); err != nil {
3✔
2953
                return fmt.Errorf("failed closing channel %v: %w",
×
2954
                        c.FundingOutpoint, err)
×
2955
        }
×
2956

2957
        // Notify other subsystems about the funding timeout.
2958
        err := f.cfg.NotifyFundingTimeout(c.FundingOutpoint, c.IdentityPub)
3✔
2959
        if err != nil {
3✔
2960
                log.Errorf("failed to notify of funding timeout for "+
×
2961
                        "ChanPoint(%v): %v", c.FundingOutpoint, err)
×
2962
        }
×
2963

2964
        timeoutErr := fmt.Errorf("timeout waiting for funding tx (%v) to "+
3✔
2965
                "confirm", c.FundingOutpoint)
3✔
2966

3✔
2967
        // When the peer comes online, we'll notify it that we are now
3✔
2968
        // considering the channel flow canceled.
3✔
2969
        f.wg.Add(1)
3✔
2970
        go func() {
6✔
2971
                defer f.wg.Done()
3✔
2972

3✔
2973
                peer, err := f.waitForPeerOnline(c.IdentityPub)
3✔
2974
                switch err {
3✔
2975
                // We're already shutting down, so we can just return.
2976
                case ErrFundingManagerShuttingDown:
×
2977
                        return
×
2978

2979
                // nil error means we continue on.
2980
                case nil:
3✔
2981

2982
                // For unexpected errors, we print the error and still try to
2983
                // fail the funding flow.
2984
                default:
×
2985
                        log.Errorf("Unexpected error while waiting for peer "+
×
2986
                                "to come online: %v", err)
×
2987
                }
2988

2989
                // Create channel identifier and set the channel ID.
2990
                cid := newChanIdentifier(pendingID)
3✔
2991
                cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
3✔
2992

3✔
2993
                // TODO(halseth): should this send be made
3✔
2994
                // reliable?
3✔
2995

3✔
2996
                // The reservation won't exist at this point, but we'll send an
3✔
2997
                // Error message over anyways with ChanID set to pendingID.
3✔
2998
                f.failFundingFlow(peer, cid, timeoutErr)
3✔
2999
        }()
3000

3001
        return timeoutErr
3✔
3002
}
3003

3004
// waitForFundingWithTimeout is a wrapper around waitForFundingConfirmation and
3005
// waitForTimeout that will return ErrConfirmationTimeout if we are not the
3006
// channel initiator and the MaxWaitNumBlocksFundingConf has passed from the
3007
// funding broadcast height. In case of confirmation, the short channel ID of
3008
// the channel and the funding transaction will be returned.
3009
func (f *Manager) waitForFundingWithTimeout(
3010
        ch *channeldb.OpenChannel) (*confirmedChannel, error) {
3✔
3011

3✔
3012
        confChan := make(chan *confirmedChannel)
3✔
3013
        timeoutChan := make(chan error, 1)
3✔
3014
        cancelChan := make(chan struct{})
3✔
3015

3✔
3016
        f.wg.Add(1)
3✔
3017
        go f.waitForFundingConfirmation(ch, cancelChan, confChan)
3✔
3018

3✔
3019
        // If we are not the initiator, we have no money at stake and will
3✔
3020
        // timeout waiting for the funding transaction to confirm after a
3✔
3021
        // while.
3✔
3022
        if !ch.IsInitiator && !ch.IsZeroConf() {
6✔
3023
                f.wg.Add(1)
3✔
3024
                go f.waitForTimeout(ch, cancelChan, timeoutChan)
3✔
3025
        }
3✔
3026
        defer close(cancelChan)
3✔
3027

3✔
3028
        select {
3✔
3029
        case err := <-timeoutChan:
3✔
3030
                if err != nil {
3✔
3031
                        return nil, err
×
3032
                }
×
3033
                return nil, ErrConfirmationTimeout
3✔
3034

3035
        case <-f.quit:
3✔
3036
                // The fundingManager is shutting down, and will resume wait on
3✔
3037
                // startup.
3✔
3038
                return nil, ErrFundingManagerShuttingDown
3✔
3039

3040
        case confirmedChannel, ok := <-confChan:
3✔
3041
                if !ok {
3✔
3042
                        return nil, fmt.Errorf("waiting for funding" +
×
3043
                                "confirmation failed")
×
3044
                }
×
3045
                return confirmedChannel, nil
3✔
3046
        }
3047
}
3048

3049
// makeFundingScript re-creates the funding script for the funding transaction
3050
// of the target channel.
3051
func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
3✔
3052
        localKey := channel.LocalChanCfg.MultiSigKey.PubKey
3✔
3053
        remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
3✔
3054

3✔
3055
        if channel.ChanType.IsTaproot() {
6✔
3056
                pkScript, _, err := input.GenTaprootFundingScript(
3✔
3057
                        localKey, remoteKey, int64(channel.Capacity),
3✔
3058
                        channel.TapscriptRoot,
3✔
3059
                )
3✔
3060
                if err != nil {
3✔
3061
                        return nil, err
×
3062
                }
×
3063

3064
                return pkScript, nil
3✔
3065
        }
3066

3067
        multiSigScript, err := input.GenMultiSigScript(
3✔
3068
                localKey.SerializeCompressed(),
3✔
3069
                remoteKey.SerializeCompressed(),
3✔
3070
        )
3✔
3071
        if err != nil {
3✔
3072
                return nil, err
×
3073
        }
×
3074

3075
        return input.WitnessScriptHash(multiSigScript)
3✔
3076
}
3077

3078
// waitForFundingConfirmation handles the final stages of the channel funding
3079
// process once the funding transaction has been broadcast. The primary
3080
// function of waitForFundingConfirmation is to wait for blockchain
3081
// confirmation, and then to notify the other systems that must be notified
3082
// when a channel has become active for lightning transactions.
3083
// The wait can be canceled by closing the cancelChan. In case of success,
3084
// a *lnwire.ShortChannelID will be passed to confChan.
3085
//
3086
// NOTE: This MUST be run as a goroutine.
3087
func (f *Manager) waitForFundingConfirmation(
3088
        completeChan *channeldb.OpenChannel, cancelChan <-chan struct{},
3089
        confChan chan<- *confirmedChannel) {
3✔
3090

3✔
3091
        defer f.wg.Done()
3✔
3092
        defer close(confChan)
3✔
3093

3✔
3094
        // Register with the ChainNotifier for a notification once the funding
3✔
3095
        // transaction reaches `numConfs` confirmations.
3✔
3096
        txid := completeChan.FundingOutpoint.Hash
3✔
3097
        fundingScript, err := makeFundingScript(completeChan)
3✔
3098
        if err != nil {
3✔
3099
                log.Errorf("unable to create funding script for "+
×
3100
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3101
                        err)
×
3102
                return
×
3103
        }
×
3104
        numConfs := uint32(completeChan.NumConfsRequired)
3✔
3105

3✔
3106
        // If the underlying channel is a zero-conf channel, we'll set numConfs
3✔
3107
        // to 6, since it will be zero here.
3✔
3108
        if completeChan.IsZeroConf() {
6✔
3109
                numConfs = 6
3✔
3110
        }
3✔
3111

3112
        confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
3113
                &txid, fundingScript, numConfs,
3✔
3114
                completeChan.BroadcastHeight(),
3✔
3115
        )
3✔
3116
        if err != nil {
3✔
3117
                log.Errorf("Unable to register for confirmation of "+
×
3118
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
×
3119
                        err)
×
3120
                return
×
3121
        }
×
3122

3123
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
3✔
3124
                txid, numConfs)
3✔
3125

3✔
3126
        var confDetails *chainntnfs.TxConfirmation
3✔
3127
        var ok bool
3✔
3128

3✔
3129
        // Wait until the specified number of confirmations has been reached,
3✔
3130
        // we get a cancel signal, or the wallet signals a shutdown.
3✔
3131
        select {
3✔
3132
        case confDetails, ok = <-confNtfn.Confirmed:
3✔
3133
                // fallthrough
3134

3135
        case <-cancelChan:
3✔
3136
                log.Warnf("canceled waiting for funding confirmation, "+
3✔
3137
                        "stopping funding flow for ChannelPoint(%v)",
3✔
3138
                        completeChan.FundingOutpoint)
3✔
3139
                return
3✔
3140

3141
        case <-f.quit:
3✔
3142
                log.Warnf("fundingManager shutting down, stopping funding "+
3✔
3143
                        "flow for ChannelPoint(%v)",
3✔
3144
                        completeChan.FundingOutpoint)
3✔
3145
                return
3✔
3146
        }
3147

3148
        if !ok {
3✔
3149
                log.Warnf("ChainNotifier shutting down, cannot complete "+
×
3150
                        "funding flow for ChannelPoint(%v)",
×
3151
                        completeChan.FundingOutpoint)
×
3152
                return
×
3153
        }
×
3154

3155
        fundingPoint := completeChan.FundingOutpoint
3✔
3156
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
3✔
3157
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
3✔
3158

3✔
3159
        // With the block height and the transaction index known, we can
3✔
3160
        // construct the compact chanID which is used on the network to unique
3✔
3161
        // identify channels.
3✔
3162
        shortChanID := lnwire.ShortChannelID{
3✔
3163
                BlockHeight: confDetails.BlockHeight,
3✔
3164
                TxIndex:     confDetails.TxIndex,
3✔
3165
                TxPosition:  uint16(fundingPoint.Index),
3✔
3166
        }
3✔
3167

3✔
3168
        select {
3✔
3169
        case confChan <- &confirmedChannel{
3170
                shortChanID: shortChanID,
3171
                fundingTx:   confDetails.Tx,
3172
        }:
3✔
3173
        case <-f.quit:
×
3174
                return
×
3175
        }
3176
}
3177

3178
// waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
3179
// has passed from the broadcast height of the given channel. In case of error,
3180
// the error is sent on timeoutChan. The wait can be canceled by closing the
3181
// cancelChan.
3182
//
3183
// NOTE: timeoutChan MUST be buffered.
3184
// NOTE: This MUST be run as a goroutine.
3185
func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
3186
        cancelChan <-chan struct{}, timeoutChan chan<- error) {
3✔
3187

3✔
3188
        defer f.wg.Done()
3✔
3189

3✔
3190
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
3191
        if err != nil {
3✔
3192
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3193
                        "notification: %v", err)
×
3194
                return
×
3195
        }
×
3196

3197
        defer epochClient.Cancel()
3✔
3198

3✔
3199
        // The value of waitBlocksForFundingConf is adjusted in a development
3✔
3200
        // environment to enhance test capabilities. Otherwise, it is set to
3✔
3201
        // DefaultMaxWaitNumBlocksFundingConf.
3✔
3202
        waitBlocksForFundingConf := uint32(
3✔
3203
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
3✔
3204
        )
3✔
3205

3✔
3206
        if lncfg.IsDevBuild() {
6✔
3207
                waitBlocksForFundingConf =
3✔
3208
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3209
        }
3✔
3210

3211
        // On block maxHeight we will cancel the funding confirmation wait.
3212
        broadcastHeight := completeChan.BroadcastHeight()
3✔
3213
        maxHeight := broadcastHeight + waitBlocksForFundingConf
3✔
3214
        for {
6✔
3215
                select {
3✔
3216
                case epoch, ok := <-epochClient.Epochs:
3✔
3217
                        if !ok {
3✔
3218
                                timeoutChan <- fmt.Errorf("epoch client " +
×
3219
                                        "shutting down")
×
3220
                                return
×
3221
                        }
×
3222

3223
                        // Close the timeout channel and exit if the block is
3224
                        // above the max height.
3225
                        if uint32(epoch.Height) >= maxHeight {
6✔
3226
                                log.Warnf("Waited for %v blocks without "+
3✔
3227
                                        "seeing funding transaction confirmed,"+
3✔
3228
                                        " cancelling.",
3✔
3229
                                        waitBlocksForFundingConf)
3✔
3230

3✔
3231
                                // Notify the caller of the timeout.
3✔
3232
                                close(timeoutChan)
3✔
3233
                                return
3✔
3234
                        }
3✔
3235

3236
                        // TODO: If we are the channel initiator implement
3237
                        // a method for recovering the funds from the funding
3238
                        // transaction
3239

3240
                case <-cancelChan:
3✔
3241
                        return
3✔
3242

3243
                case <-f.quit:
3✔
3244
                        // The fundingManager is shutting down, will resume
3✔
3245
                        // waiting for the funding transaction on startup.
3✔
3246
                        return
3✔
3247
                }
3248
        }
3249
}
3250

3251
// makeLabelForTx updates the label for the confirmed funding transaction. If
3252
// we opened the channel, and lnd's wallet published our funding tx (which is
3253
// not the case for some channels) then we update our transaction label with
3254
// our short channel ID, which is known now that our funding transaction has
3255
// confirmed. We do not label transactions we did not publish, because our
3256
// wallet has no knowledge of them.
3257
func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
3✔
3258
        if c.IsInitiator && c.ChanType.HasFundingTx() {
6✔
3259
                shortChanID := c.ShortChanID()
3✔
3260

3✔
3261
                // For zero-conf channels, we'll use the actually-confirmed
3✔
3262
                // short channel id.
3✔
3263
                if c.IsZeroConf() {
6✔
3264
                        shortChanID = c.ZeroConfRealScid()
3✔
3265
                }
3✔
3266

3267
                label := labels.MakeLabel(
3✔
3268
                        labels.LabelTypeChannelOpen, &shortChanID,
3✔
3269
                )
3✔
3270

3✔
3271
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
3✔
3272
                if err != nil {
3✔
3273
                        log.Errorf("unable to update label: %v", err)
×
3274
                }
×
3275
        }
3276
}
3277

3278
// handleFundingConfirmation marks a channel as open in the database, and set
3279
// the channelOpeningState markedOpen. In addition it will report the now
3280
// decided short channel ID to the switch, and close the local discovery signal
3281
// for this channel.
3282
func (f *Manager) handleFundingConfirmation(
3283
        completeChan *channeldb.OpenChannel,
3284
        confChannel *confirmedChannel) error {
3✔
3285

3✔
3286
        fundingPoint := completeChan.FundingOutpoint
3✔
3287
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
3✔
3288

3✔
3289
        // TODO(roasbeef): ideally persistent state update for chan above
3✔
3290
        // should be abstracted
3✔
3291

3✔
3292
        // Now that that the channel has been fully confirmed, we'll request
3✔
3293
        // that the wallet fully verify this channel to ensure that it can be
3✔
3294
        // used.
3✔
3295
        err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
3✔
3296
        if err != nil {
3✔
3297
                // TODO(roasbeef): delete chan state?
×
3298
                return fmt.Errorf("unable to validate channel: %w", err)
×
3299
        }
×
3300

3301
        // Now that the channel has been validated, we'll persist an alias for
3302
        // this channel if the option-scid-alias feature-bit was negotiated.
3303
        if completeChan.NegotiatedAliasFeature() {
6✔
3304
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
3305
                if err != nil {
3✔
3306
                        return fmt.Errorf("unable to request alias: %w", err)
×
3307
                }
×
3308

3309
                err = f.cfg.AliasManager.AddLocalAlias(
3✔
3310
                        aliasScid, confChannel.shortChanID, true, false,
3✔
3311
                )
3✔
3312
                if err != nil {
3✔
3313
                        return fmt.Errorf("unable to request alias: %w", err)
×
3314
                }
×
3315
        }
3316

3317
        // The funding transaction now being confirmed, we add this channel to
3318
        // the fundingManager's internal persistent state machine that we use
3319
        // to track the remaining process of the channel opening. This is
3320
        // useful to resume the opening process in case of restarts. We set the
3321
        // opening state before we mark the channel opened in the database,
3322
        // such that we can receover from one of the db writes failing.
3323
        err = f.saveChannelOpeningState(
3✔
3324
                &fundingPoint, markedOpen, &confChannel.shortChanID,
3✔
3325
        )
3✔
3326
        if err != nil {
3✔
3327
                return fmt.Errorf("error setting channel state to "+
×
3328
                        "markedOpen: %v", err)
×
3329
        }
×
3330

3331
        // Now that the channel has been fully confirmed and we successfully
3332
        // saved the opening state, we'll mark it as open within the database.
3333
        err = completeChan.MarkAsOpen(confChannel.shortChanID)
3✔
3334
        if err != nil {
3✔
3335
                return fmt.Errorf("error setting channel pending flag to "+
×
3336
                        "false:        %v", err)
×
3337
        }
×
3338

3339
        // Update the confirmed funding transaction label.
3340
        f.makeLabelForTx(completeChan)
3✔
3341

3✔
3342
        // Inform the ChannelNotifier that the channel has transitioned from
3✔
3343
        // pending open to open.
3✔
3344
        if err := f.cfg.NotifyOpenChannelEvent(
3✔
3345
                completeChan.FundingOutpoint, completeChan.IdentityPub,
3✔
3346
        ); err != nil {
6✔
3347
                log.Errorf("Unable to notify open channel event for "+
3✔
3348
                        "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
3✔
3349
                        err)
3✔
3350
        }
3✔
3351

3352
        // Close the discoverySignal channel, indicating to a separate
3353
        // goroutine that the channel now is marked as open in the database
3354
        // and that it is acceptable to process channel_ready messages
3355
        // from the peer.
3356
        if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
6✔
3357
                close(discoverySignal)
3✔
3358
        }
3✔
3359

3360
        return nil
3✔
3361
}
3362

3363
// sendChannelReady creates and sends the channelReady message.
3364
// This should be called after the funding transaction has been confirmed,
3365
// and the channelState is 'markedOpen'.
3366
func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
3367
        channel *lnwallet.LightningChannel) error {
3✔
3368

3✔
3369
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
3✔
3370

3✔
3371
        var peerKey [33]byte
3✔
3372
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
3✔
3373

3✔
3374
        // Next, we'll send over the channel_ready message which marks that we
3✔
3375
        // consider the channel open by presenting the remote party with our
3✔
3376
        // next revocation key. Without the revocation key, the remote party
3✔
3377
        // will be unable to propose state transitions.
3✔
3378
        nextRevocation, err := channel.NextRevocationKey()
3✔
3379
        if err != nil {
3✔
3380
                return fmt.Errorf("unable to create next revocation: %w", err)
×
3381
        }
×
3382
        channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
3✔
3383

3✔
3384
        // If this is a taproot channel, then we also need to send along our
3✔
3385
        // set of musig2 nonces as well.
3✔
3386
        if completeChan.ChanType.IsTaproot() {
6✔
3387
                log.Infof("ChanID(%v): generating musig2 nonces...",
3✔
3388
                        chanID)
3✔
3389

3✔
3390
                f.nonceMtx.Lock()
3✔
3391
                localNonce, ok := f.pendingMusigNonces[chanID]
3✔
3392
                if !ok {
6✔
3393
                        // If we don't have any nonces generated yet for this
3✔
3394
                        // first state, then we'll generate them now and stow
3✔
3395
                        // them away.  When we receive the funding locked
3✔
3396
                        // message, we'll then pass along this same set of
3✔
3397
                        // nonces.
3✔
3398
                        newNonce, err := channel.GenMusigNonces()
3✔
3399
                        if err != nil {
3✔
3400
                                f.nonceMtx.Unlock()
×
3401
                                return err
×
3402
                        }
×
3403

3404
                        // Now that we've generated the nonce for this channel,
3405
                        // we'll store it in the set of pending nonces.
3406
                        localNonce = newNonce
3✔
3407
                        f.pendingMusigNonces[chanID] = localNonce
3✔
3408
                }
3409
                f.nonceMtx.Unlock()
3✔
3410

3✔
3411
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
3✔
3412
                        localNonce.PubNonce,
3✔
3413
                )
3✔
3414
        }
3415

3416
        // If the channel negotiated the option-scid-alias feature bit, we'll
3417
        // send a TLV segment that includes an alias the peer can use in their
3418
        // invoice hop hints. We'll send the first alias we find for the
3419
        // channel since it does not matter which alias we send. We'll error
3420
        // out in the odd case that no aliases are found.
3421
        if completeChan.NegotiatedAliasFeature() {
6✔
3422
                aliases := f.cfg.AliasManager.GetAliases(
3✔
3423
                        completeChan.ShortChanID(),
3✔
3424
                )
3✔
3425
                if len(aliases) == 0 {
3✔
3426
                        return fmt.Errorf("no aliases found")
×
3427
                }
×
3428

3429
                // We can use a pointer to aliases since GetAliases returns a
3430
                // copy of the alias slice.
3431
                channelReadyMsg.AliasScid = &aliases[0]
3✔
3432
        }
3433

3434
        // If the peer has disconnected before we reach this point, we will need
3435
        // to wait for him to come back online before sending the channelReady
3436
        // message. This is special for channelReady, since failing to send any
3437
        // of the previous messages in the funding flow just cancels the flow.
3438
        // But now the funding transaction is confirmed, the channel is open
3439
        // and we have to make sure the peer gets the channelReady message when
3440
        // it comes back online. This is also crucial during restart of lnd,
3441
        // where we might try to resend the channelReady message before the
3442
        // server has had the time to connect to the peer. We keep trying to
3443
        // send channelReady until we succeed, or the fundingManager is shut
3444
        // down.
3445
        for {
6✔
3446
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
3✔
3447
                if err != nil {
3✔
UNCOV
3448
                        return err
×
UNCOV
3449
                }
×
3450

3451
                localAlias := peer.LocalFeatures().HasFeature(
3✔
3452
                        lnwire.ScidAliasOptional,
3✔
3453
                )
3✔
3454
                remoteAlias := peer.RemoteFeatures().HasFeature(
3✔
3455
                        lnwire.ScidAliasOptional,
3✔
3456
                )
3✔
3457

3✔
3458
                // We could also refresh the channel state instead of checking
3✔
3459
                // whether the feature was negotiated, but this saves us a
3✔
3460
                // database read.
3✔
3461
                if channelReadyMsg.AliasScid == nil && localAlias &&
3✔
3462
                        remoteAlias {
3✔
3463

×
3464
                        // If an alias was not assigned above and the scid
×
3465
                        // alias feature was negotiated, check if we already
×
3466
                        // have an alias stored in case handleChannelReady was
×
3467
                        // called before this. If an alias exists, use that in
×
3468
                        // channel_ready. Otherwise, request and store an
×
3469
                        // alias and use that.
×
3470
                        aliases := f.cfg.AliasManager.GetAliases(
×
3471
                                completeChan.ShortChannelID,
×
3472
                        )
×
3473
                        if len(aliases) == 0 {
×
3474
                                // No aliases were found.
×
3475
                                alias, err := f.cfg.AliasManager.RequestAlias()
×
3476
                                if err != nil {
×
3477
                                        return err
×
3478
                                }
×
3479

3480
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3481
                                        alias, completeChan.ShortChannelID,
×
3482
                                        false, false,
×
3483
                                )
×
3484
                                if err != nil {
×
3485
                                        return err
×
3486
                                }
×
3487

3488
                                channelReadyMsg.AliasScid = &alias
×
3489
                        } else {
×
3490
                                channelReadyMsg.AliasScid = &aliases[0]
×
3491
                        }
×
3492
                }
3493

3494
                log.Infof("Peer(%x) is online, sending ChannelReady "+
3✔
3495
                        "for ChannelID(%v)", peerKey, chanID)
3✔
3496

3✔
3497
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
6✔
3498
                        // Sending succeeded, we can break out and continue the
3✔
3499
                        // funding flow.
3✔
3500
                        break
3✔
3501
                }
3502

3503
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3504
                        "Will retry when online", peerKey, err)
×
3505
        }
3506

3507
        return nil
3✔
3508
}
3509

3510
// receivedChannelReady checks whether or not we've received a ChannelReady
3511
// from the remote peer. If we have, RemoteNextRevocation will be set.
3512
func (f *Manager) receivedChannelReady(node *btcec.PublicKey,
3513
        chanID lnwire.ChannelID) (bool, error) {
3✔
3514

3✔
3515
        // If the funding manager has exited, return an error to stop looping.
3✔
3516
        // Note that the peer may appear as online while the funding manager
3✔
3517
        // has stopped due to the shutdown order in the server.
3✔
3518
        select {
3✔
UNCOV
3519
        case <-f.quit:
×
UNCOV
3520
                return false, ErrFundingManagerShuttingDown
×
3521
        default:
3✔
3522
        }
3523

3524
        // Avoid a tight loop if peer is offline.
3525
        if _, err := f.waitForPeerOnline(node); err != nil {
4✔
3526
                log.Errorf("Wait for peer online failed: %v", err)
1✔
3527
                return false, err
1✔
3528
        }
1✔
3529

3530
        // If we cannot find the channel, then we haven't processed the
3531
        // remote's channelReady message.
3532
        channel, err := f.cfg.FindChannel(node, chanID)
3✔
3533
        if err != nil {
3✔
3534
                log.Errorf("Unable to locate ChannelID(%v) to determine if "+
×
3535
                        "ChannelReady was received", chanID)
×
3536
                return false, err
×
3537
        }
×
3538

3539
        // If we haven't insert the next revocation point, we haven't finished
3540
        // processing the channel ready message.
3541
        if channel.RemoteNextRevocation == nil {
6✔
3542
                return false, nil
3✔
3543
        }
3✔
3544

3545
        // Finally, the barrier signal is removed once we finish
3546
        // `handleChannelReady`. If we can still find the signal, we haven't
3547
        // finished processing it yet.
3548
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
3✔
3549

3✔
3550
        return !loaded, nil
3✔
3551
}
3552

3553
// extractAnnounceParams extracts the various channel announcement and update
3554
// parameters that will be needed to construct a ChannelAnnouncement and a
3555
// ChannelUpdate.
3556
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3557
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
3✔
3558

3✔
3559
        // We'll obtain the min HTLC value we can forward in our direction, as
3✔
3560
        // we'll use this value within our ChannelUpdate. This constraint is
3✔
3561
        // originally set by the remote node, as it will be the one that will
3✔
3562
        // need to determine the smallest HTLC it deems economically relevant.
3✔
3563
        fwdMinHTLC := c.LocalChanCfg.MinHTLC
3✔
3564

3✔
3565
        // We don't necessarily want to go as low as the remote party allows.
3✔
3566
        // Check it against our default forwarding policy.
3✔
3567
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
6✔
3568
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3569
        }
3✔
3570

3571
        // We'll obtain the max HTLC value we can forward in our direction, as
3572
        // we'll use this value within our ChannelUpdate. This value must be <=
3573
        // channel capacity and <= the maximum in-flight msats set by the peer.
3574
        fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
3✔
3575
        capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
3✔
3576
        if fwdMaxHTLC > capacityMSat {
3✔
3577
                fwdMaxHTLC = capacityMSat
×
3578
        }
×
3579

3580
        return fwdMinHTLC, fwdMaxHTLC
3✔
3581
}
3582

3583
// addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
3584
// gossiper so that the channel is added to the graph builder's internal graph.
3585
// These announcement messages are NOT broadcasted to the greater network,
3586
// only to the channel counter party. The proofs required to announce the
3587
// channel to the greater network will be created and sent in annAfterSixConfs.
3588
// The peerAlias is used for zero-conf channels to give the counter-party a
3589
// ChannelUpdate they understand. ourPolicy may be set for various
3590
// option-scid-alias channels to re-use the same policy.
3591
func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
3592
        shortChanID *lnwire.ShortChannelID,
3593
        peerAlias *lnwire.ShortChannelID,
3594
        ourPolicy *models.ChannelEdgePolicy) error {
3✔
3595

3✔
3596
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
3✔
3597

3✔
3598
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
3✔
3599

3✔
3600
        ann, err := f.newChanAnnouncement(
3✔
3601
                f.cfg.IDKey, completeChan.IdentityPub,
3✔
3602
                &completeChan.LocalChanCfg.MultiSigKey,
3✔
3603
                completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
3✔
3604
                chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
3✔
3605
                completeChan.ChanType,
3✔
3606
        )
3✔
3607
        if err != nil {
3✔
3608
                return fmt.Errorf("error generating channel "+
×
3609
                        "announcement: %v", err)
×
3610
        }
×
3611

3612
        // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
3613
        // to the Router's topology.
3614
        errChan := f.cfg.SendAnnouncement(
3✔
3615
                ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
3✔
3616
                discovery.ChannelPoint(completeChan.FundingOutpoint),
3✔
3617
                discovery.TapscriptRoot(completeChan.TapscriptRoot),
3✔
3618
        )
3✔
3619
        select {
3✔
3620
        case err := <-errChan:
3✔
3621
                if err != nil {
3✔
3622
                        if graph.IsError(err, graph.ErrOutdated,
×
3623
                                graph.ErrIgnored) {
×
3624

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

3636
        errChan = f.cfg.SendAnnouncement(
3✔
3637
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
3✔
3638
        )
3✔
3639
        select {
3✔
3640
        case err := <-errChan:
3✔
3641
                if err != nil {
3✔
3642
                        if graph.IsError(err, graph.ErrOutdated,
×
3643
                                graph.ErrIgnored) {
×
3644

×
3645
                                log.Debugf("Graph rejected "+
×
3646
                                        "ChannelUpdate: %v", err)
×
3647
                        } else {
×
3648
                                return fmt.Errorf("error sending channel "+
×
3649
                                        "update: %v", err)
×
3650
                        }
×
3651
                }
3652
        case <-f.quit:
×
3653
                return ErrFundingManagerShuttingDown
×
3654
        }
3655

3656
        return nil
3✔
3657
}
3658

3659
// annAfterSixConfs broadcasts the necessary channel announcement messages to
3660
// the network after 6 confs. Should be called after the channelReady message
3661
// is sent and the channel is added to the graph (channelState is
3662
// 'addedToGraph') and the channel is ready to be used. This is the last
3663
// step in the channel opening process, and the opening state will be deleted
3664
// from the database if successful.
3665
func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
3666
        shortChanID *lnwire.ShortChannelID) error {
3✔
3667

3✔
3668
        // If this channel is not meant to be announced to the greater network,
3✔
3669
        // we'll only send our NodeAnnouncement to our counterparty to ensure we
3✔
3670
        // don't leak any of our information.
3✔
3671
        announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3672
        if !announceChan {
6✔
3673
                log.Debugf("Will not announce private channel %v.",
3✔
3674
                        shortChanID.ToUint64())
3✔
3675

3✔
3676
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
3✔
3677
                if err != nil {
3✔
3678
                        return err
×
3679
                }
×
3680

3681
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
3✔
3682
                if err != nil {
3✔
3683
                        return fmt.Errorf("unable to retrieve current node "+
×
3684
                                "announcement: %v", err)
×
3685
                }
×
3686

3687
                chanID := lnwire.NewChanIDFromOutPoint(
3✔
3688
                        completeChan.FundingOutpoint,
3✔
3689
                )
3✔
3690
                pubKey := peer.PubKey()
3✔
3691
                log.Debugf("Sending our NodeAnnouncement for "+
3✔
3692
                        "ChannelID(%v) to %x", chanID, pubKey)
3✔
3693

3✔
3694
                // TODO(halseth): make reliable. If the peer is not online this
3✔
3695
                // will fail, and the opening process will stop. Should instead
3✔
3696
                // block here, waiting for the peer to come online.
3✔
3697
                if err := peer.SendMessage(true, &nodeAnn); err != nil {
3✔
3698
                        return fmt.Errorf("unable to send node announcement "+
×
3699
                                "to peer %x: %v", pubKey, err)
×
3700
                }
×
3701
        } else {
3✔
3702
                // Otherwise, we'll wait until the funding transaction has
3✔
3703
                // reached 6 confirmations before announcing it.
3✔
3704
                numConfs := uint32(completeChan.NumConfsRequired)
3✔
3705
                if numConfs < 6 {
6✔
3706
                        numConfs = 6
3✔
3707
                }
3✔
3708
                txid := completeChan.FundingOutpoint.Hash
3✔
3709
                log.Debugf("Will announce channel %v after ChannelPoint"+
3✔
3710
                        "(%v) has gotten %d confirmations",
3✔
3711
                        shortChanID.ToUint64(), completeChan.FundingOutpoint,
3✔
3712
                        numConfs)
3✔
3713

3✔
3714
                fundingScript, err := makeFundingScript(completeChan)
3✔
3715
                if err != nil {
3✔
3716
                        return fmt.Errorf("unable to create funding script "+
×
3717
                                "for ChannelPoint(%v): %v",
×
3718
                                completeChan.FundingOutpoint, err)
×
3719
                }
×
3720

3721
                // Register with the ChainNotifier for a notification once the
3722
                // funding transaction reaches at least 6 confirmations.
3723
                confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
3724
                        &txid, fundingScript, numConfs,
3✔
3725
                        completeChan.BroadcastHeight(),
3✔
3726
                )
3✔
3727
                if err != nil {
3✔
3728
                        return fmt.Errorf("unable to register for "+
×
3729
                                "confirmation of ChannelPoint(%v): %v",
×
3730
                                completeChan.FundingOutpoint, err)
×
3731
                }
×
3732

3733
                // Wait until 6 confirmations has been reached or the wallet
3734
                // signals a shutdown.
3735
                select {
3✔
3736
                case _, ok := <-confNtfn.Confirmed:
3✔
3737
                        if !ok {
3✔
3738
                                return fmt.Errorf("ChainNotifier shutting "+
×
3739
                                        "down, cannot complete funding flow "+
×
3740
                                        "for ChannelPoint(%v)",
×
3741
                                        completeChan.FundingOutpoint)
×
3742
                        }
×
3743
                        // Fallthrough.
3744

3745
                case <-f.quit:
3✔
3746
                        return fmt.Errorf("%v, stopping funding flow for "+
3✔
3747
                                "ChannelPoint(%v)",
3✔
3748
                                ErrFundingManagerShuttingDown,
3✔
3749
                                completeChan.FundingOutpoint)
3✔
3750
                }
3751

3752
                fundingPoint := completeChan.FundingOutpoint
3✔
3753
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
3✔
3754

3✔
3755
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
3✔
3756
                        &fundingPoint, shortChanID)
3✔
3757

3✔
3758
                // If this is a non-zero-conf option-scid-alias channel, we'll
3✔
3759
                // delete the mappings the gossiper uses so that ChannelUpdates
3✔
3760
                // with aliases won't be accepted. This is done elsewhere for
3✔
3761
                // zero-conf channels.
3✔
3762
                isScidFeature := completeChan.NegotiatedAliasFeature()
3✔
3763
                isZeroConf := completeChan.IsZeroConf()
3✔
3764
                if isScidFeature && !isZeroConf {
6✔
3765
                        baseScid := completeChan.ShortChanID()
3✔
3766
                        err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
3✔
3767
                        if err != nil {
3✔
3768
                                return fmt.Errorf("failed deleting six confs "+
×
3769
                                        "maps: %v", err)
×
3770
                        }
×
3771

3772
                        // We'll delete the edge and add it again via
3773
                        // addToGraph. This is because the peer may have
3774
                        // sent us a ChannelUpdate with an alias and we don't
3775
                        // want to relay this.
3776
                        ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
3✔
3777
                        if err != nil {
3✔
3778
                                return fmt.Errorf("failed deleting real edge "+
×
3779
                                        "for alias channel from graph: %v",
×
3780
                                        err)
×
3781
                        }
×
3782

3783
                        err = f.addToGraph(
3✔
3784
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3785
                        )
3✔
3786
                        if err != nil {
3✔
3787
                                return fmt.Errorf("failed to re-add to "+
×
3788
                                        "graph: %v", err)
×
3789
                        }
×
3790
                }
3791

3792
                // Create and broadcast the proofs required to make this channel
3793
                // public and usable for other nodes for routing.
3794
                err = f.announceChannel(
3✔
3795
                        f.cfg.IDKey, completeChan.IdentityPub,
3✔
3796
                        &completeChan.LocalChanCfg.MultiSigKey,
3✔
3797
                        completeChan.RemoteChanCfg.MultiSigKey.PubKey,
3✔
3798
                        *shortChanID, chanID, completeChan.ChanType,
3✔
3799
                )
3✔
3800
                if err != nil {
6✔
3801
                        return fmt.Errorf("channel announcement failed: %w",
3✔
3802
                                err)
3✔
3803
                }
3✔
3804

3805
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
3✔
3806
                        "sent to gossiper", &fundingPoint, shortChanID)
3✔
3807
        }
3808

3809
        return nil
3✔
3810
}
3811

3812
// waitForZeroConfChannel is called when the state is addedToGraph with
3813
// a zero-conf channel. This will wait for the real confirmation, add the
3814
// confirmed SCID to the router graph, and then announce after six confs.
3815
func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
3✔
3816
        // First we'll check whether the channel is confirmed on-chain. If it
3✔
3817
        // is already confirmed, the chainntnfs subsystem will return with the
3✔
3818
        // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
3✔
3819
        confChan, err := f.waitForFundingWithTimeout(c)
3✔
3820
        if err != nil {
6✔
3821
                return fmt.Errorf("error waiting for zero-conf funding "+
3✔
3822
                        "confirmation for ChannelPoint(%v): %v",
3✔
3823
                        c.FundingOutpoint, err)
3✔
3824
        }
3✔
3825

3826
        // We'll need to refresh the channel state so that things are properly
3827
        // populated when validating the channel state. Otherwise, a panic may
3828
        // occur due to inconsistency in the OpenChannel struct.
3829
        err = c.Refresh()
3✔
3830
        if err != nil {
6✔
3831
                return fmt.Errorf("unable to refresh channel state: %w", err)
3✔
3832
        }
3✔
3833

3834
        // Now that we have the confirmed transaction and the proper SCID,
3835
        // we'll call ValidateChannel to ensure the confirmed tx is properly
3836
        // formatted.
3837
        err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
3✔
3838
        if err != nil {
3✔
3839
                return fmt.Errorf("unable to validate zero-conf channel: "+
×
3840
                        "%v", err)
×
3841
        }
×
3842

3843
        // Once we know the confirmed ShortChannelID, we'll need to save it to
3844
        // the database and refresh the OpenChannel struct with it.
3845
        err = c.MarkRealScid(confChan.shortChanID)
3✔
3846
        if err != nil {
3✔
3847
                return fmt.Errorf("unable to set confirmed SCID for zero "+
×
3848
                        "channel: %v", err)
×
3849
        }
×
3850

3851
        // Six confirmations have been reached. If this channel is public,
3852
        // we'll delete some of the alias mappings the gossiper uses.
3853
        isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
3✔
3854
        if isPublic {
6✔
3855
                err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
3✔
3856
                if err != nil {
3✔
3857
                        return fmt.Errorf("unable to delete base alias after "+
×
3858
                                "six confirmations: %v", err)
×
3859
                }
×
3860

3861
                // TODO: Make this atomic!
3862
                ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
3✔
3863
                if err != nil {
3✔
3864
                        return fmt.Errorf("unable to delete alias edge from "+
×
3865
                                "graph: %v", err)
×
3866
                }
×
3867

3868
                // We'll need to update the graph with the new ShortChannelID
3869
                // via an addToGraph call. We don't pass in the peer's
3870
                // alias since we'll be using the confirmed SCID from now on
3871
                // regardless if it's public or not.
3872
                err = f.addToGraph(
3✔
3873
                        c, &confChan.shortChanID, nil, ourPolicy,
3✔
3874
                )
3✔
3875
                if err != nil {
3✔
3876
                        return fmt.Errorf("failed adding confirmed zero-conf "+
×
3877
                                "SCID to graph: %v", err)
×
3878
                }
×
3879
        }
3880

3881
        // Since we have now marked down the confirmed SCID, we'll also need to
3882
        // tell the Switch to refresh the relevant ChannelLink so that forwards
3883
        // under the confirmed SCID are possible if this is a public channel.
3884
        err = f.cfg.ReportShortChanID(c.FundingOutpoint)
3✔
3885
        if err != nil {
3✔
3886
                // This should only fail if the link is not found in the
×
3887
                // Switch's linkIndex map. If this is the case, then the peer
×
3888
                // has gone offline and the next time the link is loaded, it
×
3889
                // will have a refreshed state. Just log an error here.
×
3890
                log.Errorf("unable to report scid for zero-conf channel "+
×
3891
                        "channel: %v", err)
×
3892
        }
×
3893

3894
        // Update the confirmed transaction's label.
3895
        f.makeLabelForTx(c)
3✔
3896

3✔
3897
        return nil
3✔
3898
}
3899

3900
// genFirstStateMusigNonce generates a nonces for the "first" local state. This
3901
// is the verification nonce for the state created for us after the initial
3902
// commitment transaction signed as part of the funding flow.
3903
func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
3904
) (*musig2.Nonces, error) {
3✔
3905

3✔
3906
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
3✔
3907
                channel.RevocationProducer,
3✔
3908
        )
3✔
3909
        if err != nil {
3✔
3910
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3911
                        "nonces: %v", err)
×
3912
        }
×
3913

3914
        // We use the _next_ commitment height here as we need to generate the
3915
        // nonce for the next state the remote party will sign for us.
3916
        verNonce, err := channeldb.NewMusigVerificationNonce(
3✔
3917
                channel.LocalChanCfg.MultiSigKey.PubKey,
3✔
3918
                channel.LocalCommitment.CommitHeight+1,
3✔
3919
                musig2ShaChain,
3✔
3920
        )
3✔
3921
        if err != nil {
3✔
3922
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3923
                        "nonces: %v", err)
×
3924
        }
×
3925

3926
        return verNonce, nil
3✔
3927
}
3928

3929
// handleChannelReady finalizes the channel funding process and enables the
3930
// channel to enter normal operating mode.
3931
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
3932
        msg *lnwire.ChannelReady) {
3✔
3933

3✔
3934
        defer f.wg.Done()
3✔
3935

3✔
3936
        // If we are in development mode, we'll wait for specified duration
3✔
3937
        // before processing the channel ready message.
3✔
3938
        if f.cfg.Dev != nil {
6✔
3939
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
3940
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
3941
                        "channel_ready", msg.ChanID, duration)
3✔
3942

3✔
3943
                select {
3✔
3944
                case <-time.After(duration):
3✔
3945
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
3946
                                "channel_ready", msg.ChanID, duration)
3✔
3947
                case <-f.quit:
×
3948
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
3949
                        return
×
3950
                }
3951
        }
3952

3953
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
3✔
3954
                "peer %x", msg.ChanID,
3✔
3955
                peer.IdentityKey().SerializeCompressed())
3✔
3956

3✔
3957
        // We now load or create a new channel barrier for this channel.
3✔
3958
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
3✔
3959
                msg.ChanID, struct{}{},
3✔
3960
        )
3✔
3961

3✔
3962
        // If we are currently in the process of handling a channel_ready
3✔
3963
        // message for this channel, ignore.
3✔
3964
        if loaded {
6✔
3965
                log.Infof("Already handling channelReady for "+
3✔
3966
                        "ChannelID(%v), ignoring.", msg.ChanID)
3✔
3967
                return
3✔
3968
        }
3✔
3969

3970
        // If not already handling channelReady for this channel, then the
3971
        // `LoadOrStore` has set up a barrier, and it will be removed once this
3972
        // function exits.
3973
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
3✔
3974

3✔
3975
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
3✔
3976
        if ok {
6✔
3977
                // Before we proceed with processing the channel_ready
3✔
3978
                // message, we'll wait for the local waitForFundingConfirmation
3✔
3979
                // goroutine to signal that it has the necessary state in
3✔
3980
                // place. Otherwise, we may be missing critical information
3✔
3981
                // required to handle forwarded HTLC's.
3✔
3982
                select {
3✔
3983
                case <-localDiscoverySignal:
3✔
3984
                        // Fallthrough
3985
                case <-f.quit:
3✔
3986
                        return
3✔
3987
                }
3988

3989
                // With the signal received, we can now safely delete the entry
3990
                // from the map.
3991
                f.localDiscoverySignals.Delete(msg.ChanID)
3✔
3992
        }
3993

3994
        // First, we'll attempt to locate the channel whose funding workflow is
3995
        // being finalized by this message. We go to the database rather than
3996
        // our reservation map as we may have restarted, mid funding flow. Also
3997
        // provide the node's public key to make the search faster.
3998
        chanID := msg.ChanID
3✔
3999
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
3✔
4000
        if err != nil {
3✔
4001
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
4002
                        "funding", chanID)
×
4003
                return
×
4004
        }
×
4005

4006
        // If this is a taproot channel, then we can generate the set of nonces
4007
        // the remote party needs to send the next remote commitment here.
4008
        var firstVerNonce *musig2.Nonces
3✔
4009
        if channel.ChanType.IsTaproot() {
6✔
4010
                firstVerNonce, err = genFirstStateMusigNonce(channel)
3✔
4011
                if err != nil {
3✔
4012
                        log.Error(err)
×
4013
                        return
×
4014
                }
×
4015
        }
4016

4017
        // We'll need to store the received TLV alias if the option_scid_alias
4018
        // feature was negotiated. This will be used to provide route hints
4019
        // during invoice creation. In the zero-conf case, it is also used to
4020
        // provide a ChannelUpdate to the remote peer. This is done before the
4021
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
4022
        // If it were to fail on the first call to handleChannelReady, we
4023
        // wouldn't want the channel to be usable yet.
4024
        if channel.NegotiatedAliasFeature() {
6✔
4025
                // If the AliasScid field is nil, we must fail out. We will
3✔
4026
                // most likely not be able to route through the peer.
3✔
4027
                if msg.AliasScid == nil {
3✔
4028
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
4029
                                "does not implement the option-scid-alias "+
×
4030
                                "feature properly", chanID)
×
4031
                        return
×
4032
                }
×
4033

4034
                // We'll store the AliasScid so that invoice creation can use
4035
                // it.
4036
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
3✔
4037
                if err != nil {
3✔
4038
                        log.Errorf("unable to store peer's alias: %v", err)
×
4039
                        return
×
4040
                }
×
4041

4042
                // If we do not have an alias stored, we'll create one now.
4043
                // This is only used in the upgrade case where a user toggles
4044
                // the option-scid-alias feature-bit to on. We'll also send the
4045
                // channel_ready message here in case the link is created
4046
                // before sendChannelReady is called.
4047
                aliases := f.cfg.AliasManager.GetAliases(
3✔
4048
                        channel.ShortChannelID,
3✔
4049
                )
3✔
4050
                if len(aliases) == 0 {
3✔
4051
                        // No aliases were found so we'll request and store an
×
4052
                        // alias and use it in the channel_ready message.
×
4053
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
4054
                        if err != nil {
×
4055
                                log.Errorf("unable to request alias: %v", err)
×
4056
                                return
×
4057
                        }
×
4058

4059
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4060
                                alias, channel.ShortChannelID, false, false,
×
4061
                        )
×
4062
                        if err != nil {
×
4063
                                log.Errorf("unable to add local alias: %v",
×
4064
                                        err)
×
4065
                                return
×
4066
                        }
×
4067

4068
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4069
                        if err != nil {
×
4070
                                log.Errorf("unable to fetch second "+
×
4071
                                        "commitment point: %v", err)
×
4072
                                return
×
4073
                        }
×
4074

4075
                        channelReadyMsg := lnwire.NewChannelReady(
×
4076
                                chanID, secondPoint,
×
4077
                        )
×
4078
                        channelReadyMsg.AliasScid = &alias
×
4079

×
4080
                        if firstVerNonce != nil {
×
4081
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4082
                                        firstVerNonce.PubNonce,
×
4083
                                )
×
4084
                        }
×
4085

4086
                        err = peer.SendMessage(true, channelReadyMsg)
×
4087
                        if err != nil {
×
4088
                                log.Errorf("unable to send channel_ready: %v",
×
4089
                                        err)
×
4090
                                return
×
4091
                        }
×
4092
                }
4093
        }
4094

4095
        // If the RemoteNextRevocation is non-nil, it means that we have
4096
        // already processed channelReady for this channel, so ignore. This
4097
        // check is after the alias logic so we store the peer's most recent
4098
        // alias. The spec requires us to validate that subsequent
4099
        // channel_ready messages use the same per commitment point (the
4100
        // second), but it is not actually necessary since we'll just end up
4101
        // ignoring it. We are, however, required to *send* the same per
4102
        // commitment point, since another pedantic implementation might
4103
        // verify it.
4104
        if channel.RemoteNextRevocation != nil {
6✔
4105
                log.Infof("Received duplicate channelReady for "+
3✔
4106
                        "ChannelID(%v), ignoring.", chanID)
3✔
4107
                return
3✔
4108
        }
3✔
4109

4110
        // If this is a taproot channel, then we'll need to map the received
4111
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4112
        // required in order to make the channel whole.
4113
        var chanOpts []lnwallet.ChannelOpt
3✔
4114
        if channel.ChanType.IsTaproot() {
6✔
4115
                f.nonceMtx.Lock()
3✔
4116
                localNonce, ok := f.pendingMusigNonces[chanID]
3✔
4117
                if !ok {
6✔
4118
                        // If there's no pending nonce for this channel ID,
3✔
4119
                        // we'll use the one generated above.
3✔
4120
                        localNonce = firstVerNonce
3✔
4121
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4122
                }
3✔
4123
                f.nonceMtx.Unlock()
3✔
4124

3✔
4125
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
3✔
4126
                        chanID)
3✔
4127

3✔
4128
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
3✔
4129
                        errNoLocalNonce,
3✔
4130
                )
3✔
4131
                if err != nil {
3✔
4132
                        cid := newChanIdentifier(msg.ChanID)
×
4133
                        f.sendWarning(peer, cid, err)
×
4134

×
4135
                        return
×
4136
                }
×
4137

4138
                chanOpts = append(
3✔
4139
                        chanOpts,
3✔
4140
                        lnwallet.WithLocalMusigNonces(localNonce),
3✔
4141
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
3✔
4142
                                PubNonce: remoteNonce,
3✔
4143
                        }),
3✔
4144
                )
3✔
4145

3✔
4146
                // Inform the aux funding controller that the liquidity in the
3✔
4147
                // custom channel is now ready to be advertised. We potentially
3✔
4148
                // haven't sent our own channel ready message yet, but other
3✔
4149
                // than that the channel is ready to count toward available
3✔
4150
                // liquidity.
3✔
4151
                err = fn.MapOptionZ(
3✔
4152
                        f.cfg.AuxFundingController,
3✔
4153
                        func(controller AuxFundingController) error {
3✔
4154
                                return controller.ChannelReady(
×
4155
                                        lnwallet.NewAuxChanState(channel),
×
4156
                                )
×
4157
                        },
×
4158
                )
4159
                if err != nil {
3✔
4160
                        cid := newChanIdentifier(msg.ChanID)
×
4161
                        f.sendWarning(peer, cid, err)
×
4162

×
4163
                        return
×
4164
                }
×
4165
        }
4166

4167
        // The channel_ready message contains the next commitment point we'll
4168
        // need to create the next commitment state for the remote party. So
4169
        // we'll insert that into the channel now before passing it along to
4170
        // other sub-systems.
4171
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
3✔
4172
        if err != nil {
3✔
4173
                log.Errorf("unable to insert next commitment point: %v", err)
×
4174
                return
×
4175
        }
×
4176

4177
        // Before we can add the channel to the peer, we'll need to ensure that
4178
        // we have an initial forwarding policy set.
4179
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
3✔
4180
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4181
                        err)
×
4182
        }
×
4183

4184
        err = peer.AddNewChannel(&lnpeer.NewChannel{
3✔
4185
                OpenChannel: channel,
3✔
4186
                ChanOpts:    chanOpts,
3✔
4187
        }, f.quit)
3✔
4188
        if err != nil {
3✔
4189
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
4190
                        channel.FundingOutpoint,
×
4191
                        peer.IdentityKey().SerializeCompressed(), err,
×
4192
                )
×
4193
        }
×
4194
}
4195

4196
// handleChannelReadyReceived is called once the remote's channelReady message
4197
// is received and processed. At this stage, we must have sent out our
4198
// channelReady message, once the remote's channelReady is processed, the
4199
// channel is now active, thus we change its state to `addedToGraph` to
4200
// let the channel start handling routing.
4201
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4202
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4203
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
3✔
4204

3✔
4205
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
4206

3✔
4207
        // Since we've sent+received funding locked at this point, we
3✔
4208
        // can clean up the pending musig2 nonce state.
3✔
4209
        f.nonceMtx.Lock()
3✔
4210
        delete(f.pendingMusigNonces, chanID)
3✔
4211
        f.nonceMtx.Unlock()
3✔
4212

3✔
4213
        var peerAlias *lnwire.ShortChannelID
3✔
4214
        if channel.IsZeroConf() {
6✔
4215
                // We'll need to wait until channel_ready has been received and
3✔
4216
                // the peer lets us know the alias they want to use for the
3✔
4217
                // channel. With this information, we can then construct a
3✔
4218
                // ChannelUpdate for them.  If an alias does not yet exist,
3✔
4219
                // we'll just return, letting the next iteration of the loop
3✔
4220
                // check again.
3✔
4221
                var defaultAlias lnwire.ShortChannelID
3✔
4222
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
3✔
4223
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
3✔
4224
                if foundAlias == defaultAlias {
3✔
4225
                        return nil
×
4226
                }
×
4227

4228
                peerAlias = &foundAlias
3✔
4229
        }
4230

4231
        err := f.addToGraph(channel, scid, peerAlias, nil)
3✔
4232
        if err != nil {
3✔
4233
                return fmt.Errorf("failed adding to graph: %w", err)
×
4234
        }
×
4235

4236
        // As the channel is now added to the ChannelRouter's topology, the
4237
        // channel is moved to the next state of the state machine. It will be
4238
        // moved to the last state (actually deleted from the database) after
4239
        // the channel is finally announced.
4240
        err = f.saveChannelOpeningState(
3✔
4241
                &channel.FundingOutpoint, addedToGraph, scid,
3✔
4242
        )
3✔
4243
        if err != nil {
3✔
4244
                return fmt.Errorf("error setting channel state to"+
×
4245
                        " addedToGraph: %w", err)
×
4246
        }
×
4247

4248
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
3✔
4249
                "added to graph", chanID, scid)
3✔
4250

3✔
4251
        err = fn.MapOptionZ(
3✔
4252
                f.cfg.AuxFundingController,
3✔
4253
                func(controller AuxFundingController) error {
3✔
4254
                        return controller.ChannelReady(
×
4255
                                lnwallet.NewAuxChanState(channel),
×
4256
                        )
×
4257
                },
×
4258
        )
4259
        if err != nil {
3✔
4260
                return fmt.Errorf("failed notifying aux funding controller "+
×
4261
                        "about channel ready: %w", err)
×
4262
        }
×
4263

4264
        // Give the caller a final update notifying them that the channel is
4265
        fundingPoint := channel.FundingOutpoint
3✔
4266
        cp := &lnrpc.ChannelPoint{
3✔
4267
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
3✔
4268
                        FundingTxidBytes: fundingPoint.Hash[:],
3✔
4269
                },
3✔
4270
                OutputIndex: fundingPoint.Index,
3✔
4271
        }
3✔
4272

3✔
4273
        if updateChan != nil {
6✔
4274
                upd := &lnrpc.OpenStatusUpdate{
3✔
4275
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
3✔
4276
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
3✔
4277
                                        ChannelPoint: cp,
3✔
4278
                                },
3✔
4279
                        },
3✔
4280
                        PendingChanId: pendingChanID[:],
3✔
4281
                }
3✔
4282

3✔
4283
                select {
3✔
4284
                case updateChan <- upd:
3✔
4285
                case <-f.quit:
×
4286
                        return ErrFundingManagerShuttingDown
×
4287
                }
4288
        }
4289

4290
        return nil
3✔
4291
}
4292

4293
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4294
// policy set for the given channel. If we don't, we'll fall back to the default
4295
// values.
4296
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4297
        channel *channeldb.OpenChannel) error {
3✔
4298

3✔
4299
        // Before we can add the channel to the peer, we'll need to ensure that
3✔
4300
        // we have an initial forwarding policy set. This should always be the
3✔
4301
        // case except for a channel that was created with lnd <= 0.15.5 and
3✔
4302
        // is still pending while updating to this version.
3✔
4303
        var needDBUpdate bool
3✔
4304
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
3✔
4305
        if err != nil {
3✔
4306
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4307
                        "falling back to default values: %v", err)
×
4308

×
4309
                forwardingPolicy = f.defaultForwardingPolicy(
×
4310
                        channel.LocalChanCfg.ChannelStateBounds,
×
4311
                )
×
4312
                needDBUpdate = true
×
4313
        }
×
4314

4315
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4316
        // after 0.16.x, so if a channel was opened with such a version and is
4317
        // still pending while updating to this version, we'll need to set the
4318
        // values to the default values.
4319
        if forwardingPolicy.MinHTLCOut == 0 {
6✔
4320
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
3✔
4321
                needDBUpdate = true
3✔
4322
        }
3✔
4323
        if forwardingPolicy.MaxHTLC == 0 {
6✔
4324
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
3✔
4325
                needDBUpdate = true
3✔
4326
        }
3✔
4327

4328
        // And finally, if we found that the values currently stored aren't
4329
        // sufficient for the link, we'll update the database.
4330
        if needDBUpdate {
6✔
4331
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
3✔
4332
                if err != nil {
3✔
4333
                        return fmt.Errorf("unable to update initial "+
×
4334
                                "forwarding policy: %v", err)
×
4335
                }
×
4336
        }
4337

4338
        return nil
3✔
4339
}
4340

4341
// chanAnnouncement encapsulates the two authenticated announcements that we
4342
// send out to the network after a new channel has been created locally.
4343
type chanAnnouncement struct {
4344
        chanAnn       *lnwire.ChannelAnnouncement1
4345
        chanUpdateAnn *lnwire.ChannelUpdate1
4346
        chanProof     *lnwire.AnnounceSignatures1
4347
}
4348

4349
// newChanAnnouncement creates the authenticated channel announcement messages
4350
// required to broadcast a newly created channel to the network. The
4351
// announcement is two part: the first part authenticates the existence of the
4352
// channel and contains four signatures binding the funding pub keys and
4353
// identity pub keys of both parties to the channel, and the second segment is
4354
// authenticated only by us and contains our directional routing policy for the
4355
// channel. ourPolicy may be set in order to re-use an existing, non-default
4356
// policy.
4357
func (f *Manager) newChanAnnouncement(localPubKey,
4358
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4359
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4360
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4361
        ourPolicy *models.ChannelEdgePolicy,
4362
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
3✔
4363

3✔
4364
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
3✔
4365

3✔
4366
        // The unconditional section of the announcement is the ShortChannelID
3✔
4367
        // itself which compactly encodes the location of the funding output
3✔
4368
        // within the blockchain.
3✔
4369
        chanAnn := &lnwire.ChannelAnnouncement1{
3✔
4370
                ShortChannelID: shortChanID,
3✔
4371
                Features:       lnwire.NewRawFeatureVector(),
3✔
4372
                ChainHash:      chainHash,
3✔
4373
        }
3✔
4374

3✔
4375
        // If this is a taproot channel, then we'll set a special bit in the
3✔
4376
        // feature vector to indicate to the routing layer that this needs a
3✔
4377
        // slightly different type of validation.
3✔
4378
        //
3✔
4379
        // TODO(roasbeef): temp, remove after gossip 1.5
3✔
4380
        if chanType.IsTaproot() {
6✔
4381
                log.Debugf("Applying taproot feature bit to "+
3✔
4382
                        "ChannelAnnouncement for %v", chanID)
3✔
4383

3✔
4384
                chanAnn.Features.Set(
3✔
4385
                        lnwire.SimpleTaprootChannelsRequiredStaging,
3✔
4386
                )
3✔
4387
        }
3✔
4388

4389
        // The chanFlags field indicates which directed edge of the channel is
4390
        // being updated within the ChannelUpdateAnnouncement announcement
4391
        // below. A value of zero means it's the edge of the "first" node and 1
4392
        // being the other node.
4393
        var chanFlags lnwire.ChanUpdateChanFlags
3✔
4394

3✔
4395
        // The lexicographical ordering of the two identity public keys of the
3✔
4396
        // nodes indicates which of the nodes is "first". If our serialized
3✔
4397
        // identity key is lower than theirs then we're the "first" node and
3✔
4398
        // second otherwise.
3✔
4399
        selfBytes := localPubKey.SerializeCompressed()
3✔
4400
        remoteBytes := remotePubKey.SerializeCompressed()
3✔
4401
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
6✔
4402
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
3✔
4403
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
3✔
4404
                copy(
3✔
4405
                        chanAnn.BitcoinKey1[:],
3✔
4406
                        localFundingKey.PubKey.SerializeCompressed(),
3✔
4407
                )
3✔
4408
                copy(
3✔
4409
                        chanAnn.BitcoinKey2[:],
3✔
4410
                        remoteFundingKey.SerializeCompressed(),
3✔
4411
                )
3✔
4412

3✔
4413
                // If we're the first node then update the chanFlags to
3✔
4414
                // indicate the "direction" of the update.
3✔
4415
                chanFlags = 0
3✔
4416
        } else {
6✔
4417
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
3✔
4418
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
3✔
4419
                copy(
3✔
4420
                        chanAnn.BitcoinKey1[:],
3✔
4421
                        remoteFundingKey.SerializeCompressed(),
3✔
4422
                )
3✔
4423
                copy(
3✔
4424
                        chanAnn.BitcoinKey2[:],
3✔
4425
                        localFundingKey.PubKey.SerializeCompressed(),
3✔
4426
                )
3✔
4427

3✔
4428
                // If we're the second node then update the chanFlags to
3✔
4429
                // indicate the "direction" of the update.
3✔
4430
                chanFlags = 1
3✔
4431
        }
3✔
4432

4433
        // Our channel update message flags will signal that we support the
4434
        // max_htlc field.
4435
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
3✔
4436

3✔
4437
        // We announce the channel with the default values. Some of
3✔
4438
        // these values can later be changed by crafting a new ChannelUpdate.
3✔
4439
        chanUpdateAnn := &lnwire.ChannelUpdate1{
3✔
4440
                ShortChannelID: shortChanID,
3✔
4441
                ChainHash:      chainHash,
3✔
4442
                Timestamp:      uint32(time.Now().Unix()),
3✔
4443
                MessageFlags:   msgFlags,
3✔
4444
                ChannelFlags:   chanFlags,
3✔
4445
                TimeLockDelta: uint16(
3✔
4446
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
3✔
4447
                ),
3✔
4448
                HtlcMinimumMsat: fwdMinHTLC,
3✔
4449
                HtlcMaximumMsat: fwdMaxHTLC,
3✔
4450
        }
3✔
4451

3✔
4452
        // The caller of newChanAnnouncement is expected to provide the initial
3✔
4453
        // forwarding policy to be announced. If no persisted initial policy
3✔
4454
        // values are found, then we will use the default policy values in the
3✔
4455
        // channel announcement.
3✔
4456
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
3✔
4457
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
3✔
4458
                return nil, errors.Errorf("unable to generate channel "+
×
4459
                        "update announcement: %v", err)
×
4460
        }
×
4461

4462
        switch {
3✔
4463
        case ourPolicy != nil:
3✔
4464
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4465
                // ChannelUpdate.
3✔
4466
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4467
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4468
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4469
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4470
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4471
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4472
                chanUpdateAnn.FeeRate = uint32(
3✔
4473
                        ourPolicy.FeeProportionalMillionths,
3✔
4474
                )
3✔
4475

4476
        case storedFwdingPolicy != nil:
3✔
4477
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
3✔
4478
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
3✔
4479

4480
        default:
×
4481
                log.Infof("No channel forwarding policy specified for channel "+
×
4482
                        "announcement of ChannelID(%v). "+
×
4483
                        "Assuming default fee parameters.", chanID)
×
4484
                chanUpdateAnn.BaseFee = uint32(
×
4485
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4486
                )
×
4487
                chanUpdateAnn.FeeRate = uint32(
×
4488
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4489
                )
×
4490
        }
4491

4492
        // With the channel update announcement constructed, we'll generate a
4493
        // signature that signs a double-sha digest of the announcement.
4494
        // This'll serve to authenticate this announcement and any other future
4495
        // updates we may send.
4496
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
3✔
4497
        if err != nil {
3✔
4498
                return nil, err
×
4499
        }
×
4500
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
3✔
4501
        if err != nil {
3✔
4502
                return nil, errors.Errorf("unable to generate channel "+
×
4503
                        "update announcement signature: %v", err)
×
4504
        }
×
4505
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
4506
        if err != nil {
3✔
4507
                return nil, errors.Errorf("unable to generate channel "+
×
4508
                        "update announcement signature: %v", err)
×
4509
        }
×
4510

4511
        // The channel existence proofs itself is currently announced in
4512
        // distinct message. In order to properly authenticate this message, we
4513
        // need two signatures: one under the identity public key used which
4514
        // signs the message itself and another signature of the identity
4515
        // public key under the funding key itself.
4516
        //
4517
        // TODO(roasbeef): use SignAnnouncement here instead?
4518
        chanAnnMsg, err := chanAnn.DataToSign()
3✔
4519
        if err != nil {
3✔
4520
                return nil, err
×
4521
        }
×
4522
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
3✔
4523
        if err != nil {
3✔
4524
                return nil, errors.Errorf("unable to generate node "+
×
4525
                        "signature for channel announcement: %v", err)
×
4526
        }
×
4527
        bitcoinSig, err := f.cfg.SignMessage(
3✔
4528
                localFundingKey.KeyLocator, chanAnnMsg, true,
3✔
4529
        )
3✔
4530
        if err != nil {
3✔
4531
                return nil, errors.Errorf("unable to generate bitcoin "+
×
4532
                        "signature for node public key: %v", err)
×
4533
        }
×
4534

4535
        // Finally, we'll generate the announcement proof which we'll use to
4536
        // provide the other side with the necessary signatures required to
4537
        // allow them to reconstruct the full channel announcement.
4538
        proof := &lnwire.AnnounceSignatures1{
3✔
4539
                ChannelID:      chanID,
3✔
4540
                ShortChannelID: shortChanID,
3✔
4541
        }
3✔
4542
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
3✔
4543
        if err != nil {
3✔
4544
                return nil, err
×
4545
        }
×
4546
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
3✔
4547
        if err != nil {
3✔
4548
                return nil, err
×
4549
        }
×
4550

4551
        return &chanAnnouncement{
3✔
4552
                chanAnn:       chanAnn,
3✔
4553
                chanUpdateAnn: chanUpdateAnn,
3✔
4554
                chanProof:     proof,
3✔
4555
        }, nil
3✔
4556
}
4557

4558
// announceChannel announces a newly created channel to the rest of the network
4559
// by crafting the two authenticated announcements required for the peers on
4560
// the network to recognize the legitimacy of the channel. The crafted
4561
// announcements are then sent to the channel router to handle broadcasting to
4562
// the network during its next trickle.
4563
// This method is synchronous and will return when all the network requests
4564
// finish, either successfully or with an error.
4565
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4566
        localFundingKey *keychain.KeyDescriptor,
4567
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4568
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
3✔
4569

3✔
4570
        // First, we'll create the batch of announcements to be sent upon
3✔
4571
        // initial channel creation. This includes the channel announcement
3✔
4572
        // itself, the channel update announcement, and our half of the channel
3✔
4573
        // proof needed to fully authenticate the channel.
3✔
4574
        //
3✔
4575
        // We can pass in zeroes for the min and max htlc policy, because we
3✔
4576
        // only use the channel announcement message from the returned struct.
3✔
4577
        ann, err := f.newChanAnnouncement(
3✔
4578
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
3✔
4579
                shortChanID, chanID, 0, 0, nil, chanType,
3✔
4580
        )
3✔
4581
        if err != nil {
3✔
4582
                log.Errorf("can't generate channel announcement: %v", err)
×
4583
                return err
×
4584
        }
×
4585

4586
        // We only send the channel proof announcement and the node announcement
4587
        // because addToGraph previously sent the ChannelAnnouncement and
4588
        // the ChannelUpdate announcement messages. The channel proof and node
4589
        // announcements are broadcast to the greater network.
4590
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
3✔
4591
        select {
3✔
4592
        case err := <-errChan:
3✔
4593
                if err != nil {
6✔
4594
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4595
                                graph.ErrIgnored) {
3✔
4596

×
4597
                                log.Debugf("Graph rejected "+
×
4598
                                        "AnnounceSignatures: %v", err)
×
4599
                        } else {
3✔
4600
                                log.Errorf("Unable to send channel "+
3✔
4601
                                        "proof: %v", err)
3✔
4602
                                return err
3✔
4603
                        }
3✔
4604
                }
4605

4606
        case <-f.quit:
×
4607
                return ErrFundingManagerShuttingDown
×
4608
        }
4609

4610
        // Now that the channel is announced to the network, we will also
4611
        // obtain and send a node announcement. This is done since a node
4612
        // announcement is only accepted after a channel is known for that
4613
        // particular node, and this might be our first channel.
4614
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
3✔
4615
        if err != nil {
3✔
4616
                log.Errorf("can't generate node announcement: %v", err)
×
4617
                return err
×
4618
        }
×
4619

4620
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
3✔
4621
        select {
3✔
4622
        case err := <-errChan:
3✔
4623
                if err != nil {
6✔
4624
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4625
                                graph.ErrIgnored) {
6✔
4626

3✔
4627
                                log.Debugf("Graph rejected "+
3✔
4628
                                        "NodeAnnouncement: %v", err)
3✔
4629
                        } else {
3✔
4630
                                log.Errorf("Unable to send node "+
×
4631
                                        "announcement: %v", err)
×
4632
                                return err
×
4633
                        }
×
4634
                }
4635

4636
        case <-f.quit:
×
4637
                return ErrFundingManagerShuttingDown
×
4638
        }
4639

4640
        return nil
3✔
4641
}
4642

4643
// InitFundingWorkflow sends a message to the funding manager instructing it
4644
// to initiate a single funder workflow with the source peer.
4645
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
3✔
4646
        f.fundingRequests <- msg
3✔
4647
}
3✔
4648

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

3✔
4661
        // Check whether the remote peer supports upfront shutdown scripts.
3✔
4662
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
3✔
4663
                lnwire.UpfrontShutdownScriptOptional,
3✔
4664
        )
3✔
4665

3✔
4666
        // If the peer does not support upfront shutdown scripts, and one has been
3✔
4667
        // provided, return an error because the feature is not supported.
3✔
4668
        if !remoteUpfrontShutdown && len(script) != 0 {
3✔
UNCOV
4669
                return nil, errUpfrontShutdownScriptNotSupported
×
UNCOV
4670
        }
×
4671

4672
        // If the peer does not support upfront shutdown, return an empty address.
4673
        if !remoteUpfrontShutdown {
3✔
UNCOV
4674
                return nil, nil
×
UNCOV
4675
        }
×
4676

4677
        // If the user has provided an script and the peer supports the feature,
4678
        // return it. Note that user set scripts override the enable upfront
4679
        // shutdown flag.
4680
        if len(script) > 0 {
6✔
4681
                return script, nil
3✔
4682
        }
3✔
4683

4684
        // If we do not have setting of upfront shutdown script enabled, return
4685
        // an empty script.
4686
        if !enableUpfrontShutdown {
6✔
4687
                return nil, nil
3✔
4688
        }
3✔
4689

4690
        // We can safely send a taproot address iff, both sides have negotiated
4691
        // the shutdown-any-segwit feature.
UNCOV
4692
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
×
UNCOV
4693
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
×
UNCOV
4694

×
UNCOV
4695
        return getScript(taprootOK)
×
4696
}
4697

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

3✔
4716
        // If no maximum CSV delay was set for this channel, we use our default
3✔
4717
        // value.
3✔
4718
        if maxCSV == 0 {
6✔
4719
                maxCSV = f.cfg.MaxLocalCSVDelay
3✔
4720
        }
3✔
4721

4722
        log.Infof("Initiating fundingRequest(local_amt=%v "+
3✔
4723
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
3✔
4724
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
3✔
4725
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
3✔
4726

3✔
4727
        // We set the channel flags to indicate whether we want this channel to
3✔
4728
        // be announced to the network.
3✔
4729
        var channelFlags lnwire.FundingFlag
3✔
4730
        if !msg.Private {
6✔
4731
                // This channel will be announced.
3✔
4732
                channelFlags = lnwire.FFAnnounceChannel
3✔
4733
        }
3✔
4734

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

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

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

4783
        var (
3✔
4784
                zeroConf bool
3✔
4785
                scid     bool
3✔
4786
        )
3✔
4787

3✔
4788
        if chanType != nil {
6✔
4789
                // Check if the returned chanType includes either the zero-conf
3✔
4790
                // or scid-alias bits.
3✔
4791
                featureVec := lnwire.RawFeatureVector(*chanType)
3✔
4792
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
3✔
4793
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
3✔
4794

3✔
4795
                // The option-scid-alias channel type for a public channel is
3✔
4796
                // disallowed.
3✔
4797
                if scid && !msg.Private {
3✔
4798
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4799
                                "public channel")
×
4800
                        log.Error(err)
×
4801
                        msg.Err <- err
×
4802

×
4803
                        return
×
4804
                }
×
4805
        }
4806

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

4817
        // For anchor channels cap the initial commit fee rate at our defined
4818
        // maximum.
4819
        if commitType.HasAnchors() &&
3✔
4820
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
6✔
4821

3✔
4822
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
3✔
4823
        }
3✔
4824

4825
        var scidFeatureVal bool
3✔
4826
        if hasFeatures(
3✔
4827
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
3✔
4828
                lnwire.ScidAliasOptional,
3✔
4829
        ) {
6✔
4830

3✔
4831
                scidFeatureVal = true
3✔
4832
        }
3✔
4833

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

×
4848
                return
×
4849
        }
×
4850

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

4881
                        // Query the sweeper storage to make sure we don't use
4882
                        // an unconfirmed utxo still in use by the sweeper
4883
                        // subsystem.
4884
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
3✔
4885
                },
4886
                ZeroConf:         zeroConf,
4887
                OptionScidAlias:  scid,
4888
                ScidAliasFeature: scidFeatureVal,
4889
                Memo:             msg.Memo,
4890
                TapscriptRoot:    tapscriptRoot,
4891
        }
4892

4893
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
3✔
4894
        if err != nil {
6✔
4895
                msg.Err <- err
3✔
4896
                return
3✔
4897
        }
3✔
4898

4899
        if zeroConf {
6✔
4900
                // Store the alias for zero-conf channels in the underlying
3✔
4901
                // partial channel state.
3✔
4902
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
3✔
4903
                if err != nil {
3✔
4904
                        msg.Err <- err
×
4905
                        return
×
4906
                }
×
4907

4908
                reservation.AddAlias(aliasScid)
3✔
4909
        }
4910

4911
        // Set our upfront shutdown address in the existing reservation.
4912
        reservation.SetOurUpfrontShutdown(shutdown)
3✔
4913

3✔
4914
        // Now that we have successfully reserved funds for this channel in the
3✔
4915
        // wallet, we can fetch the final channel capacity. This is done at
3✔
4916
        // this point since the final capacity might change in case of
3✔
4917
        // SubtractFees=true.
3✔
4918
        capacity := reservation.Capacity()
3✔
4919

3✔
4920
        log.Infof("Target commit tx sat/kw for pendingID(%x): %v", chanID,
3✔
4921
                int64(commitFeePerKw))
3✔
4922

3✔
4923
        // If the remote CSV delay was not set in the open channel request,
3✔
4924
        // we'll use the RequiredRemoteDelay closure to compute the delay we
3✔
4925
        // require given the total amount of funds within the channel.
3✔
4926
        if remoteCsvDelay == 0 {
6✔
4927
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
3✔
4928
        }
3✔
4929

4930
        // If no minimum HTLC value was specified, use the default one.
4931
        if minHtlcIn == 0 {
6✔
4932
                minHtlcIn = f.cfg.DefaultMinHtlcIn
3✔
4933
        }
3✔
4934

4935
        // If no max value was specified, use the default one.
4936
        if maxValue == 0 {
6✔
4937
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
3✔
4938
        }
3✔
4939

4940
        if maxHtlcs == 0 {
6✔
4941
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
3✔
4942
        }
3✔
4943

4944
        // Once the reservation has been created, and indexed, queue a funding
4945
        // request to the remote peer, kicking off the funding workflow.
4946
        ourContribution := reservation.OurContribution()
3✔
4947

3✔
4948
        // Prepare the optional channel fee values from the initFundingMsg. If
3✔
4949
        // useBaseFee or useFeeRate are false the client did not provide fee
3✔
4950
        // values hence we assume default fee settings from the config.
3✔
4951
        forwardingPolicy := f.defaultForwardingPolicy(
3✔
4952
                ourContribution.ChannelStateBounds,
3✔
4953
        )
3✔
4954
        if baseFee != nil {
6✔
4955
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
3✔
4956
        }
3✔
4957

4958
        if feeRate != nil {
6✔
4959
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
3✔
4960
        }
3✔
4961

4962
        // Fetch our dust limit which is part of the default channel
4963
        // constraints, and log it.
4964
        ourDustLimit := ourContribution.DustLimit
3✔
4965

3✔
4966
        log.Infof("Dust limit for pendingID(%x): %v", chanID, ourDustLimit)
3✔
4967

3✔
4968
        // If the channel reserve is not specified, then we calculate an
3✔
4969
        // appropriate amount here.
3✔
4970
        if chanReserve == 0 {
6✔
4971
                chanReserve = f.cfg.RequiredRemoteChanReserve(
3✔
4972
                        capacity, ourDustLimit,
3✔
4973
                )
3✔
4974
        }
3✔
4975

4976
        // If a pending channel map for this peer isn't already created, then
4977
        // we create one, ultimately allowing us to track this pending
4978
        // reservation within the target peer.
4979
        peerIDKey := newSerializedKey(peerKey)
3✔
4980
        f.resMtx.Lock()
3✔
4981
        if _, ok := f.activeReservations[peerIDKey]; !ok {
6✔
4982
                f.activeReservations[peerIDKey] = make(pendingChannels)
3✔
4983
        }
3✔
4984

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

3✔
5003
        // Update the timestamp once the InitFundingMsg has been handled.
3✔
5004
        defer resCtx.updateTimestamp()
3✔
5005

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

UNCOV
5027
                msg.Err <- err
×
UNCOV
5028
                return
×
5029
        }
5030

5031
        // When opening a script enforced channel lease, include the required
5032
        // expiry TLV record in our proposal.
5033
        var leaseExpiry *lnwire.LeaseExpiry
3✔
5034
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
6✔
5035
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5036
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5037
        }
3✔
5038

5039
        log.Infof("Starting funding workflow with %v for pending_id(%x), "+
3✔
5040
                "committype=%v", msg.Peer.Address(), chanID, commitType)
3✔
5041

3✔
5042
        reservation.SetState(lnwallet.SentOpenChannel)
3✔
5043

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

3✔
5068
        if commitType.IsTaproot() {
6✔
5069
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
3✔
5070
                        ourContribution.LocalNonce.PubNonce,
3✔
5071
                )
3✔
5072
        }
3✔
5073

5074
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
3✔
5075
                e := fmt.Errorf("unable to send funding request message: %w",
×
5076
                        err)
×
5077
                log.Errorf(e.Error())
×
5078

×
5079
                // Since we were unable to send the initial message to the peer
×
5080
                // and start the funding flow, we'll cancel this reservation.
×
5081
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5082
                if err != nil {
×
5083
                        log.Errorf("unable to cancel reservation: %v", err)
×
5084
                }
×
5085

5086
                msg.Err <- e
×
5087
                return
×
5088
        }
5089
}
5090

5091
// handleWarningMsg processes the warning which was received from remote peer.
UNCOV
5092
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
×
UNCOV
5093
        log.Warnf("received warning message from peer %x: %v",
×
UNCOV
5094
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
×
UNCOV
5095
}
×
5096

5097
// handleErrorMsg processes the error which was received from remote peer,
5098
// depending on the type of error we should do different clean up steps and
5099
// inform the user about it.
5100
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
3✔
5101
        chanID := msg.ChanID
3✔
5102
        peerKey := peer.IdentityKey()
3✔
5103

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

5114
        // If we did indeed find the funding workflow, then we'll return the
5115
        // error back to the caller (if any), and cancel the workflow itself.
5116
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5117
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5118
        )
3✔
5119
        log.Errorf(fundingErr.Error())
3✔
5120

3✔
5121
        // If this was a PSBT funding flow, the remote likely timed out because
3✔
5122
        // we waited too long. Return a nice error message to the user in that
3✔
5123
        // case so the user knows what's the problem.
3✔
5124
        if resCtx.reservation.IsPsbt() {
6✔
5125
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
3✔
5126
                        fundingErr)
3✔
5127
        }
3✔
5128

5129
        resCtx.err <- fundingErr
3✔
5130
}
5131

5132
// pruneZombieReservations loops through all pending reservations and fails the
5133
// funding flow for any reservations that have not been updated since the
5134
// ReservationTimeout and are not locked waiting for the funding transaction.
5135
func (f *Manager) pruneZombieReservations() {
3✔
5136
        zombieReservations := make(pendingChannels)
3✔
5137

3✔
5138
        f.resMtx.RLock()
3✔
5139
        for _, pendingReservations := range f.activeReservations {
6✔
5140
                for pendingChanID, resCtx := range pendingReservations {
6✔
5141
                        if resCtx.isLocked() {
3✔
5142
                                continue
×
5143
                        }
5144

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

3✔
5159
        for pendingChanID, resCtx := range zombieReservations {
6✔
5160
                err := fmt.Errorf("reservation timed out waiting for peer "+
3✔
5161
                        "(peer_id:%x, chan_id:%x)",
3✔
5162
                        resCtx.peer.IdentityKey().SerializeCompressed(),
3✔
5163
                        pendingChanID[:])
3✔
5164
                log.Warnf(err.Error())
3✔
5165

3✔
5166
                chanID := lnwire.NewChanIDFromOutPoint(
3✔
5167
                        *resCtx.reservation.FundingOutpoint(),
3✔
5168
                )
3✔
5169

3✔
5170
                // Create channel identifier and set the channel ID.
3✔
5171
                cid := newChanIdentifier(pendingChanID)
3✔
5172
                cid.setChanID(chanID)
3✔
5173

3✔
5174
                f.failFundingFlow(resCtx.peer, cid, err)
3✔
5175
        }
3✔
5176
}
5177

5178
// cancelReservationCtx does all needed work in order to securely cancel the
5179
// reservation.
5180
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5181
        pendingChanID PendingChanID,
5182
        byRemote bool) (*reservationWithCtx, error) {
3✔
5183

3✔
5184
        log.Infof("Cancelling funding reservation for node_key=%x, "+
3✔
5185
                "chan_id=%x", peerKey.SerializeCompressed(), pendingChanID[:])
3✔
5186

3✔
5187
        peerIDKey := newSerializedKey(peerKey)
3✔
5188
        f.resMtx.Lock()
3✔
5189
        defer f.resMtx.Unlock()
3✔
5190

3✔
5191
        nodeReservations, ok := f.activeReservations[peerIDKey]
3✔
5192
        if !ok {
6✔
5193
                // No reservations for this node.
3✔
5194
                return nil, errors.Errorf("no active reservations for peer(%x)",
3✔
5195
                        peerIDKey[:])
3✔
5196
        }
3✔
5197

5198
        ctx, ok := nodeReservations[pendingChanID]
3✔
5199
        if !ok {
3✔
UNCOV
5200
                return nil, errors.Errorf("unknown channel (id: %x) for "+
×
UNCOV
5201
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
×
UNCOV
5202
        }
×
5203

5204
        // If the reservation was a PSBT funding flow and it was canceled by the
5205
        // remote peer, then we need to thread through a different error message
5206
        // to the subroutine that's waiting for the user input so it can return
5207
        // a nice error message to the user.
5208
        if ctx.reservation.IsPsbt() && byRemote {
6✔
5209
                ctx.reservation.RemoteCanceled()
3✔
5210
        }
3✔
5211

5212
        if err := ctx.reservation.Cancel(); err != nil {
3✔
5213
                return nil, errors.Errorf("unable to cancel reservation: %v",
×
5214
                        err)
×
5215
        }
×
5216

5217
        delete(nodeReservations, pendingChanID)
3✔
5218

3✔
5219
        // If this was the last active reservation for this peer, delete the
3✔
5220
        // peer's entry altogether.
3✔
5221
        if len(nodeReservations) == 0 {
6✔
5222
                delete(f.activeReservations, peerIDKey)
3✔
5223
        }
3✔
5224
        return ctx, nil
3✔
5225
}
5226

5227
// deleteReservationCtx deletes the reservation uniquely identified by the
5228
// target public key of the peer, and the specified pending channel ID.
5229
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5230
        pendingChanID PendingChanID) {
3✔
5231

3✔
5232
        peerIDKey := newSerializedKey(peerKey)
3✔
5233
        f.resMtx.Lock()
3✔
5234
        defer f.resMtx.Unlock()
3✔
5235

3✔
5236
        nodeReservations, ok := f.activeReservations[peerIDKey]
3✔
5237
        if !ok {
3✔
5238
                // No reservations for this node.
×
5239
                return
×
5240
        }
×
5241
        delete(nodeReservations, pendingChanID)
3✔
5242

3✔
5243
        // If this was the last active reservation for this peer, delete the
3✔
5244
        // peer's entry altogether.
3✔
5245
        if len(nodeReservations) == 0 {
6✔
5246
                delete(f.activeReservations, peerIDKey)
3✔
5247
        }
3✔
5248
}
5249

5250
// getReservationCtx returns the reservation context for a particular pending
5251
// channel ID for a target peer.
5252
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5253
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
3✔
5254

3✔
5255
        peerIDKey := newSerializedKey(peerKey)
3✔
5256
        f.resMtx.RLock()
3✔
5257
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5258
        f.resMtx.RUnlock()
3✔
5259

3✔
5260
        if !ok {
6✔
5261
                return nil, errors.Errorf("unknown channel (id: %x) for "+
3✔
5262
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5263
        }
3✔
5264

5265
        return resCtx, nil
3✔
5266
}
5267

5268
// IsPendingChannel returns a boolean indicating whether the channel identified
5269
// by the pendingChanID and given peer is pending, meaning it is in the process
5270
// of being funded. After the funding transaction has been confirmed, the
5271
// channel will receive a new, permanent channel ID, and will no longer be
5272
// considered pending.
5273
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5274
        peer lnpeer.Peer) bool {
3✔
5275

3✔
5276
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5277
        f.resMtx.RLock()
3✔
5278
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5279
        f.resMtx.RUnlock()
3✔
5280

3✔
5281
        return ok
3✔
5282
}
3✔
5283

5284
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
3✔
5285
        var tmp btcec.JacobianPoint
3✔
5286
        pub.AsJacobian(&tmp)
3✔
5287
        tmp.ToAffine()
3✔
5288
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
3✔
5289
}
3✔
5290

5291
// defaultForwardingPolicy returns the default forwarding policy based on the
5292
// default routing policy and our local channel constraints.
5293
func (f *Manager) defaultForwardingPolicy(
5294
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
3✔
5295

3✔
5296
        return &models.ForwardingPolicy{
3✔
5297
                MinHTLCOut:    bounds.MinHTLC,
3✔
5298
                MaxHTLC:       bounds.MaxPendingAmount,
3✔
5299
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
3✔
5300
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
3✔
5301
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
3✔
5302
        }
3✔
5303
}
3✔
5304

5305
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5306
// chanPoint in the channelOpeningStateBucket.
5307
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5308
        forwardingPolicy *models.ForwardingPolicy) error {
3✔
5309

3✔
5310
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
3✔
5311
                chanID, forwardingPolicy,
3✔
5312
        )
3✔
5313
}
3✔
5314

5315
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5316
// channel id from the database which will be applied during the channel
5317
// announcement phase.
5318
func (f *Manager) getInitialForwardingPolicy(
5319
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
3✔
5320

3✔
5321
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
3✔
5322
}
3✔
5323

5324
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5325
// the database.
5326
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
3✔
5327
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
3✔
5328
}
3✔
5329

5330
// saveChannelOpeningState saves the channelOpeningState for the provided
5331
// chanPoint to the channelOpeningStateBucket.
5332
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5333
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
3✔
5334

3✔
5335
        var outpointBytes bytes.Buffer
3✔
5336
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5337
                return err
×
5338
        }
×
5339

5340
        // Save state and the uint64 representation of the shortChanID
5341
        // for later use.
5342
        scratch := make([]byte, 10)
3✔
5343
        byteOrder.PutUint16(scratch[:2], uint16(state))
3✔
5344
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
3✔
5345

3✔
5346
        return f.cfg.ChannelDB.SaveChannelOpeningState(
3✔
5347
                outpointBytes.Bytes(), scratch,
3✔
5348
        )
3✔
5349
}
5350

5351
// getChannelOpeningState fetches the channelOpeningState for the provided
5352
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5353
// is not found.
5354
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5355
        channelOpeningState, *lnwire.ShortChannelID, error) {
3✔
5356

3✔
5357
        var outpointBytes bytes.Buffer
3✔
5358
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5359
                return 0, nil, err
×
5360
        }
×
5361

5362
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
3✔
5363
                outpointBytes.Bytes(),
3✔
5364
        )
3✔
5365
        if err != nil {
6✔
5366
                return 0, nil, err
3✔
5367
        }
3✔
5368

5369
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
3✔
5370
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
3✔
5371
        return state, &shortChanID, nil
3✔
5372
}
5373

5374
// deleteChannelOpeningState removes any state for chanPoint from the database.
5375
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
3✔
5376
        var outpointBytes bytes.Buffer
3✔
5377
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
3✔
5378
                return err
×
5379
        }
×
5380

5381
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
3✔
5382
                outpointBytes.Bytes(),
3✔
5383
        )
3✔
5384
}
5385

5386
// selectShutdownScript selects the shutdown script we should send to the peer.
5387
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5388
// script.
5389
func (f *Manager) selectShutdownScript(taprootOK bool,
5390
) (lnwire.DeliveryAddress, error) {
×
5391

×
5392
        addrType := lnwallet.WitnessPubKey
×
5393
        if taprootOK {
×
5394
                addrType = lnwallet.TaprootPubkey
×
5395
        }
×
5396

5397
        addr, err := f.cfg.Wallet.NewAddress(
×
5398
                addrType, false, lnwallet.DefaultAccountName,
×
5399
        )
×
5400
        if err != nil {
×
5401
                return nil, err
×
5402
        }
×
5403

5404
        return txscript.PayToAddrScript(addr)
×
5405
}
5406

5407
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5408
// and then returns the online peer.
5409
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5410
        error) {
3✔
5411

3✔
5412
        peerChan := make(chan lnpeer.Peer, 1)
3✔
5413

3✔
5414
        var peerKey [33]byte
3✔
5415
        copy(peerKey[:], peerPubkey.SerializeCompressed())
3✔
5416

3✔
5417
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
3✔
5418

3✔
5419
        var peer lnpeer.Peer
3✔
5420
        select {
3✔
5421
        case peer = <-peerChan:
3✔
5422
        case <-f.quit:
1✔
5423
                return peer, ErrFundingManagerShuttingDown
1✔
5424
        }
5425
        return peer, nil
3✔
5426
}
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