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

lightningnetwork / lnd / 16569502135

28 Jul 2025 12:50PM UTC coverage: 67.251% (+0.02%) from 67.227%
16569502135

Pull #9455

github

web-flow
Merge b3899c4fd into 2e36f9b8b
Pull Request #9455: discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

179 of 208 new or added lines in 6 files covered. (86.06%)

105 existing lines in 23 files now uncovered.

135676 of 201746 relevant lines covered (67.25%)

21711.59 hits per line

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

74.44
/funding/manager.go
1
package funding
2

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

13
        "github.com/btcsuite/btcd/blockchain"
14
        "github.com/btcsuite/btcd/btcec/v2"
15
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
16
        "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
17
        "github.com/btcsuite/btcd/btcutil"
18
        "github.com/btcsuite/btcd/chaincfg/chainhash"
19
        "github.com/btcsuite/btcd/txscript"
20
        "github.com/btcsuite/btcd/wire"
21
        "github.com/davecgh/go-spew/spew"
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 {
367✔
67
        scratch := make([]byte, 4)
367✔
68

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

73
        byteOrder.PutUint32(scratch, o.Index)
367✔
74
        _, err := w.Write(scratch)
367✔
75
        return err
367✔
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 {
6✔
175
        r.updateMtx.RLock()
6✔
176
        defer r.updateMtx.RUnlock()
6✔
177

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

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

137✔
187
        r.lastUpdated = time.Now()
137✔
188
}
137✔
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 {
383✔
327
        var s serializedPubKey
383✔
328
        copy(s[:], pubKey.SerializeCompressed())
383✔
329
        return s
383✔
330
}
383✔
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)
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)
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)
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) {
110✔
683
        return &Manager{
110✔
684
                cfg:       &cfg,
110✔
685
                chanIDKey: cfg.TempChanIDSeed,
110✔
686
                activeReservations: make(
110✔
687
                        map[serializedPubKey]pendingChannels,
110✔
688
                ),
110✔
689
                signedReservations: make(
110✔
690
                        map[lnwire.ChannelID][32]byte,
110✔
691
                ),
110✔
692
                fundingMsgs: make(
110✔
693
                        chan *fundingMsg, msgBufferSize,
110✔
694
                ),
110✔
695
                fundingRequests: make(
110✔
696
                        chan *InitFundingMsg, msgBufferSize,
110✔
697
                ),
110✔
698
                localDiscoverySignals: &lnutils.SyncMap[
110✔
699
                        lnwire.ChannelID, chan struct{},
110✔
700
                ]{},
110✔
701
                handleChannelReadyBarriers: &lnutils.SyncMap[
110✔
702
                        lnwire.ChannelID, struct{},
110✔
703
                ]{},
110✔
704
                pendingMusigNonces: make(
110✔
705
                        map[lnwire.ChannelID]*musig2.Nonces,
110✔
706
                ),
110✔
707
                quit: make(chan struct{}),
110✔
708
        }, nil
110✔
709
}
110✔
710

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

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

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

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

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

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

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

2✔
765
                        // Rebroadcast the funding transaction for unconfirmed
2✔
766
                        // zero-conf channels if we have the funding tx and are
2✔
767
                        // also the initiator.
2✔
768
                        f.rebroadcastFundingTx(channel)
2✔
769
                }
2✔
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)
12✔
776
                go f.advanceFundingState(channel, chanID, nil)
12✔
777
        }
778

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

110✔
782
        return nil
