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

lightningnetwork / lnd / 17820705803

18 Sep 2025 06:59AM UTC coverage: 66.637% (-0.02%) from 66.657%
17820705803

push

github

web-flow
Merge pull request #10228 from ellemouton/fixNilAssignment

autopilot: fix nil map assignment

1 of 4 new or added lines in 3 files covered. (25.0%)

87 existing lines in 19 files now uncovered.

136277 of 204507 relevant lines covered (66.64%)

21432.68 hits per line

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

73.74
/funding/manager.go
1
package funding
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

102
        msgBufferSize = 50
103

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

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

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

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

129
        zeroID [32]byte
130
)
131

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

145
        chanAmt btcutil.Amount
146

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

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

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

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

164
        updateMtx   sync.RWMutex
165
        lastUpdated time.Time
166

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

112✔
781
        return nil
112✔
782
}
783

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

108✔
791
                close(f.quit)
108✔
792
                f.wg.Wait()
108✔
793
        })
108✔
794

795
        return nil
109✔
796
}
797

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

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

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

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

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

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

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

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

60✔
851
        return nextChanID
60✔
852
}
60✔
853

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

24✔
993
        log.Debugf("Sending funding error to peer (%x): %v",
24✔
994
                peer.IdentityKey().SerializeCompressed(),
24✔
995
                lnutils.SpewLogClosure(errMsg))
24✔
996

24✔
997
        if err := peer.SendMessage(false, errMsg); err != nil {
24✔
UNCOV
998
                log.Errorf("unable to send error message to peer %v", err)
×
UNCOV
999
        }
×
1000
}
1001

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

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

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

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

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

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

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

112✔
1034
        for {
496✔
1035
                select {
384✔
1036
                case fmsg := <-f.fundingMsgs:
218✔
1037
                        switch msg := fmsg.msg.(type) {
218✔
1038
                        case *lnwire.OpenChannel:
57✔
1039
                                f.fundeeProcessOpenChannel(fmsg.peer, msg)
57✔
1040

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

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

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

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

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

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

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

1066
                case <-f.quit:
108✔
1067
                        return
108✔
1068
                }
1069
        }
1070
}
1071

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

68✔
1084
        defer f.wg.Done()
68✔
1085

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

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

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

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

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

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

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

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

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

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

37✔
1197
                return nil
37✔
1198

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

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

1222
                        return nil
27✔
1223
                }
1224

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

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

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

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

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

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

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

27✔
1278
                return nil
27✔
1279
        }
1280

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

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

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

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

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

1321
                // Inform the ChannelNotifier that the channel has transitioned
1322
                // from pending open to open.
1323
                f.cfg.NotifyOpenChannelEvent(
7✔
1324
                        channel.FundingOutpoint, channel.IdentityPub,
7✔
1325
                )
7✔
1326

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

1335
                return nil
7✔
1336
        }
1337

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

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

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

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

×
1365
                        return err
×
1366
                }
×
1367

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

×
1377
                        return err
×
1378
                }
×
1379

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

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

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

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

1406
        return nil
33✔
1407
}
1408

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

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

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

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

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

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

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

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

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

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

7✔
1482
                return
7✔
1483
        }
7✔
1484

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1645
                return
×
1646

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

×
1655
                return
×
1656
        }
1657

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

×
1672
                return
×
1673
        }
×
1674

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

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

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

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

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

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

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

1735
        reservation.SetNumConfsRequired(numConfsReq)
50✔
1736

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1924
                        return
×
1925
                }
×
1926

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

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

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

44✔
1948
        reservation.SetState(lnwallet.SentAcceptChannel)
44✔
1949

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

44✔
1972
        if commitType.IsTaproot() {
49✔
1973
                fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
1974
                        ourContribution.LocalNonce.PubNonce,
5✔
1975
                )
5✔
1976
        }
5✔
1977

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2113
                minDepth = 1
×
2114
        }
×
2115

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

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

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

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

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

×
2184
                        return
×
2185
                }
×
2186

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

2192
        err = resCtx.reservation.ProcessContribution(remoteContribution)
33✔
2193

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2424
                        return
×
2425
                }
×
2426

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

2439
        resCtx.reservation.SetState(lnwallet.SentFundingCreated)
33✔
2440

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

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

31✔
2458
        peerKey := peer.IdentityKey()
31✔
2459
        pendingChanID := msg.PendingChannelID
31✔
2460

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

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

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

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

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

×
2492
                        return
×
2493
                }
×
2494

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

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

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

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

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

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

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

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

31✔
2585
        fundingSigned := &lnwire.FundingSigned{}
31✔
2586

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

×
2599
                        return
×
2600
                }
×
2601

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

×
2612
                        return
×
2613
                }
×
2614
        }
2615

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

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

31✔
2629
        fundingSigned.ChanID = cid.chanID
31✔
2630

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2746
                return
×
2747
        }
×
2748

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

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

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

×
2775
                        return
×
2776
                }
×
2777

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2987
        return timeoutErr
5✔
2988
}
2989

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

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

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

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

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

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

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

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

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

3050
                return pkScript, nil
8✔
3051
        }
3052

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

3061
        return input.WitnessScriptHash(multiSigScript)
77✔
3062
}
3063

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

62✔
3078
        defer f.wg.Done()
62✔
3079
        defer close(confChan)
62✔
3080

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

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

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

3110
        log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
62✔
3111
                txid, numConfs)
62✔
3112

62✔
3113
        // Wait until the specified number of confirmations has been reached,
62✔
3114
        // we get a cancel signal, or the wallet signals a shutdown.
62✔
3115
        for {
151✔
3116
                select {
89✔
3117
                case updDetails, ok := <-confNtfn.Updates:
28✔
3118
                        if !ok {
28✔
3119
                                log.Warnf("ChainNotifier shutting down, "+
×
3120
                                        "cannot process updates for "+
×
3121
                                        "ChannelPoint(%v)",
×
3122
                                        completeChan.FundingOutpoint)
×
3123

×
3124
                                return
×
3125
                        }
×
3126

3127
                        log.Debugf("funding tx %s received confirmation in "+
28✔
3128
                                "block %d, %d confirmations left", txid,
28✔
3129
                                updDetails.BlockHeight, updDetails.NumConfsLeft)
28✔
3130

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

×
3145
                                        return
×
3146
                                }
×
3147
                        }
3148

3149
                case _, ok := <-confNtfn.NegativeConf:
4✔
3150
                        if !ok {
4✔
3151
                                log.Warnf("ChainNotifier shutting down, "+
×
3152
                                        "cannot track negative confirmations "+
×
3153
                                        "for ChannelPoint(%v)",
×
3154
                                        completeChan.FundingOutpoint)
×
3155

×
3156
                                return
×
3157
                        }
×
3158

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

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

×
3170
                                return
×
3171
                        }
×
3172

3173
                case confDetails, ok := <-confNtfn.Confirmed:
37✔
3174
                        if !ok {
37✔
3175
                                log.Warnf("ChainNotifier shutting down, "+
×
3176
                                        "cannot complete funding flow for "+
×
3177
                                        "ChannelPoint(%v)",
×
3178
                                        completeChan.FundingOutpoint)
×
3179

×
3180
                                return
×
3181
                        }
×
3182

3183
                        log.Debugf("funding tx %s for ChannelPoint(%v) "+
37✔
3184
                                "confirmed in block %d", txid,
37✔
3185
                                completeChan.FundingOutpoint,
37✔
3186
                                confDetails.BlockHeight)
37✔
3187

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

×
3204
                                        return
×
3205
                                }
×
3206
                        }
3207

3208
                        err := f.handleConfirmation(
37✔
3209
                                confDetails, completeChan, confChan,
37✔
3210
                        )
37✔
3211
                        if err != nil {
37✔
3212
                                log.Errorf("Error handling confirmation for "+
×
3213
                                        "ChannelPoint(%v), txid=%v: %v",
×
3214
                                        completeChan.FundingOutpoint, txid, err)
×
3215
                        }
×
3216

3217
                        return
37✔
3218

3219
                case <-cancelChan:
8✔
3220
                        log.Warnf("canceled waiting for funding confirmation, "+
8✔
3221
                                "stopping funding flow for ChannelPoint(%v)",
8✔
3222
                                completeChan.FundingOutpoint)
8✔
3223

8✔
3224
                        return
8✔
3225

3226
                case <-f.quit:
23✔
3227
                        log.Warnf("fundingManager shutting down, stopping "+
23✔
3228
                                "funding flow for ChannelPoint(%v)",
23✔
3229
                                completeChan.FundingOutpoint)
23✔
3230

23✔
3231
                        return
23✔
3232
                }
3233
        }
3234
}
3235

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

37✔
3243
        fundingPoint := completeChan.FundingOutpoint
37✔
3244
        log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
37✔
3245
                fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
37✔
3246

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

37✔
3256
        select {
37✔
3257
        case confChan <- &confirmedChannel{
3258
                shortChanID: shortChanID,
3259
                fundingTx:   confDetails.Tx,
3260
        }:
37✔
3261
        case <-f.quit:
×
3262
                return fmt.Errorf("manager shutting down")
×
3263
        }
3264

3265
        return nil
37✔
3266
}
3267

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

29✔
3278
        defer f.wg.Done()
29✔
3279

29✔
3280
        epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
29✔
3281
        if err != nil {
29✔
3282
                timeoutChan <- fmt.Errorf("unable to register for epoch "+
×
3283
                        "notification: %v", err)
×
3284
                return
×
3285
        }
×
3286

3287
        defer epochClient.Cancel()
29✔
3288

29✔
3289
        // The value of waitBlocksForFundingConf is adjusted in a development
29✔
3290
        // environment to enhance test capabilities. Otherwise, it is set to
29✔
3291
        // DefaultMaxWaitNumBlocksFundingConf.
29✔
3292
        waitBlocksForFundingConf := uint32(
29✔
3293
                lncfg.DefaultMaxWaitNumBlocksFundingConf,
29✔
3294
        )
29✔
3295

29✔
3296
        if lncfg.IsDevBuild() {
32✔
3297
                waitBlocksForFundingConf =
3✔
3298
                        f.cfg.Dev.MaxWaitNumBlocksFundingConf
3✔
3299
        }
3✔
3300

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

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

5✔
3321
                                // Notify the caller of the timeout.
5✔
3322
                                close(timeoutChan)
5✔
3323
                                return
5✔
3324
                        }
5✔
3325

3326
                        // TODO: If we are the channel initiator implement
3327
                        // a method for recovering the funds from the funding
3328
                        // transaction
3329

3330
                case <-cancelChan:
18✔
3331
                        return
18✔
3332

3333
                case <-f.quit:
12✔
3334
                        // The fundingManager is shutting down, will resume
12✔
3335
                        // waiting for the funding transaction on startup.
12✔
3336
                        return
12✔
3337
                }
3338
        }
3339
}
3340

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

19✔
3351
                // For zero-conf channels, we'll use the actually-confirmed
19✔
3352
                // short channel id.
19✔
3353
                if c.IsZeroConf() {
24✔
3354
                        shortChanID = c.ZeroConfRealScid()
5✔
3355
                }
5✔
3356

3357
                label := labels.MakeLabel(
19✔
3358
                        labels.LabelTypeChannelOpen, &shortChanID,
19✔
3359
                )
19✔
3360

19✔
3361
                err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
19✔
3362
                if err != nil {
19✔
3363
                        log.Errorf("unable to update label: %v", err)
×
3364
                }
×
3365
        }
3366
}
3367

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

33✔
3376
        fundingPoint := completeChan.FundingOutpoint
33✔
3377
        chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
33✔
3378

33✔
3379
        // TODO(roasbeef): ideally persistent state update for chan above
33✔
3380
        // should be abstracted
33✔
3381

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

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

3399
                err = f.cfg.AliasManager.AddLocalAlias(
5✔
3400
                        aliasScid, confChannel.shortChanID, true, false,
5✔
3401
                )
5✔
3402
                if err != nil {
5✔
3403
                        return fmt.Errorf("unable to request alias: %w", err)
×
3404
                }
×
3405
        }
3406

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

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

3429
        // Update the confirmed funding transaction label.
3430
        f.makeLabelForTx(completeChan)
33✔
3431

33✔
3432
        // Inform the ChannelNotifier that the channel has transitioned from
33✔
3433
        // pending open to open.
33✔
3434
        f.cfg.NotifyOpenChannelEvent(
33✔
3435
                completeChan.FundingOutpoint, completeChan.IdentityPub,
33✔
3436
        )
33✔
3437

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

3446
        return nil
33✔
3447
}
3448

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

38✔
3455
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
38✔
3456

38✔
3457
        var peerKey [33]byte
38✔
3458
        copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
38✔
3459

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

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

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

3490
                        // Now that we've generated the nonce for this channel,
3491
                        // we'll store it in the set of pending nonces.
3492
                        localNonce = newNonce
7✔
3493
                        f.pendingMusigNonces[chanID] = localNonce
7✔
3494
                }
3495
                f.nonceMtx.Unlock()
7✔
3496

7✔
3497
                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
7✔
3498
                        localNonce.PubNonce,
7✔
3499
                )
7✔
3500
        }
3501

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

3515
                // We can use a pointer to aliases since GetAliases returns a
3516
                // copy of the alias slice.
3517
                channelReadyMsg.AliasScid = &aliases[0]
9✔
3518
        }
3519

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

3537
                localAlias := peer.LocalFeatures().HasFeature(
37✔
3538
                        lnwire.ScidAliasOptional,
37✔
3539
                )
37✔
3540
                remoteAlias := peer.RemoteFeatures().HasFeature(
37✔
3541
                        lnwire.ScidAliasOptional,
37✔
3542
                )
37✔
3543

37✔
3544
                // We could also refresh the channel state instead of checking
37✔
3545
                // whether the feature was negotiated, but this saves us a
37✔
3546
                // database read.
37✔
3547
                if channelReadyMsg.AliasScid == nil && localAlias &&
37✔
3548
                        remoteAlias {
37✔
3549

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

3566
                                err = f.cfg.AliasManager.AddLocalAlias(
×
3567
                                        alias, completeChan.ShortChannelID,
×
3568
                                        false, false,
×
3569
                                )
×
3570
                                if err != nil {
×
3571
                                        return err
×
3572
                                }
×
3573

3574
                                channelReadyMsg.AliasScid = &alias
×
3575
                        } else {
×
3576
                                channelReadyMsg.AliasScid = &aliases[0]
×
3577
                        }
×
3578
                }
3579

3580
                log.Infof("Peer(%x) is online, sending ChannelReady "+
37✔
3581
                        "for ChannelID(%v)", peerKey, chanID)
37✔
3582

37✔
3583
                if err := peer.SendMessage(true, channelReadyMsg); err == nil {
74✔
3584
                        // Sending succeeded, we can break out and continue the
37✔
3585
                        // funding flow.
37✔
3586
                        break
37✔
3587
                }
3588

3589
                log.Warnf("Unable to send channelReady to peer %x: %v. "+
×
3590
                        "Will retry when online", peerKey, err)
×
3591
        }
3592

3593
        return nil
37✔
3594
}
3595

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

63✔
3601
        // If the funding manager has exited, return an error to stop looping.
63✔
3602
        // Note that the peer may appear as online while the funding manager
63✔
3603
        // has stopped due to the shutdown order in the server.
63✔
3604
        select {
63✔
3605
        case <-f.quit:
1✔
3606
                return false, ErrFundingManagerShuttingDown
1✔
3607
        default:
62✔
3608
        }
3609

3610
        // Avoid a tight loop if peer is offline.
3611
        if _, err := f.waitForPeerOnline(node); err != nil {
62✔
3612
                log.Errorf("Wait for peer online failed: %v", err)
×
3613
                return false, err
×
3614
        }
×
3615

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

3625
        // If we haven't insert the next revocation point, we haven't finished
3626
        // processing the channel ready message.
3627
        if channel.RemoteNextRevocation == nil {
99✔
3628
                return false, nil
37✔
3629
        }
37✔
3630

3631
        // Finally, the barrier signal is removed once we finish
3632
        // `handleChannelReady`. If we can still find the signal, we haven't
3633
        // finished processing it yet.
3634
        _, loaded := f.handleChannelReadyBarriers.Load(chanID)
28✔
3635

28✔
3636
        return !loaded, nil
28✔
3637
}
3638

3639
// extractAnnounceParams extracts the various channel announcement and update
3640
// parameters that will be needed to construct a ChannelAnnouncement and a
3641
// ChannelUpdate.
3642
func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
3643
        lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
29✔
3644

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

29✔
3651
        // We don't necessarily want to go as low as the remote party allows.
29✔
3652
        // Check it against our default forwarding policy.
29✔
3653
        if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
32✔
3654
                fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
3✔
3655
        }
3✔
3656

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

3666
        return fwdMinHTLC, fwdMaxHTLC
29✔
3667
}
3668

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

29✔
3682
        chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
29✔
3683

29✔
3684
        fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
29✔
3685

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

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

×
3711
                                log.Debugf("Graph rejected "+
×
3712
                                        "ChannelAnnouncement: %v", err)
×
3713
                        } else {
×
3714
                                return fmt.Errorf("error sending channel "+
×
3715
                                        "announcement: %v", err)
×
3716
                        }
×
3717
                }
3718
        case <-f.quit:
×
3719
                return ErrFundingManagerShuttingDown
×
3720
        }
3721

3722
        errChan = f.cfg.SendAnnouncement(
29✔
3723
                ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
29✔
3724
        )
29✔
3725
        select {
29✔
3726
        case err := <-errChan:
29✔
3727
                if err != nil {
29✔
3728
                        if graph.IsError(err, graph.ErrOutdated,
×
3729
                                graph.ErrIgnored) {
×
3730

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

3742
        return nil
29✔
3743
}
3744

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

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

11✔
3762
                peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
11✔
3763
                if err != nil {
11✔
3764
                        return err
×
3765
                }
×
3766

3767
                nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
11✔
3768
                if err != nil {
11✔
3769
                        return fmt.Errorf("unable to retrieve current node "+
×
3770
                                "announcement: %v", err)
×
3771
                }
×
3772

3773
                chanID := lnwire.NewChanIDFromOutPoint(
11✔
3774
                        completeChan.FundingOutpoint,
11✔
3775
                )
11✔
3776
                pubKey := peer.PubKey()
11✔
3777
                log.Debugf("Sending our NodeAnnouncement for "+
11✔
3778
                        "ChannelID(%v) to %x", chanID, pubKey)
11✔
3779

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

21✔
3800
                fundingScript, err := makeFundingScript(completeChan)
21✔
3801
                if err != nil {
21✔
3802
                        return fmt.Errorf("unable to create funding script "+
×
3803
                                "for ChannelPoint(%v): %v",
×
3804
                                completeChan.FundingOutpoint, err)
×
3805
                }
×
3806

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

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

3831
                case <-f.quit:
5✔
3832
                        return fmt.Errorf("%v, stopping funding flow for "+
5✔
3833
                                "ChannelPoint(%v)",
5✔
3834
                                ErrFundingManagerShuttingDown,
5✔
3835
                                completeChan.FundingOutpoint)
5✔
3836
                }
3837

3838
                fundingPoint := completeChan.FundingOutpoint
19✔
3839
                chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
19✔
3840

19✔
3841
                log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
19✔
3842
                        &fundingPoint, shortChanID)
19✔
3843

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

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

3869
                        err = f.addToGraph(
3✔
3870
                                completeChan, &baseScid, nil, ourPolicy,
3✔
3871
                        )
3✔
3872
                        if err != nil {
3✔
3873
                                return fmt.Errorf("failed to re-add to "+
×
3874
                                        "graph: %v", err)
×
3875
                        }
×
3876
                }
3877

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

3891
                log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
19✔
3892
                        "sent to gossiper", &fundingPoint, shortChanID)
19✔
3893
        }
3894

3895
        return nil
27✔
3896
}
3897

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

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

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

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

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

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

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

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

3980
        // Update the confirmed transaction's label.
3981
        f.makeLabelForTx(c)
7✔
3982

7✔
3983
        return nil
7✔
3984
}
3985

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

7✔
3992
        musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
7✔
3993
                channel.RevocationProducer,
7✔
3994
        )
7✔
3995
        if err != nil {
7✔
3996
                return nil, fmt.Errorf("unable to generate musig channel "+
×
3997
                        "nonces: %v", err)
×
3998
        }
×
3999

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

4012
        return verNonce, nil
7✔
4013
}
4014