110✔
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 {
107✔
788
        f.stopped.Do(func() {
213✔
789
                log.Info("Funding manager shutting down...")
106✔
790
                defer log.Debug("Funding manager shutdown complete")
106✔
791

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

796
        return nil
107✔
797
}
798

799
// rebroadcastFundingTx publishes the funding tx on startup for each
800
// unconfirmed channel.
801
func (f *Manager) rebroadcastFundingTx(c *channeldb.OpenChannel) {
6✔
802
        var fundingTxBuf bytes.Buffer
6✔
803
        err := c.FundingTxn.Serialize(&fundingTxBuf)
6✔
804
        if err != nil {
6✔
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 {
6✔
813
                log.Debugf("Rebroadcasting funding tx for ChannelPoint(%v): "+
6✔
814
                        "%x", c.FundingOutpoint, fundingTxBuf.Bytes())
6✔
815
        }
6✔
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)
6✔
820

6✔
821
        err = f.cfg.PublishTransaction(c.FundingTxn, label)
6✔
822
        if err != nil {
6✔
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 {
59✔
836
        // Obtain a fresh nonce. We do this by encoding the incremented nonce.
59✔
837
        nextNonce := f.chanIDNonce.Add(1)
59✔
838

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

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

59✔
852
        return nextChanID
59✔
853
}
59✔
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 {
148✔
916
        return &chanIdentifier{
148✔
917
                tempChanID: tempChanID,
148✔
918
        }
148✔
919
}
148✔
920

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

927
// hasChanID returns true if the active channel ID has been set.
928
func (c *chanIdentifier) hasChanID() bool {
25✔
929
        return c.chanIDSet
25✔
930
}
25✔
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) {
25✔
941

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

25✔
945
        // First, notify Brontide to remove the pending channel.
25✔
946
        //
25✔
947
        // NOTE: depending on where we fail the flow, we may not have the
25✔
948
        // active channel ID yet.
25✔
949
        if cid.hasChanID() {
33✔
950
                err := peer.RemovePendingChannel(cid.chanID)
8✔
951
                if err != nil {
8✔
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(
25✔
959
                peer.IdentityKey(), cid.tempChanID, false,
25✔
960
        )
25✔
961
        if err != nil {
38✔
962
                log.Errorf("unable to cancel reservation: %v", err)
13✔
963
        }
13✔
964

965
        // In case the case where the reservation existed, send the funding
966
        // error on the error channel.
967
        if ctx != nil {
40✔
968
                ctx.err <- fundingErr
15✔
969
        }
15✔
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
25✔
974
        switch e := fundingErr.(type) {
25✔
975
        // Let the actual error message be sent to the remote for the
976
        // whitelisted types.
977
        case lnwallet.ReservationError:
9✔
978
                msg = lnwire.ErrorData(e.Error())
9✔
979
        case lnwire.FundingError:
7✔
980
                msg = lnwire.ErrorData(e.Error())
7✔
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:
15✔
986
                msg = lnwire.ErrorData("funding failed due to internal error")
15✔
987
        }
988

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

25✔
994
        log.Debugf("Sending funding error to peer (%x): %v",
25✔
995
                peer.IdentityKey().SerializeCompressed(), spew.Sdump(errMsg))
25✔
996
        if err := peer.SendMessage(false, errMsg); err != nil {
26✔
997
                log.Errorf("unable to send error message to peer %v", err)
1✔
998
        }
1✔
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() {
110✔
1028
        defer f.wg.Done()
110✔
1029

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

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

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

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

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

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

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

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

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

1065
                case <-f.quit:
106✔
1066
                        return
106✔
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) {
66✔
1082

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

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

1097
        var chanOpts []lnwallet.ChannelOpt
45✔
1098
        f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
87✔
1099
                chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
42✔
1100
        })
42✔
1101
        f.cfg.AuxSigner.WhenSome(func(s lnwallet.AuxSigner) {
87✔
1102
                chanOpts = append(chanOpts, lnwallet.WithAuxSigner(s))
42✔
1103
        })
42✔
1104
        f.cfg.AuxResolver.WhenSome(func(s lnwallet.AuxContractResolver) {
45✔
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(
45✔
1110
                nil, channel, nil, chanOpts...,
45✔
1111
        )
45✔
1112
        if err != nil {
45✔
1113
                log.Errorf("Unable to create LightningChannel(%v): %v",
×
1114
                        channel.FundingOutpoint, err)
×
1115
                return
×
1116
        }
×
1117

1118
        for {
194✔
1119
                channelState, shortChanID, err := f.getChannelOpeningState(
149✔
1120
                        &channel.FundingOutpoint,
149✔
1121
                )
149✔
1122
                if err == channeldb.ErrChannelNotFound {
177✔
1123
                        // Channel not in fundingManager's opening database,
28✔
1124
                        // meaning it was successfully announced to the
28✔
1125
                        // network.
28✔
1126
                        // TODO(halseth): could do graph consistency check
28✔
1127
                        // here, and re-add the edge if missing.
28✔
1128
                        log.Debugf("ChannelPoint(%v) with chan_id=%x not "+
28✔
1129
                                "found in opening database, assuming already "+
28✔
1130
                                "announced to the network",
28✔
1131
                                channel.FundingOutpoint, pendingChanID)
28✔
1132
                        return
28✔
1133
                } else if err != nil {
152✔
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(
124✔
1145
                        channel, lnChannel, shortChanID, pendingChanID,
124✔
1146
                        channelState, updateChan,
124✔
1147
                )
124✔
1148
                if err != nil {
144✔
1149
                        log.Errorf("Unable to advance state(%v): %v",
20✔
1150
                                channel.FundingOutpoint, err)
20✔
1151
                        return
20✔
1152
                }
20✔
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 {
124✔
1165

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

124✔
1170
        switch channelState {
124✔
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:
38✔
1174
                err := f.sendChannelReady(channel, lnChannel)
38✔
1175
                if err != nil {
39✔
1176
                        return fmt.Errorf("failed sending channelReady: %w",
1✔
1177
                                err)
1✔
1178
                }
1✔
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(
37✔
1185
                        &channel.FundingOutpoint, channelReadySent,
37✔
1186
                        shortChanID,
37✔
1187
                )
37✔
1188
                if err != nil {
37✔
1189
                        return fmt.Errorf("error setting channel state to"+
×
1190
                                " channelReadySent: %w", err)
×
1191
                }
×
1192

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

37✔
1196
                return nil
37✔
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:
61✔
1201
                // We must wait until we've received the peer's channel_ready
61✔
1202
                // before sending a channel_update according to BOLT#07.
61✔
1203
                received, err := f.receivedChannelReady(
61✔
1204
                        channel.IdentityPub, chanID,
61✔
1205
                )
61✔
1206
                if err != nil {
61✔
UNCOV
1207
                        return fmt.Errorf("failed to check if channel_ready "+
×
UNCOV
1208
                                "was received: %v", err)
×
UNCOV
1209
                }
×
1210

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

1221
                        return nil
25✔
1222
                }
1223

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

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

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

1247
                err := f.annAfterSixConfs(channel, shortChanID)
29✔
1248
                if err != nil {
34✔
1249
                        return fmt.Errorf("error sending channel "+
5✔
1250
                                "announcement: %v", err)
5✔
1251
                }
5✔
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)
27✔
1259
                if err != nil {
27✔
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)
27✔
1269
                if err != nil {
27✔
1270
                        log.Infof("Could not delete initial policy for chanId "+
×
1271
                                "%x", chanID)
×
1272
                }
×
1273

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

27✔
1277
                return nil
27✔
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 {
58✔
1287

58✔
1288
        if channel.IsZeroConf() {
65✔
1289
                // Persist the alias to the alias database.
7✔
1290
                baseScid := channel.ShortChannelID
7✔
1291
                err := f.cfg.AliasManager.AddLocalAlias(
7✔
1292
                        baseScid, baseScid, true, false,
7✔
1293
                )
7✔
1294
                if err != nil {
7✔
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(
7✔
1304
                        &channel.FundingOutpoint, markedOpen,
7✔
1305
                        &channel.ShortChannelID,
7✔
1306
                )
7✔
1307
                if err != nil {
7✔
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)
7✔
1315
                if err != nil {
7✔
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
                f.cfg.NotifyOpenChannelEvent(
7✔
1323
                        channel.FundingOutpoint, channel.IdentityPub,
7✔
1324
                )
7✔
1325

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

1334
                return nil
7✔
1335
        }
1336

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

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

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

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

×
1364
                        return err
×
1365
                }
×
1366

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

×
1376
                        return err
×
1377
                }
×
1378

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

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

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

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

1405
        return nil
33✔
1406
}
1407

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

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

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

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

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

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

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

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

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

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

7✔
1481
                return
7✔
1482
        }
7✔
1483

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1644
                return
×
1645

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

×
1654
                return
×
1655
        }
1656

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

×
1671
                return
×
1672
        }
×
1673

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

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

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

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

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

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

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

1734
        reservation.SetNumConfsRequired(numConfsReq)
50✔
1735

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1923
                        return
×
1924
                }
×
1925

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2112
                minDepth = 1
×
2113
        }
×
2114

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

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

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

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

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

×
2183
                        return
×
2184
                }
×
2185

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2423
                        return
×
2424
                }
×
2425

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

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

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

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

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

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

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

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

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

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

×
2491
                        return
×
2492
                }
×
2493

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

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

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

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

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

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

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

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

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

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

×
2598
                        return
×
2599
                }