4015
// handleChannelReady finalizes the channel funding process and enables the
4016
// channel to enter normal operating mode.
4017
func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
4018
        msg *lnwire.ChannelReady) {
31✔
4019

31✔
4020
        defer f.wg.Done()
31✔
4021

31✔
4022
        // If we are in development mode, we'll wait for specified duration
31✔
4023
        // before processing the channel ready message.
31✔
4024
        if f.cfg.Dev != nil {
34✔
4025
                duration := f.cfg.Dev.ProcessChannelReadyWait
3✔
4026
                log.Warnf("Channel(%v): sleeping %v before processing "+
3✔
4027
                        "channel_ready", msg.ChanID, duration)
3✔
4028

3✔
4029
                select {
3✔
4030
                case <-time.After(duration):
3✔
4031
                        log.Warnf("Channel(%v): slept %v before processing "+
3✔
4032
                                "channel_ready", msg.ChanID, duration)
3✔
4033
                case <-f.quit:
×
4034
                        log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
×
4035
                        return
×
4036
                }
4037
        }
4038

4039
        log.Debugf("Received ChannelReady for ChannelID(%v) from "+
31✔
4040
                "peer %x", msg.ChanID,
31✔
4041
                peer.IdentityKey().SerializeCompressed())
31✔
4042

31✔
4043
        // We now load or create a new channel barrier for this channel.
31✔
4044
        _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
31✔
4045
                msg.ChanID, struct{}{},
31✔
4046
        )
31✔
4047

31✔
4048
        // If we are currently in the process of handling a channel_ready
31✔
4049
        // message for this channel, ignore.
31✔
4050
        if loaded {
35✔
4051
                log.Infof("Already handling channelReady for "+
4✔
4052
                        "ChannelID(%v), ignoring.", msg.ChanID)
4✔
4053
                return
4✔
4054
        }
4✔
4055

4056
        // If not already handling channelReady for this channel, then the
4057
        // `LoadOrStore` has set up a barrier, and it will be removed once this
4058
        // function exits.
4059
        defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
30✔
4060

30✔
4061
        localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
30✔
4062
        if ok {
58✔
4063
                // Before we proceed with processing the channel_ready
28✔
4064
                // message, we'll wait for the local waitForFundingConfirmation
28✔
4065
                // goroutine to signal that it has the necessary state in
28✔
4066
                // place. Otherwise, we may be missing critical information
28✔
4067
                // required to handle forwarded HTLC's.
28✔
4068
                select {
28✔
4069
                case <-localDiscoverySignal:
28✔
4070
                        // Fallthrough
4071
                case <-f.quit:
3✔
4072
                        return
3✔
4073
                }
4074

4075
                // With the signal received, we can now safely delete the entry
4076
                // from the map.
4077
                f.localDiscoverySignals.Delete(msg.ChanID)
28✔
4078
        }
4079

4080
        // First, we'll attempt to locate the channel whose funding workflow is
4081
        // being finalized by this message. We go to the database rather than
4082
        // our reservation map as we may have restarted, mid funding flow. Also
4083
        // provide the node's public key to make the search faster.
4084
        chanID := msg.ChanID
30✔
4085
        channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
30✔
4086
        if err != nil {
30✔
4087
                log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
×
4088
                        "funding", chanID)
×
4089
                return
×
4090
        }
×
4091

4092
        // If this is a taproot channel, then we can generate the set of nonces
4093
        // the remote party needs to send the next remote commitment here.
4094
        var firstVerNonce *musig2.Nonces
30✔
4095
        if channel.ChanType.IsTaproot() {
37✔
4096
                firstVerNonce, err = genFirstStateMusigNonce(channel)
7✔
4097
                if err != nil {
7✔
4098
                        log.Error(err)
×
4099
                        return
×
4100
                }
×
4101
        }
4102

4103
        // We'll need to store the received TLV alias if the option_scid_alias
4104
        // feature was negotiated. This will be used to provide route hints
4105
        // during invoice creation. In the zero-conf case, it is also used to
4106
        // provide a ChannelUpdate to the remote peer. This is done before the
4107
        // call to InsertNextRevocation in case the call to PutPeerAlias fails.
4108
        // If it were to fail on the first call to handleChannelReady, we
4109
        // wouldn't want the channel to be usable yet.
4110
        if channel.NegotiatedAliasFeature() {
39✔
4111
                // If the AliasScid field is nil, we must fail out. We will
9✔
4112
                // most likely not be able to route through the peer.
9✔
4113
                if msg.AliasScid == nil {
9✔
4114
                        log.Debugf("Consider closing ChannelID(%v), peer "+
×
4115
                                "does not implement the option-scid-alias "+
×
4116
                                "feature properly", chanID)
×
4117
                        return
×
4118
                }
×
4119

4120
                // We'll store the AliasScid so that invoice creation can use
4121
                // it.
4122
                err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
9✔
4123
                if err != nil {
9✔
4124
                        log.Errorf("unable to store peer's alias: %v", err)
×
4125
                        return
×
4126
                }
×
4127

4128
                // If we do not have an alias stored, we'll create one now.
4129
                // This is only used in the upgrade case where a user toggles
4130
                // the option-scid-alias feature-bit to on. We'll also send the
4131
                // channel_ready message here in case the link is created
4132
                // before sendChannelReady is called.
4133
                aliases := f.cfg.AliasManager.GetAliases(
9✔
4134
                        channel.ShortChannelID,
9✔
4135
                )
9✔
4136
                if len(aliases) == 0 {
9✔
4137
                        // No aliases were found so we'll request and store an
×
4138
                        // alias and use it in the channel_ready message.
×
4139
                        alias, err := f.cfg.AliasManager.RequestAlias()
×
4140
                        if err != nil {
×
4141
                                log.Errorf("unable to request alias: %v", err)
×
4142
                                return
×
4143
                        }
×
4144

4145
                        err = f.cfg.AliasManager.AddLocalAlias(
×
4146
                                alias, channel.ShortChannelID, false, false,
×
4147
                        )
×
4148
                        if err != nil {
×
4149
                                log.Errorf("unable to add local alias: %v",
×
4150
                                        err)
×
4151
                                return
×
4152
                        }
×
4153

4154
                        secondPoint, err := channel.SecondCommitmentPoint()
×
4155
                        if err != nil {
×
4156
                                log.Errorf("unable to fetch second "+
×
4157
                                        "commitment point: %v", err)
×
4158
                                return
×
4159
                        }
×
4160

4161
                        channelReadyMsg := lnwire.NewChannelReady(
×
4162
                                chanID, secondPoint,
×
4163
                        )
×
4164
                        channelReadyMsg.AliasScid = &alias
×
4165

×
4166
                        if firstVerNonce != nil {
×
4167
                                channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll
×
4168
                                        firstVerNonce.PubNonce,
×
4169
                                )
×
4170
                        }
×
4171

4172
                        err = peer.SendMessage(true, channelReadyMsg)
×
4173
                        if err != nil {
×
4174
                                log.Errorf("unable to send channel_ready: %v",
×
4175
                                        err)
×
4176
                                return
×
4177
                        }
×
4178
                }
4179
        }
4180

4181
        // If the RemoteNextRevocation is non-nil, it means that we have
4182
        // already processed channelReady for this channel, so ignore. This
4183
        // check is after the alias logic so we store the peer's most recent
4184
        // alias. The spec requires us to validate that subsequent
4185
        // channel_ready messages use the same per commitment point (the
4186
        // second), but it is not actually necessary since we'll just end up
4187
        // ignoring it. We are, however, required to *send* the same per
4188
        // commitment point, since another pedantic implementation might
4189
        // verify it.
4190
        if channel.RemoteNextRevocation != nil {
34✔
4191
                log.Infof("Received duplicate channelReady for "+
4✔
4192
                        "ChannelID(%v), ignoring.", chanID)
4✔
4193
                return
4✔
4194
        }
4✔
4195

4196
        // If this is a taproot channel, then we'll need to map the received
4197
        // nonces to a nonce pair, and also fetch our pending nonces, which are
4198
        // required in order to make the channel whole.
4199
        var chanOpts []lnwallet.ChannelOpt
29✔
4200
        if channel.ChanType.IsTaproot() {
36✔
4201
                f.nonceMtx.Lock()
7✔
4202
                localNonce, ok := f.pendingMusigNonces[chanID]
7✔
4203
                if !ok {
10✔
4204
                        // If there's no pending nonce for this channel ID,
3✔
4205
                        // we'll use the one generated above.
3✔
4206
                        localNonce = firstVerNonce
3✔
4207
                        f.pendingMusigNonces[chanID] = firstVerNonce
3✔
4208
                }
3✔
4209
                f.nonceMtx.Unlock()
7✔
4210

7✔
4211
                log.Infof("ChanID(%v): applying local+remote musig2 nonces",
7✔
4212
                        chanID)
7✔
4213

7✔
4214
                remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
7✔
4215
                        errNoLocalNonce,
7✔
4216
                )
7✔
4217
                if err != nil {
7✔
4218
                        cid := newChanIdentifier(msg.ChanID)
×
4219
                        f.sendWarning(peer, cid, err)
×
4220

×
4221
                        return
×
4222
                }
×
4223

4224
                chanOpts = append(
7✔
4225
                        chanOpts,
7✔
4226
                        lnwallet.WithLocalMusigNonces(localNonce),
7✔
4227
                        lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
7✔
4228
                                PubNonce: remoteNonce,
7✔
4229
                        }),
7✔
4230
                )
7✔
4231

7✔
4232
                // Inform the aux funding controller that the liquidity in the
7✔
4233
                // custom channel is now ready to be advertised. We potentially
7✔
4234
                // haven't sent our own channel ready message yet, but other
7✔
4235
                // than that the channel is ready to count toward available
7✔
4236
                // liquidity.
7✔
4237
                err = fn.MapOptionZ(
7✔
4238
                        f.cfg.AuxFundingController,
7✔
4239
                        func(controller AuxFundingController) error {
7✔
4240
                                return controller.ChannelReady(
×
4241
                                        lnwallet.NewAuxChanState(channel),
×
4242
                                )
×
4243
                        },
×
4244
                )
4245
                if err != nil {
7✔
4246
                        cid := newChanIdentifier(msg.ChanID)
×
4247
                        f.sendWarning(peer, cid, err)
×
4248

×
4249
                        return
×
4250
                }
×
4251
        }
4252

4253
        // The channel_ready message contains the next commitment point we'll
4254
        // need to create the next commitment state for the remote party. So
4255
        // we'll insert that into the channel now before passing it along to
4256
        // other sub-systems.
4257
        err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
29✔
4258
        if err != nil {
29✔
4259
                log.Errorf("unable to insert next commitment point: %v", err)
×
4260
                return
×
4261
        }
×
4262

4263
        // Before we can add the channel to the peer, we'll need to ensure that
4264
        // we have an initial forwarding policy set.
4265
        if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
29✔
4266
                log.Errorf("Unable to ensure initial forwarding policy: %v",
×
4267
                        err)
×
4268
        }
×
4269

4270
        err = peer.AddNewChannel(&lnpeer.NewChannel{
29✔
4271
                OpenChannel: channel,
29✔
4272
                ChanOpts:    chanOpts,
29✔
4273
        }, f.quit)
29✔
4274
        if err != nil {
29✔
UNCOV
4275
                log.Errorf("Unable to add new channel %v with peer %x: %v",
×
UNCOV
4276
                        channel.FundingOutpoint,
×
UNCOV
4277
                        peer.IdentityKey().SerializeCompressed(), err,
×
UNCOV
4278
                )
×
UNCOV
4279
        }
×
4280
}
4281

4282
// handleChannelReadyReceived is called once the remote's channelReady message
4283
// is received and processed. At this stage, we must have sent out our
4284
// channelReady message, once the remote's channelReady is processed, the
4285
// channel is now active, thus we change its state to `addedToGraph` to
4286
// let the channel start handling routing.
4287
func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
4288
        scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
4289
        updateChan chan<- *lnrpc.OpenStatusUpdate) error {
27✔
4290

27✔
4291
        chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
27✔
4292

27✔
4293
        // Since we've sent+received funding locked at this point, we
27✔
4294
        // can clean up the pending musig2 nonce state.
27✔
4295
        f.nonceMtx.Lock()
27✔
4296
        delete(f.pendingMusigNonces, chanID)
27✔
4297
        f.nonceMtx.Unlock()
27✔
4298

27✔
4299
        var peerAlias *lnwire.ShortChannelID
27✔
4300
        if channel.IsZeroConf() {
34✔
4301
                // We'll need to wait until channel_ready has been received and
7✔
4302
                // the peer lets us know the alias they want to use for the
7✔
4303
                // channel. With this information, we can then construct a
7✔
4304
                // ChannelUpdate for them.  If an alias does not yet exist,
7✔
4305
                // we'll just return, letting the next iteration of the loop
7✔
4306
                // check again.
7✔
4307
                var defaultAlias lnwire.ShortChannelID
7✔
4308
                chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
7✔
4309
                foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
7✔
4310
                if foundAlias == defaultAlias {
7✔
4311
                        return nil
×
4312
                }
×
4313

4314
                peerAlias = &foundAlias
7✔
4315
        }
4316

4317
        err := f.addToGraph(channel, scid, peerAlias, nil)
27✔
4318
        if err != nil {
27✔
4319
                return fmt.Errorf("failed adding to graph: %w", err)
×
4320
        }
×
4321

4322
        // As the channel is now added to the ChannelRouter's topology, the
4323
        // channel is moved to the next state of the state machine. It will be
4324
        // moved to the last state (actually deleted from the database) after
4325
        // the channel is finally announced.
4326
        err = f.saveChannelOpeningState(
27✔
4327
                &channel.FundingOutpoint, addedToGraph, scid,
27✔
4328
        )
27✔
4329
        if err != nil {
27✔
4330
                return fmt.Errorf("error setting channel state to"+
×
4331
                        " addedToGraph: %w", err)
×
4332
        }
×
4333

4334
        log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
27✔
4335
                "added to graph", chanID, scid)
27✔
4336

27✔
4337
        err = fn.MapOptionZ(
27✔
4338
                f.cfg.AuxFundingController,
27✔
4339
                func(controller AuxFundingController) error {
27✔
4340
                        return controller.ChannelReady(
×
4341
                                lnwallet.NewAuxChanState(channel),
×
4342
                        )
×
4343
                },
×
4344
        )
4345
        if err != nil {
27✔
4346
                return fmt.Errorf("failed notifying aux funding controller "+
×
4347
                        "about channel ready: %w", err)
×
4348
        }
×
4349

4350
        // Give the caller a final update notifying them that the channel is
4351
        fundingPoint := channel.FundingOutpoint
27✔
4352
        cp := &lnrpc.ChannelPoint{
27✔
4353
                FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
27✔
4354
                        FundingTxidBytes: fundingPoint.Hash[:],
27✔
4355
                },
27✔
4356
                OutputIndex: fundingPoint.Index,
27✔
4357
        }
27✔
4358

27✔
4359
        if updateChan != nil {
40✔
4360
                upd := &lnrpc.OpenStatusUpdate{
13✔
4361
                        Update: &lnrpc.OpenStatusUpdate_ChanOpen{
13✔
4362
                                ChanOpen: &lnrpc.ChannelOpenUpdate{
13✔
4363
                                        ChannelPoint: cp,
13✔
4364
                                },
13✔
4365
                        },
13✔
4366
                        PendingChanId: pendingChanID[:],
13✔
4367
                }
13✔
4368

13✔
4369
                select {
13✔
4370
                case updateChan <- upd:
13✔
4371
                case <-f.quit:
×
4372
                        return ErrFundingManagerShuttingDown
×
4373
                }
4374
        }
4375

4376
        return nil
27✔
4377
}
4378

4379
// ensureInitialForwardingPolicy ensures that we have an initial forwarding
4380
// policy set for the given channel. If we don't, we'll fall back to the default
4381
// values.
4382
func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
4383
        channel *channeldb.OpenChannel) error {
29✔
4384

29✔
4385
        // Before we can add the channel to the peer, we'll need to ensure that
29✔
4386
        // we have an initial forwarding policy set. This should always be the
29✔
4387
        // case except for a channel that was created with lnd <= 0.15.5 and
29✔
4388
        // is still pending while updating to this version.
29✔
4389
        var needDBUpdate bool
29✔
4390
        forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
29✔
4391
        if err != nil {
29✔
4392
                log.Errorf("Unable to fetch initial forwarding policy, "+
×
4393
                        "falling back to default values: %v", err)
×
4394

×
4395
                forwardingPolicy = f.defaultForwardingPolicy(
×
4396
                        channel.LocalChanCfg.ChannelStateBounds,
×
4397
                )
×
4398
                needDBUpdate = true
×
4399
        }
×
4400

4401
        // We only started storing the actual values for MinHTLCOut and MaxHTLC
4402
        // after 0.16.x, so if a channel was opened with such a version and is
4403
        // still pending while updating to this version, we'll need to set the
4404
        // values to the default values.
4405
        if forwardingPolicy.MinHTLCOut == 0 {
45✔
4406
                forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
16✔
4407
                needDBUpdate = true
16✔
4408
        }
16✔
4409
        if forwardingPolicy.MaxHTLC == 0 {
45✔
4410
                forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
16✔
4411
                needDBUpdate = true
16✔
4412
        }
16✔
4413

4414
        // And finally, if we found that the values currently stored aren't
4415
        // sufficient for the link, we'll update the database.
4416
        if needDBUpdate {
45✔
4417
                err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
16✔
4418
                if err != nil {
16✔
4419
                        return fmt.Errorf("unable to update initial "+
×
4420
                                "forwarding policy: %v", err)
×
4421
                }
×
4422
        }
4423

4424
        return nil
29✔
4425
}
4426

4427
// chanAnnouncement encapsulates the two authenticated announcements that we
4428
// send out to the network after a new channel has been created locally.
4429
type chanAnnouncement struct {
4430
        chanAnn       *lnwire.ChannelAnnouncement1
4431
        chanUpdateAnn *lnwire.ChannelUpdate1
4432
        chanProof     *lnwire.AnnounceSignatures1
4433
}
4434

4435
// newChanAnnouncement creates the authenticated channel announcement messages
4436
// required to broadcast a newly created channel to the network. The
4437
// announcement is two part: the first part authenticates the existence of the
4438
// channel and contains four signatures binding the funding pub keys and
4439
// identity pub keys of both parties to the channel, and the second segment is
4440
// authenticated only by us and contains our directional routing policy for the
4441
// channel. ourPolicy may be set in order to re-use an existing, non-default
4442
// policy.
4443
func (f *Manager) newChanAnnouncement(localPubKey,
4444
        remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
4445
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4446
        chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
4447
        ourPolicy *models.ChannelEdgePolicy,
4448
        chanType channeldb.ChannelType) (*chanAnnouncement, error) {
45✔
4449

45✔
4450
        chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
45✔
4451

45✔
4452
        // The unconditional section of the announcement is the ShortChannelID
45✔
4453
        // itself which compactly encodes the location of the funding output
45✔
4454
        // within the blockchain.
45✔
4455
        chanAnn := &lnwire.ChannelAnnouncement1{
45✔
4456
                ShortChannelID: shortChanID,
45✔
4457
                Features:       lnwire.NewRawFeatureVector(),
45✔
4458
                ChainHash:      chainHash,
45✔
4459
        }
45✔
4460

45✔
4461
        // If this is a taproot channel, then we'll set a special bit in the
45✔
4462
        // feature vector to indicate to the routing layer that this needs a
45✔
4463
        // slightly different type of validation.
45✔
4464
        //
45✔
4465
        // TODO(roasbeef): temp, remove after gossip 1.5
45✔
4466
        if chanType.IsTaproot() {
52✔
4467
                log.Debugf("Applying taproot feature bit to "+
7✔
4468
                        "ChannelAnnouncement for %v", chanID)
7✔
4469

7✔
4470
                chanAnn.Features.Set(
7✔
4471
                        lnwire.SimpleTaprootChannelsRequiredStaging,
7✔
4472
                )
7✔
4473
        }
7✔
4474

4475
        // The chanFlags field indicates which directed edge of the channel is
4476
        // being updated within the ChannelUpdateAnnouncement announcement
4477
        // below. A value of zero means it's the edge of the "first" node and 1
4478
        // being the other node.
4479
        var chanFlags lnwire.ChanUpdateChanFlags
45✔
4480

45✔
4481
        // The lexicographical ordering of the two identity public keys of the
45✔
4482
        // nodes indicates which of the nodes is "first". If our serialized
45✔
4483
        // identity key is lower than theirs then we're the "first" node and
45✔
4484
        // second otherwise.
45✔
4485
        selfBytes := localPubKey.SerializeCompressed()
45✔
4486
        remoteBytes := remotePubKey.SerializeCompressed()
45✔
4487
        if bytes.Compare(selfBytes, remoteBytes) == -1 {
69✔
4488
                copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
24✔
4489
                copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
24✔
4490
                copy(
24✔
4491
                        chanAnn.BitcoinKey1[:],
24✔
4492
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4493
                )
24✔
4494
                copy(
24✔
4495
                        chanAnn.BitcoinKey2[:],
24✔
4496
                        remoteFundingKey.SerializeCompressed(),
24✔
4497
                )
24✔
4498

24✔
4499
                // If we're the first node then update the chanFlags to
24✔
4500
                // indicate the "direction" of the update.
24✔
4501
                chanFlags = 0
24✔
4502
        } else {
48✔
4503
                copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
24✔
4504
                copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
24✔
4505
                copy(
24✔
4506
                        chanAnn.BitcoinKey1[:],
24✔
4507
                        remoteFundingKey.SerializeCompressed(),
24✔
4508
                )
24✔
4509
                copy(
24✔
4510
                        chanAnn.BitcoinKey2[:],
24✔
4511
                        localFundingKey.PubKey.SerializeCompressed(),
24✔
4512
                )
24✔
4513

24✔
4514
                // If we're the second node then update the chanFlags to
24✔
4515
                // indicate the "direction" of the update.
24✔
4516
                chanFlags = 1
24✔
4517
        }
24✔
4518

4519
        // Our channel update message flags will signal that we support the
4520
        // max_htlc field.
4521
        msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
45✔
4522

45✔
4523
        // We announce the channel with the default values. Some of
45✔
4524
        // these values can later be changed by crafting a new ChannelUpdate.
45✔
4525
        chanUpdateAnn := &lnwire.ChannelUpdate1{
45✔
4526
                ShortChannelID: shortChanID,
45✔
4527
                ChainHash:      chainHash,
45✔
4528
                Timestamp:      uint32(time.Now().Unix()),
45✔
4529
                MessageFlags:   msgFlags,
45✔
4530
                ChannelFlags:   chanFlags,
45✔
4531
                TimeLockDelta: uint16(
45✔
4532
                        f.cfg.DefaultRoutingPolicy.TimeLockDelta,
45✔
4533
                ),
45✔
4534
                HtlcMinimumMsat: fwdMinHTLC,
45✔
4535
                HtlcMaximumMsat: fwdMaxHTLC,
45✔
4536
        }
45✔
4537

45✔
4538
        // The caller of newChanAnnouncement is expected to provide the initial
45✔
4539
        // forwarding policy to be announced. If no persisted initial policy
45✔
4540
        // values are found, then we will use the default policy values in the
45✔
4541
        // channel announcement.
45✔
4542
        storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
45✔
4543
        if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
45✔
4544
                return nil, fmt.Errorf("unable to generate channel "+
×
4545
                        "update announcement: %w", err)
×
4546
        }