×
2600

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

×
2611
                        return
×
2612
                }
×
2613
        }
2614

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2745
                return
×
2746
        }
×
2747

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

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

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

×
2774
                        return
×
2775
                }
×
2776

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2986
        return timeoutErr
5✔
2987
}
2988

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

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

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

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

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

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

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

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

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

3049
                return pkScript, nil
8✔
3050
        }
3051

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3182
        defer epochClient.Cancel()
28✔
3183

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3341
        return nil
33✔
3342
}
3343

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3488
        return nil
37✔
3489
}
3490

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

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

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

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

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

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

27✔
3531
        return !loaded, nil
27✔
3532
}
3533

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

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

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

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

3561
        return fwdMinHTLC, fwdMaxHTLC
29✔
3562
}
3563

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

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

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

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

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

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

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

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

3637
        return nil
29✔
3638
}
3639

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3790
        return nil
27✔
3791
}
3792

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

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

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

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

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

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

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

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

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

7✔
3878
        return nil
7✔
3879
}
3880

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

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

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

3907
        return verNonce, nil
7✔
3908
}
3909

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
4116
                        return
×
4117
                }
×
4118

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

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

×
4144
                        return
×
4145
                }
×
4146
        }
4147

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

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

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

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

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

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

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

4209
                peerAlias = &foundAlias
7✔
4210
        }
4211

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

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

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

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

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

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

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

4271
        return nil
27✔
4272
}
4273

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

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

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

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

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

4319
        return nil
29✔
4320
}
4321

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4621
        return nil
19✔
4622
}
4623

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
4784
                        return
×
4785
                }
×
4786
        }
4787

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

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

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

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

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

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

×
4829
                return
×
4830
        }
×
4831

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5197
        delete(nodeReservations, pendingChanID)
17✔
5198

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

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

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

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

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

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

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

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

5245
        return resCtx, nil
91✔
5246
}
5247

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

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

3✔
5261
        return ok
3✔
5262
}
3✔
5263

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

106✔
5392
        peerChan := make(chan lnpeer.Peer, 1)
106✔
5393

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

106✔
5397
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
106✔
5398

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