×
4547

4548
        switch {
45✔
4549
        case ourPolicy != nil:
3✔
4550
                // If ourPolicy is non-nil, modify the default parameters of the
3✔
4551
                // ChannelUpdate.
3✔
4552
                chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
3✔
4553
                chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
3✔
4554
                chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
3✔
4555
                chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
3✔
4556
                chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
3✔
4557
                chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
3✔
4558
                chanUpdateAnn.FeeRate = uint32(
3✔
4559
                        ourPolicy.FeeProportionalMillionths,
3✔
4560
                )
3✔
4561

4562
        case storedFwdingPolicy != nil:
45✔
4563
                chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
45✔
4564
                chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
45✔
4565

4566
        default:
×
4567
                log.Infof("No channel forwarding policy specified for channel "+
×
4568
                        "announcement of ChannelID(%v). "+
×
4569
                        "Assuming default fee parameters.", chanID)
×
4570
                chanUpdateAnn.BaseFee = uint32(
×
4571
                        f.cfg.DefaultRoutingPolicy.BaseFee,
×
4572
                )
×
4573
                chanUpdateAnn.FeeRate = uint32(
×
4574
                        f.cfg.DefaultRoutingPolicy.FeeRate,
×
4575
                )
×
4576
        }
4577

4578
        // With the channel update announcement constructed, we'll generate a
4579
        // signature that signs a double-sha digest of the announcement.
4580
        // This'll serve to authenticate this announcement and any other future
4581
        // updates we may send.
4582
        chanUpdateMsg, err := chanUpdateAnn.DataToSign()
45✔
4583
        if err != nil {
45✔
4584
                return nil, err
×
4585
        }
×
4586
        sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
45✔
4587
        if err != nil {
45✔
4588
                return nil, fmt.Errorf("unable to generate channel "+
×
4589
                        "update announcement signature: %w", err)
×
4590
        }
×
4591
        chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
45✔
4592
        if err != nil {
45✔
4593
                return nil, fmt.Errorf("unable to generate channel "+
×
4594
                        "update announcement signature: %w", err)
×
4595
        }
×
4596

4597
        // The channel existence proofs itself is currently announced in
4598
        // distinct message. In order to properly authenticate this message, we
4599
        // need two signatures: one under the identity public key used which
4600
        // signs the message itself and another signature of the identity
4601
        // public key under the funding key itself.
4602
        //
4603
        // TODO(roasbeef): use SignAnnouncement here instead?
4604
        chanAnnMsg, err := chanAnn.DataToSign()
45✔
4605
        if err != nil {
45✔
4606
                return nil, err
×
4607
        }
×
4608
        nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
45✔
4609
        if err != nil {
45✔
4610
                return nil, fmt.Errorf("unable to generate node "+
×
4611
                        "signature for channel announcement: %w", err)
×
4612
        }
×
4613
        bitcoinSig, err := f.cfg.SignMessage(
45✔
4614
                localFundingKey.KeyLocator, chanAnnMsg, true,
45✔
4615
        )
45✔
4616
        if err != nil {
45✔
4617
                return nil, fmt.Errorf("unable to generate bitcoin "+
×
4618
                        "signature for node public key: %w", err)
×
4619
        }
×
4620

4621
        // Finally, we'll generate the announcement proof which we'll use to
4622
        // provide the other side with the necessary signatures required to
4623
        // allow them to reconstruct the full channel announcement.
4624
        proof := &lnwire.AnnounceSignatures1{
45✔
4625
                ChannelID:      chanID,
45✔
4626
                ShortChannelID: shortChanID,
45✔
4627
        }
45✔
4628
        proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
45✔
4629
        if err != nil {
45✔
4630
                return nil, err
×
4631
        }
×
4632
        proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
45✔
4633
        if err != nil {
45✔
4634
                return nil, err
×
4635
        }
×
4636

4637
        return &chanAnnouncement{
45✔
4638
                chanAnn:       chanAnn,
45✔
4639
                chanUpdateAnn: chanUpdateAnn,
45✔
4640
                chanProof:     proof,
45✔
4641
        }, nil
45✔
4642
}
4643

4644
// announceChannel announces a newly created channel to the rest of the network
4645
// by crafting the two authenticated announcements required for the peers on
4646
// the network to recognize the legitimacy of the channel. The crafted
4647
// announcements are then sent to the channel router to handle broadcasting to
4648
// the network during its next trickle.
4649
// This method is synchronous and will return when all the network requests
4650
// finish, either successfully or with an error.
4651
func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
4652
        localFundingKey *keychain.KeyDescriptor,
4653
        remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
4654
        chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
19✔
4655

19✔
4656
        // First, we'll create the batch of announcements to be sent upon
19✔
4657
        // initial channel creation. This includes the channel announcement
19✔
4658
        // itself, the channel update announcement, and our half of the channel
19✔
4659
        // proof needed to fully authenticate the channel.
19✔
4660
        //
19✔
4661
        // We can pass in zeroes for the min and max htlc policy, because we
19✔
4662
        // only use the channel announcement message from the returned struct.
19✔
4663
        ann, err := f.newChanAnnouncement(
19✔
4664
                localIDKey, remoteIDKey, localFundingKey, remoteFundingKey,
19✔
4665
                shortChanID, chanID, 0, 0, nil, chanType,
19✔
4666
        )
19✔
4667
        if err != nil {
19✔
4668
                log.Errorf("can't generate channel announcement: %v", err)
×
4669
                return err
×
4670
        }
×
4671

4672
        // We only send the channel proof announcement and the node announcement
4673
        // because addToGraph previously sent the ChannelAnnouncement and
4674
        // the ChannelUpdate announcement messages. The channel proof and node
4675
        // announcements are broadcast to the greater network.
4676
        errChan := f.cfg.SendAnnouncement(ann.chanProof)
19✔
4677
        select {
19✔
4678
        case err := <-errChan:
19✔
4679
                if err != nil {
22✔
4680
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4681
                                graph.ErrIgnored) {
3✔
4682

×
4683
                                log.Debugf("Graph rejected "+
×
4684
                                        "AnnounceSignatures: %v", err)
×
4685
                        } else {
3✔
4686
                                log.Errorf("Unable to send channel "+
3✔
4687
                                        "proof: %v", err)
3✔
4688
                                return err
3✔
4689
                        }
3✔
4690
                }
4691

4692
        case <-f.quit:
×
4693
                return ErrFundingManagerShuttingDown
×
4694
        }
4695

4696
        // Now that the channel is announced to the network, we will also
4697
        // obtain and send a node announcement. This is done since a node
4698
        // announcement is only accepted after a channel is known for that
4699
        // particular node, and this might be our first channel.
4700
        nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
19✔
4701
        if err != nil {
19✔
4702
                log.Errorf("can't generate node announcement: %v", err)
×
4703
                return err
×
4704
        }
×
4705

4706
        errChan = f.cfg.SendAnnouncement(&nodeAnn)
19✔
4707
        select {
19✔
4708
        case err := <-errChan:
19✔
4709
                if err != nil {
22✔
4710
                        if graph.IsError(err, graph.ErrOutdated,
3✔
4711
                                graph.ErrIgnored) {
6✔
4712

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

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

4726
        return nil
19✔
4727
}
4728

4729
// InitFundingWorkflow sends a message to the funding manager instructing it
4730
// to initiate a single funder workflow with the source peer.
4731
func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
60✔
4732
        f.fundingRequests <- msg
60✔
4733
}
60✔
4734

4735
// getUpfrontShutdownScript takes a user provided script and a getScript
4736
// function which can be used to generate an upfront shutdown script. If our
4737
// peer does not support the feature, this function will error if a non-zero
4738
// script was provided by the user, and return an empty script otherwise. If
4739
// our peer does support the feature, we will return the user provided script
4740
// if non-zero, or a freshly generated script if our node is configured to set
4741
// upfront shutdown scripts automatically.
4742
func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
4743
        script lnwire.DeliveryAddress,
4744
        getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
4745
        error) {
113✔
4746

113✔
4747
        // Check whether the remote peer supports upfront shutdown scripts.
113✔
4748
        remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
113✔
4749
                lnwire.UpfrontShutdownScriptOptional,
113✔
4750
        )
113✔
4751

113✔
4752
        // If the peer does not support upfront shutdown scripts, and one has been
113✔
4753
        // provided, return an error because the feature is not supported.
113✔
4754
        if !remoteUpfrontShutdown && len(script) != 0 {
114✔
4755
                return nil, errUpfrontShutdownScriptNotSupported
1✔
4756
        }
1✔
4757

4758
        // If the peer does not support upfront shutdown, return an empty address.
4759
        if !remoteUpfrontShutdown {
217✔
4760
                return nil, nil
105✔
4761
        }
105✔
4762

4763
        // If the user has provided an script and the peer supports the feature,
4764
        // return it. Note that user set scripts override the enable upfront
4765
        // shutdown flag.
4766
        if len(script) > 0 {
12✔
4767
                return script, nil
5✔
4768
        }
5✔
4769

4770
        // If we do not have setting of upfront shutdown script enabled, return
4771
        // an empty script.
4772
        if !enableUpfrontShutdown {
9✔
4773
                return nil, nil
4✔
4774
        }
4✔
4775

4776
        // We can safely send a taproot address iff, both sides have negotiated
4777
        // the shutdown-any-segwit feature.
4778
        taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
1✔
4779
                peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
1✔
4780

1✔
4781
        return getScript(taprootOK)
1✔
4782
}
4783

4784
// handleInitFundingMsg creates a channel reservation within the daemon's
4785
// wallet, then sends a funding request to the remote peer kicking off the
4786
// funding workflow.
4787
func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
60✔
4788
        var (
60✔
4789
                peerKey        = msg.Peer.IdentityKey()
60✔
4790
                localAmt       = msg.LocalFundingAmt
60✔
4791
                baseFee        = msg.BaseFee
60✔
4792
                feeRate        = msg.FeeRate
60✔
4793
                minHtlcIn      = msg.MinHtlcIn
60✔
4794
                remoteCsvDelay = msg.RemoteCsvDelay
60✔
4795
                maxValue       = msg.MaxValueInFlight
60✔
4796
                maxHtlcs       = msg.MaxHtlcs
60✔
4797
                maxCSV         = msg.MaxLocalCsv
60✔
4798
                chanReserve    = msg.RemoteChanReserve
60✔
4799
                outpoints      = msg.Outpoints
60✔
4800
        )
60✔
4801

60✔
4802
        // If no maximum CSV delay was set for this channel, we use our default
60✔
4803
        // value.
60✔
4804
        if maxCSV == 0 {
120✔
4805
                maxCSV = f.cfg.MaxLocalCSVDelay
60✔
4806
        }
60✔
4807

4808
        log.Infof("Initiating fundingRequest(local_amt=%v "+
60✔
4809
                "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
60✔
4810
                "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
60✔
4811
                msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
60✔
4812

60✔
4813
        // We set the channel flags to indicate whether we want this channel to
60✔
4814
        // be announced to the network.
60✔
4815
        var channelFlags lnwire.FundingFlag
60✔
4816
        if !msg.Private {
115✔
4817
                // This channel will be announced.
55✔
4818
                channelFlags = lnwire.FFAnnounceChannel
55✔
4819
        }
55✔
4820

4821
        // If the caller specified their own channel ID, then we'll use that.
4822
        // Otherwise we'll generate a fresh one as normal.  This will be used
4823
        // to track this reservation throughout its lifetime.
4824
        var chanID PendingChanID
60✔
4825
        if msg.PendingChanID == zeroID {
120✔
4826
                chanID = f.nextPendingChanID()
60✔
4827
        } else {
63✔
4828
                // If the user specified their own pending channel ID, then
3✔
4829
                // we'll ensure it doesn't collide with any existing pending
3✔
4830
                // channel ID.
3✔
4831
                chanID = msg.PendingChanID
3✔
4832
                if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
3✔
4833
                        msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
×
4834
                                "already present", chanID[:])
×
4835
                        return
×
4836
                }
×
4837
        }
4838

4839
        // Check whether the peer supports upfront shutdown, and get an address
4840
        // which should be used (either a user specified address or a new
4841
        // address from the wallet if our node is configured to set shutdown
4842
        // address by default).
4843
        shutdown, err := getUpfrontShutdownScript(
60✔
4844
                f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
60✔
4845
                f.selectShutdownScript,
60✔
4846
        )
60✔
4847
        if err != nil {
60✔
4848
                msg.Err <- err
×
4849
                return
×
4850
        }
×
4851

4852
        // Initialize a funding reservation with the local wallet. If the
4853
        // wallet doesn't have enough funds to commit to this channel, then the
4854
        // request will fail, and be aborted.
4855
        //
4856
        // Before we init the channel, we'll also check to see what commitment
4857
        // format we can use with this peer. This is dependent on *both* us and
4858
        // the remote peer are signaling the proper feature bit.
4859
        chanType, commitType, err := negotiateCommitmentType(
60✔
4860
                msg.ChannelType, msg.Peer.LocalFeatures(),
60✔
4861
                msg.Peer.RemoteFeatures(),
60✔
4862
        )
60✔
4863
        if err != nil {
63✔
4864
                log.Errorf("channel type negotiation failed: %v", err)
3✔
4865
                msg.Err <- err
3✔
4866
                return
3✔
4867
        }
3✔
4868

4869
        var (
60✔
4870
                zeroConf bool
60✔
4871
                scid     bool
60✔
4872
        )
60✔
4873

60✔
4874
        if chanType != nil {
67✔
4875
                // Check if the returned chanType includes either the zero-conf
7✔
4876
                // or scid-alias bits.
7✔
4877
                featureVec := lnwire.RawFeatureVector(*chanType)
7✔
4878
                zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
7✔
4879
                scid = featureVec.IsSet(lnwire.ScidAliasRequired)
7✔
4880

7✔
4881
                // The option-scid-alias channel type for a public channel is
7✔
4882
                // disallowed.
7✔
4883
                if scid && !msg.Private {
7✔
4884
                        err = fmt.Errorf("option-scid-alias chantype for " +
×
4885
                                "public channel")
×
4886
                        log.Error(err)
×
4887
                        msg.Err <- err
×
4888

×
4889
                        return
×
4890
                }
×
4891
        }
4892

4893
        // First, we'll query the fee estimator for a fee that should get the
4894
        // commitment transaction confirmed by the next few blocks (conf target
4895
        // of 3). We target the near blocks here to ensure that we'll be able
4896
        // to execute a timely unilateral channel closure if needed.
4897
        commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
60✔
4898
        if err != nil {
60✔
4899
                msg.Err <- err
×
4900
                return
×
4901
        }
×
4902

4903
        // For anchor channels cap the initial commit fee rate at our defined
4904
        // maximum.
4905
        if commitType.HasAnchors() &&
60✔
4906
                commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
67✔
4907

7✔
4908
                commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
7✔
4909
        }
7✔
4910

4911
        var scidFeatureVal bool
60✔
4912
        if hasFeatures(
60✔
4913
                msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
60✔
4914
                lnwire.ScidAliasOptional,
60✔
4915
        ) {
66✔
4916

6✔
4917
                scidFeatureVal = true
6✔
4918
        }
6✔
4919

4920
        // At this point, if we have an AuxFundingController active, we'll check
4921
        // to see if we have a special tapscript root to use in our MuSig2
4922
        // funding output.
4923
        tapscriptRoot, err := fn.MapOptionZ(
60✔
4924
                f.cfg.AuxFundingController,
60✔
4925
                func(c AuxFundingController) AuxTapscriptResult {
60✔
4926
                        return c.DeriveTapscriptRoot(chanID)
×
4927
                },
×
4928
        ).Unpack()
4929
        if err != nil {
60✔
4930
                err = fmt.Errorf("error deriving tapscript root: %w", err)
×
4931
                log.Error(err)
×
4932
                msg.Err <- err
×
4933

×
4934
                return
×
4935
        }
×
4936

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

4967
                        // Query the sweeper storage to make sure we don't use
4968
                        // an unconfirmed utxo still in use by the sweeper
4969
                        // subsystem.
4970
                        return !f.cfg.IsSweeperOutpoint(u.OutPoint)
61✔
4971
                },
4972
                ZeroConf:         zeroConf,
4973
                OptionScidAlias:  scid,
4974
                ScidAliasFeature: scidFeatureVal,
4975
                Memo:             msg.Memo,
4976
                TapscriptRoot:    tapscriptRoot,
4977
        }
4978

4979
        reservation, err := f.cfg.Wallet.InitChannelReservation(req)
60✔
4980
        if err != nil {
63✔
4981
                msg.Err <- err
3✔
4982
                return
3✔
4983
        }
3✔
4984

4985
        if zeroConf {
65✔
4986
                // Store the alias for zero-conf channels in the underlying
5✔
4987
                // partial channel state.
5✔
4988
                aliasScid, err := f.cfg.AliasManager.RequestAlias()
5✔
4989
                if err != nil {
5✔
4990
                        msg.Err <- err
×
4991
                        return
×
4992
                }
×
4993

4994
                reservation.AddAlias(aliasScid)
5✔
4995
        }
4996

4997
        // Set our upfront shutdown address in the existing reservation.
4998
        reservation.SetOurUpfrontShutdown(shutdown)
60✔
4999

60✔
5000
        // Now that we have successfully reserved funds for this channel in the
60✔
5001
        // wallet, we can fetch the final channel capacity. This is done at
60✔
5002
        // this point since the final capacity might change in case of
60✔
5003
        // SubtractFees=true.
60✔
5004
        capacity := reservation.Capacity()
60✔
5005

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

60✔
5009
        // If the remote CSV delay was not set in the open channel request,
60✔
5010
        // we'll use the RequiredRemoteDelay closure to compute the delay we
60✔
5011
        // require given the total amount of funds within the channel.
60✔
5012
        if remoteCsvDelay == 0 {
119✔
5013
                remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
59✔
5014
        }
59✔
5015

5016
        // If no minimum HTLC value was specified, use the default one.
5017
        if minHtlcIn == 0 {
119✔
5018
                minHtlcIn = f.cfg.DefaultMinHtlcIn
59✔
5019
        }
59✔
5020

5021
        // If no max value was specified, use the default one.
5022
        if maxValue == 0 {
119✔
5023
                maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
59✔
5024
        }
59✔
5025

5026
        if maxHtlcs == 0 {
120✔
5027
                maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
60✔
5028
        }
60✔
5029

5030
        // Once the reservation has been created, and indexed, queue a funding
5031
        // request to the remote peer, kicking off the funding workflow.
5032
        ourContribution := reservation.OurContribution()
60✔
5033

60✔
5034
        // Prepare the optional channel fee values from the initFundingMsg. If
60✔
5035
        // useBaseFee or useFeeRate are false the client did not provide fee
60✔
5036
        // values hence we assume default fee settings from the config.
60✔
5037
        forwardingPolicy := f.defaultForwardingPolicy(
60✔
5038
                ourContribution.ChannelStateBounds,
60✔
5039
        )
60✔
5040
        if baseFee != nil {
64✔
5041
                forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
4✔
5042
        }
4✔
5043

5044
        if feeRate != nil {
64✔
5045
                forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
4✔
5046
        }
4✔
5047

5048
        // Fetch our dust limit which is part of the default channel
5049
        // constraints, and log it.
5050
        ourDustLimit := ourContribution.DustLimit
60✔
5051

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

60✔
5054
        // If the channel reserve is not specified, then we calculate an
60✔
5055
        // appropriate amount here.
60✔
5056
        if chanReserve == 0 {
116✔
5057
                chanReserve = f.cfg.RequiredRemoteChanReserve(
56✔
5058
                        capacity, ourDustLimit,
56✔
5059
                )
56✔
5060
        }
56✔
5061

5062
        // If a pending channel map for this peer isn't already created, then
5063
        // we create one, ultimately allowing us to track this pending
5064
        // reservation within the target peer.
5065
        peerIDKey := newSerializedKey(peerKey)
60✔
5066
        f.resMtx.Lock()
60✔
5067
        if _, ok := f.activeReservations[peerIDKey]; !ok {
113✔
5068
                f.activeReservations[peerIDKey] = make(pendingChannels)
53✔
5069
        }
53✔
5070

5071
        resCtx := &reservationWithCtx{
60✔
5072
                chanAmt:           capacity,
60✔
5073
                forwardingPolicy:  *forwardingPolicy,
60✔
5074
                remoteCsvDelay:    remoteCsvDelay,
60✔
5075
                remoteMinHtlc:     minHtlcIn,
60✔
5076
                remoteMaxValue:    maxValue,
60✔
5077
                remoteMaxHtlcs:    maxHtlcs,
60✔
5078
                remoteChanReserve: chanReserve,
60✔
5079
                maxLocalCsv:       maxCSV,
60✔
5080
                channelType:       chanType,
60✔
5081
                reservation:       reservation,
60✔
5082
                peer:              msg.Peer,
60✔
5083
                updates:           msg.Updates,
60✔
5084
                err:               msg.Err,
60✔
5085
        }
60✔
5086
        f.activeReservations[peerIDKey][chanID] = resCtx
60✔
5087
        f.resMtx.Unlock()
60✔
5088

60✔
5089
        // Update the timestamp once the InitFundingMsg has been handled.
60✔
5090
        defer resCtx.updateTimestamp()
60✔
5091

60✔
5092
        // Check the sanity of the selected channel constraints.
60✔
5093
        bounds := &channeldb.ChannelStateBounds{
60✔
5094
                ChanReserve:      chanReserve,
60✔
5095
                MaxPendingAmount: maxValue,
60✔
5096
                MinHTLC:          minHtlcIn,
60✔
5097
                MaxAcceptedHtlcs: maxHtlcs,
60✔
5098
        }
60✔
5099
        commitParams := &channeldb.CommitmentParams{
60✔
5100
                DustLimit: ourDustLimit,
60✔
5101
                CsvDelay:  remoteCsvDelay,
60✔
5102
        }
60✔
5103
        err = lnwallet.VerifyConstraints(
60✔
5104
                bounds, commitParams, resCtx.maxLocalCsv, capacity,
60✔
5105
        )
60✔
5106
        if err != nil {
62✔
5107
                _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
2✔
5108
                if reserveErr != nil {
2✔
5109
                        log.Errorf("unable to cancel reservation: %v",
×
5110
                                reserveErr)
×
5111
                }
×
5112

5113
                msg.Err <- err
2✔
5114
                return
2✔
5115
        }
5116

5117
        // When opening a script enforced channel lease, include the required
5118
        // expiry TLV record in our proposal.
5119
        var leaseExpiry *lnwire.LeaseExpiry
58✔
5120
        if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
61✔
5121
                leaseExpiry = new(lnwire.LeaseExpiry)
3✔
5122
                *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
3✔
5123
        }
3✔
5124

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

58✔
5128
        reservation.SetState(lnwallet.SentOpenChannel)
58✔
5129

58✔
5130
        fundingOpen := lnwire.OpenChannel{
58✔
5131
                ChainHash:             *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
58✔
5132
                PendingChannelID:      chanID,
58✔
5133
                FundingAmount:         capacity,
58✔
5134
                PushAmount:            msg.PushAmt,
58✔
5135
                DustLimit:             ourDustLimit,
58✔
5136
                MaxValueInFlight:      maxValue,
58✔
5137
                ChannelReserve:        chanReserve,
58✔
5138
                HtlcMinimum:           minHtlcIn,
58✔
5139
                FeePerKiloWeight:      uint32(commitFeePerKw),
58✔
5140
                CsvDelay:              remoteCsvDelay,
58✔
5141
                MaxAcceptedHTLCs:      maxHtlcs,
58✔
5142
                FundingKey:            ourContribution.MultiSigKey.PubKey,
58✔
5143
                RevocationPoint:       ourContribution.RevocationBasePoint.PubKey,
58✔
5144
                PaymentPoint:          ourContribution.PaymentBasePoint.PubKey,
58✔
5145
                HtlcPoint:             ourContribution.HtlcBasePoint.PubKey,
58✔
5146
                DelayedPaymentPoint:   ourContribution.DelayBasePoint.PubKey,
58✔
5147
                FirstCommitmentPoint:  ourContribution.FirstCommitmentPoint,
58✔
5148
                ChannelFlags:          channelFlags,
58✔
5149
                UpfrontShutdownScript: shutdown,
58✔
5150
                ChannelType:           chanType,
58✔
5151
                LeaseExpiry:           leaseExpiry,
58✔
5152
        }
58✔
5153

58✔
5154
        if commitType.IsTaproot() {
63✔
5155
                fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
5✔
5156
                        ourContribution.LocalNonce.PubNonce,
5✔
5157
                )
5✔
5158
        }
5✔
5159

5160
        if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
58✔
5161
                e := fmt.Errorf("unable to send funding request message: %w",
×
5162
                        err)
×
5163
                log.Errorf(e.Error())
×
5164

×
5165
                // Since we were unable to send the initial message to the peer
×
5166
                // and start the funding flow, we'll cancel this reservation.
×
5167
                _, err := f.cancelReservationCtx(peerKey, chanID, false)
×
5168
                if err != nil {
×
5169
                        log.Errorf("unable to cancel reservation: %v", err)
×
5170
                }
×
5171

5172
                msg.Err <- e
×
5173
                return
×
5174
        }
5175
}
5176

5177
// handleWarningMsg processes the warning which was received from remote peer.
5178
func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
44✔
5179
        log.Warnf("received warning message from peer %x: %v",
44✔
5180
                peer.IdentityKey().SerializeCompressed(), msg.Warning())
44✔
5181
}
44✔
5182

5183
// handleErrorMsg processes the error which was received from remote peer,
5184
// depending on the type of error we should do different clean up steps and
5185
// inform the user about it.
5186
func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
3✔
5187
        chanID := msg.ChanID
3✔
5188
        peerKey := peer.IdentityKey()
3✔
5189

3✔
5190
        // First, we'll attempt to retrieve and cancel the funding workflow
3✔
5191
        // that this error was tied to. If we're unable to do so, then we'll
3✔
5192
        // exit early as this was an unwarranted error.
3✔
5193
        resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
3✔
5194
        if err != nil {
3✔
5195
                log.Warnf("Received error for non-existent funding "+
×
5196
                        "flow: %v (%v)", err, msg.Error())
×
5197
                return
×
5198
        }
×
5199

5200
        // If we did indeed find the funding workflow, then we'll return the
5201
        // error back to the caller (if any), and cancel the workflow itself.
5202
        fundingErr := fmt.Errorf("received funding error from %x: %v",
3✔
5203
                peerKey.SerializeCompressed(), msg.Error(),
3✔
5204
        )
3✔
5205
        log.Errorf(fundingErr.Error())
3✔
5206

3✔
5207
        // If this was a PSBT funding flow, the remote likely timed out because
3✔
5208
        // we waited too long. Return a nice error message to the user in that
3✔
5209
        // case so the user knows what's the problem.
3✔
5210
        if resCtx.reservation.IsPsbt() {
6✔
5211
                fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
3✔
5212
                        fundingErr)
3✔
5213
        }
3✔
5214

5215
        resCtx.err <- fundingErr
3✔
5216
}
5217

5218
// pruneZombieReservations loops through all pending reservations and fails the
5219
// funding flow for any reservations that have not been updated since the
5220
// ReservationTimeout and are not locked waiting for the funding transaction.
5221
func (f *Manager) pruneZombieReservations() {
6✔
5222
        zombieReservations := make(pendingChannels)
6✔
5223

6✔
5224
        f.resMtx.RLock()
6✔
5225
        for _, pendingReservations := range f.activeReservations {
12✔
5226
                for pendingChanID, resCtx := range pendingReservations {
12✔
5227
                        if resCtx.isLocked() {
6✔
5228
                                continue
×
5229
                        }
5230

5231
                        // We don't want to expire PSBT funding reservations.
5232
                        // These reservations are always initiated by us and the
5233
                        // remote peer is likely going to cancel them after some
5234
                        // idle time anyway. So no need for us to also prune
5235
                        // them.
5236
                        sinceLastUpdate := time.Since(resCtx.lastUpdated)
6✔
5237
                        isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
6✔
5238
                        if !resCtx.reservation.IsPsbt() && isExpired {
12✔
5239
                                zombieReservations[pendingChanID] = resCtx
6✔
5240
                        }
6✔
5241
                }
5242
        }
5243
        f.resMtx.RUnlock()
6✔
5244

6✔
5245
        for pendingChanID, resCtx := range zombieReservations {
12✔
5246
                err := fmt.Errorf("reservation timed out waiting for peer "+
6✔
5247
                        "(peer_id:%x, chan_id:%x)",
6✔
5248
                        resCtx.peer.IdentityKey().SerializeCompressed(),
6✔
5249
                        pendingChanID[:])
6✔
5250
                log.Warnf(err.Error())
6✔
5251

6✔
5252
                chanID := lnwire.NewChanIDFromOutPoint(
6✔
5253
                        *resCtx.reservation.FundingOutpoint(),
6✔
5254
                )
6✔
5255

6✔
5256
                // Create channel identifier and set the channel ID.
6✔
5257
                cid := newChanIdentifier(pendingChanID)
6✔
5258
                cid.setChanID(chanID)
6✔
5259

6✔
5260
                f.failFundingFlow(resCtx.peer, cid, err)
6✔
5261
        }
6✔
5262
}
5263

5264
// cancelReservationCtx does all needed work in order to securely cancel the
5265
// reservation.
5266
func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
5267
        pendingChanID PendingChanID,
5268
        byRemote bool) (*reservationWithCtx, error) {
26✔
5269

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

26✔
5273
        peerIDKey := newSerializedKey(peerKey)
26✔
5274
        f.resMtx.Lock()
26✔
5275
        defer f.resMtx.Unlock()
26✔
5276

26✔
5277
        nodeReservations, ok := f.activeReservations[peerIDKey]
26✔
5278
        if !ok {
36✔
5279
                // No reservations for this node.
10✔
5280
                return nil, fmt.Errorf("no active reservations for peer(%x)",
10✔
5281
                        peerIDKey[:])
10✔
5282
        }
10✔
5283

5284
        ctx, ok := nodeReservations[pendingChanID]
19✔
5285
        if !ok {
21✔
5286
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
2✔
5287
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
2✔
5288
        }
2✔
5289

5290
        // If the reservation was a PSBT funding flow and it was canceled by the
5291
        // remote peer, then we need to thread through a different error message
5292
        // to the subroutine that's waiting for the user input so it can return
5293
        // a nice error message to the user.
5294
        if ctx.reservation.IsPsbt() && byRemote {
20✔
5295
                ctx.reservation.RemoteCanceled()
3✔
5296
        }
3✔
5297

5298
        if err := ctx.reservation.Cancel(); err != nil {
17✔
5299
                return nil, fmt.Errorf("unable to cancel reservation: %w", err)
×
5300
        }
×
5301

5302
        delete(nodeReservations, pendingChanID)
17✔
5303

17✔
5304
        // If this was the last active reservation for this peer, delete the
17✔
5305
        // peer's entry altogether.
17✔
5306
        if len(nodeReservations) == 0 {
34✔
5307
                delete(f.activeReservations, peerIDKey)
17✔
5308
        }
17✔
5309
        return ctx, nil
17✔
5310
}
5311

5312
// deleteReservationCtx deletes the reservation uniquely identified by the
5313
// target public key of the peer, and the specified pending channel ID.
5314
func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
5315
        pendingChanID PendingChanID) {
59✔
5316

59✔
5317
        peerIDKey := newSerializedKey(peerKey)
59✔
5318
        f.resMtx.Lock()
59✔
5319
        defer f.resMtx.Unlock()
59✔
5320

59✔
5321
        nodeReservations, ok := f.activeReservations[peerIDKey]
59✔
5322
        if !ok {
59✔
5323
                // No reservations for this node.
×
5324
                return
×
5325
        }
×
5326
        delete(nodeReservations, pendingChanID)
59✔
5327

59✔
5328
        // If this was the last active reservation for this peer, delete the
59✔
5329
        // peer's entry altogether.
59✔
5330
        if len(nodeReservations) == 0 {
111✔
5331
                delete(f.activeReservations, peerIDKey)
52✔
5332
        }
52✔
5333
}
5334

5335
// getReservationCtx returns the reservation context for a particular pending
5336
// channel ID for a target peer.
5337
func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
5338
        pendingChanID PendingChanID) (*reservationWithCtx, error) {
94✔
5339

94✔
5340
        peerIDKey := newSerializedKey(peerKey)
94✔
5341
        f.resMtx.RLock()
94✔
5342
        resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
94✔
5343
        f.resMtx.RUnlock()
94✔
5344

94✔
5345
        if !ok {
97✔
5346
                return nil, fmt.Errorf("unknown channel (id: %x) for "+
3✔
5347
                        "peer(%x)", pendingChanID[:], peerIDKey[:])
3✔
5348
        }
3✔
5349

5350
        return resCtx, nil
94✔
5351
}
5352

5353
// IsPendingChannel returns a boolean indicating whether the channel identified
5354
// by the pendingChanID and given peer is pending, meaning it is in the process
5355
// of being funded. After the funding transaction has been confirmed, the
5356
// channel will receive a new, permanent channel ID, and will no longer be
5357
// considered pending.
5358
func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
5359
        peer lnpeer.Peer) bool {
3✔
5360

3✔
5361
        peerIDKey := newSerializedKey(peer.IdentityKey())
3✔
5362
        f.resMtx.RLock()
3✔
5363
        _, ok := f.activeReservations[peerIDKey][pendingChanID]
3✔
5364
        f.resMtx.RUnlock()
3✔
5365

3✔
5366
        return ok
3✔
5367
}
3✔
5368

5369
func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
388✔
5370
        var tmp btcec.JacobianPoint
388✔
5371
        pub.AsJacobian(&tmp)
388✔
5372
        tmp.ToAffine()
388✔
5373
        return btcec.NewPublicKey(&tmp.X, &tmp.Y)
388✔
5374
}
388✔
5375

5376
// defaultForwardingPolicy returns the default forwarding policy based on the
5377
// default routing policy and our local channel constraints.
5378
func (f *Manager) defaultForwardingPolicy(
5379
        bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
107✔
5380

107✔
5381
        return &models.ForwardingPolicy{
107✔
5382
                MinHTLCOut:    bounds.MinHTLC,
107✔
5383
                MaxHTLC:       bounds.MaxPendingAmount,
107✔
5384
                BaseFee:       f.cfg.DefaultRoutingPolicy.BaseFee,
107✔
5385
                FeeRate:       f.cfg.DefaultRoutingPolicy.FeeRate,
107✔
5386
                TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
107✔
5387
        }
107✔
5388
}
107✔
5389

5390
// saveInitialForwardingPolicy saves the forwarding policy for the provided
5391
// chanPoint in the channelOpeningStateBucket.
5392
func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
5393
        forwardingPolicy *models.ForwardingPolicy) error {
72✔
5394

72✔
5395
        return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
72✔
5396
                chanID, forwardingPolicy,
72✔
5397
        )
72✔
5398
}
72✔
5399

5400
// getInitialForwardingPolicy fetches the initial forwarding policy for a given
5401
// channel id from the database which will be applied during the channel
5402
// announcement phase.
5403
func (f *Manager) getInitialForwardingPolicy(
5404
        chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
97✔
5405

97✔
5406
        return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
97✔
5407
}
97✔
5408

5409
// deleteInitialForwardingPolicy removes channel fees for this chanID from
5410
// the database.
5411
func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
27✔
5412
        return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
27✔
5413
}
27✔
5414

5415
// saveChannelOpeningState saves the channelOpeningState for the provided
5416
// chanPoint to the channelOpeningStateBucket.
5417
func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
5418
        state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
95✔
5419

95✔
5420
        var outpointBytes bytes.Buffer
95✔
5421
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
95✔
5422
                return err
×
5423
        }
×
5424

5425
        // Save state and the uint64 representation of the shortChanID
5426
        // for later use.
5427
        scratch := make([]byte, 10)
95✔
5428
        byteOrder.PutUint16(scratch[:2], uint16(state))
95✔
5429
        byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
95✔
5430

95✔
5431
        return f.cfg.ChannelDB.SaveChannelOpeningState(
95✔
5432
                outpointBytes.Bytes(), scratch,
95✔
5433
        )
95✔
5434
}
5435

5436
// getChannelOpeningState fetches the channelOpeningState for the provided
5437
// chanPoint from the database, or returns ErrChannelNotFound if the channel
5438
// is not found.
5439
func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
5440
        channelOpeningState, *lnwire.ShortChannelID, error) {
256✔
5441

256✔
5442
        var outpointBytes bytes.Buffer
256✔
5443
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
256✔
5444
                return 0, nil, err
×
5445
        }
×
5446

5447
        value, err := f.cfg.ChannelDB.GetChannelOpeningState(
256✔
5448
                outpointBytes.Bytes(),
256✔
5449
        )
256✔
5450
        if err != nil {
308✔
5451
                return 0, nil, err
52✔
5452
        }
52✔
5453

5454
        state := channelOpeningState(byteOrder.Uint16(value[:2]))
207✔
5455
        shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
207✔
5456
        return state, &shortChanID, nil
207✔
5457
}
5458

5459
// deleteChannelOpeningState removes any state for chanPoint from the database.
5460
func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
27✔
5461
        var outpointBytes bytes.Buffer
27✔
5462
        if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
27✔
5463
                return err
×
5464
        }
×
5465

5466
        return f.cfg.ChannelDB.DeleteChannelOpeningState(
27✔
5467
                outpointBytes.Bytes(),
27✔
5468
        )
27✔
5469
}
5470

5471
// selectShutdownScript selects the shutdown script we should send to the peer.
5472
// If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
5473
// script.
5474
func (f *Manager) selectShutdownScript(taprootOK bool,
5475
) (lnwire.DeliveryAddress, error) {
×
5476

×
5477
        addrType := lnwallet.WitnessPubKey
×
5478
        if taprootOK {
×
5479
                addrType = lnwallet.TaprootPubkey
×
5480
        }
×
5481

5482
        addr, err := f.cfg.Wallet.NewAddress(
×
5483
                addrType, false, lnwallet.DefaultAccountName,
×
5484
        )
×
5485
        if err != nil {
×
5486
                return nil, err
×
5487
        }
×
5488

5489
        return txscript.PayToAddrScript(addr)
×
5490
}
5491

5492
// waitForPeerOnline blocks until the peer specified by peerPubkey comes online
5493
// and then returns the online peer.
5494
func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
5495
        error) {
107✔
5496

107✔
5497
        peerChan := make(chan lnpeer.Peer, 1)
107✔
5498

107✔
5499
        var peerKey [33]byte
107✔
5500
        copy(peerKey[:], peerPubkey.SerializeCompressed())
107✔
5501

107✔
5502
        f.cfg.NotifyWhenOnline(peerKey, peerChan)
107✔
5503

107✔
5504
        var peer lnpeer.Peer
107✔
5505
        select {
107✔
5506
        case peer = <-peerChan:
106✔
5507
        case <-f.quit:
1✔
5508
                return peer, ErrFundingManagerShuttingDown
1✔
5509
        }
5510
        return peer, nil
106✔
5511
}
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