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

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

38420.67 hits per line

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

82.63
/lnwallet/commitment.go
1
package lnwallet
2

3
import (
4
        "bytes"
5
        "fmt"
6

7
        "github.com/btcsuite/btcd/blockchain"
8
        "github.com/btcsuite/btcd/btcec/v2"
9
        "github.com/btcsuite/btcd/btcutil"
10
        "github.com/btcsuite/btcd/chaincfg/chainhash"
11
        "github.com/btcsuite/btcd/txscript"
12
        "github.com/btcsuite/btcd/wire"
13
        "github.com/lightningnetwork/lnd/channeldb"
14
        "github.com/lightningnetwork/lnd/fn"
15
        "github.com/lightningnetwork/lnd/input"
16
        "github.com/lightningnetwork/lnd/lntypes"
17
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
18
        "github.com/lightningnetwork/lnd/lnwire"
19
)
20

21
// AnchorSize is the constant anchor output size.
22
const AnchorSize = btcutil.Amount(330)
23

24
// DefaultAnchorsCommitMaxFeeRateSatPerVByte is the default max fee rate in
25
// sat/vbyte the initiator will use for anchor channels. This should be enough
26
// to ensure propagation before anchoring down the commitment transaction.
27
const DefaultAnchorsCommitMaxFeeRateSatPerVByte = 10
28

29
// CommitmentKeyRing holds all derived keys needed to construct commitment and
30
// HTLC transactions. The keys are derived differently depending whether the
31
// commitment transaction is ours or the remote peer's. Private keys associated
32
// with each key may belong to the commitment owner or the "other party" which
33
// is referred to in the field comments, regardless of which is local and which
34
// is remote.
35
type CommitmentKeyRing struct {
36
        // CommitPoint is the "per commitment point" used to derive the tweak
37
        // for each base point.
38
        CommitPoint *btcec.PublicKey
39

40
        // LocalCommitKeyTweak is the tweak used to derive the local public key
41
        // from the local payment base point or the local private key from the
42
        // base point secret. This may be included in a SignDescriptor to
43
        // generate signatures for the local payment key.
44
        //
45
        // NOTE: This will always refer to "our" local key, regardless of
46
        // whether this is our commit or not.
47
        LocalCommitKeyTweak []byte
48

49
        // TODO(roasbeef): need delay tweak as well?
50

51
        // LocalHtlcKeyTweak is the tweak used to derive the local HTLC key
52
        // from the local HTLC base point. This value is needed in order to
53
        // derive the final key used within the HTLC scripts in the commitment
54
        // transaction.
55
        //
56
        // NOTE: This will always refer to "our" local HTLC key, regardless of
57
        // whether this is our commit or not.
58
        LocalHtlcKeyTweak []byte
59

60
        // LocalHtlcKey is the key that will be used in any clause paying to
61
        // our node of any HTLC scripts within the commitment transaction for
62
        // this key ring set.
63
        //
64
        // NOTE: This will always refer to "our" local HTLC key, regardless of
65
        // whether this is our commit or not.
66
        LocalHtlcKey *btcec.PublicKey
67

68
        // RemoteHtlcKey is the key that will be used in clauses within the
69
        // HTLC script that send money to the remote party.
70
        //
71
        // NOTE: This will always refer to "their" remote HTLC key, regardless
72
        // of whether this is our commit or not.
73
        RemoteHtlcKey *btcec.PublicKey
74

75
        // ToLocalKey is the commitment transaction owner's key which is
76
        // included in HTLC success and timeout transaction scripts. This is
77
        // the public key used for the to_local output of the commitment
78
        // transaction.
79
        //
80
        // NOTE: Who's key this is depends on the current perspective. If this
81
        // is our commitment this will be our key.
82
        ToLocalKey *btcec.PublicKey
83

84
        // ToRemoteKey is the non-owner's payment key in the commitment tx.
85
        // This is the key used to generate the to_remote output within the
86
        // commitment transaction.
87
        //
88
        // NOTE: Who's key this is depends on the current perspective. If this
89
        // is our commitment this will be their key.
90
        ToRemoteKey *btcec.PublicKey
91

92
        // RevocationKey is the key that can be used by the other party to
93
        // redeem outputs from a revoked commitment transaction if it were to
94
        // be published.
95
        //
96
        // NOTE: Who can sign for this key depends on the current perspective.
97
        // If this is our commitment, it means the remote node can sign for
98
        // this key in case of a breach.
99
        RevocationKey *btcec.PublicKey
100
}
101

102
// DeriveCommitmentKeys generates a new commitment key set using the base points
103
// and commitment point. The keys are derived differently depending on the type
104
// of channel, and whether the commitment transaction is ours or the remote
105
// peer's.
106
func DeriveCommitmentKeys(commitPoint *btcec.PublicKey,
107
        whoseCommit lntypes.ChannelParty, chanType channeldb.ChannelType,
108
        localChanCfg, remoteChanCfg *channeldb.ChannelConfig) *CommitmentKeyRing {
14,411✔
109

14,411✔
110
        tweaklessCommit := chanType.IsTweakless()
14,411✔
111

14,411✔
112
        // Depending on if this is our commit or not, we'll choose the correct
14,411✔
113
        // base point.
14,411✔
114
        localBasePoint := localChanCfg.PaymentBasePoint
14,411✔
115
        if whoseCommit.IsLocal() {
19,918✔
116
                localBasePoint = localChanCfg.DelayBasePoint
5,507✔
117
        }
5,507✔
118

119
        // First, we'll derive all the keys that don't depend on the context of
120
        // whose commitment transaction this is.
121
        keyRing := &CommitmentKeyRing{
14,411✔
122
                CommitPoint: commitPoint,
14,411✔
123

14,411✔
124
                LocalCommitKeyTweak: input.SingleTweakBytes(
14,411✔
125
                        commitPoint, localBasePoint.PubKey,
14,411✔
126
                ),
14,411✔
127
                LocalHtlcKeyTweak: input.SingleTweakBytes(
14,411✔
128
                        commitPoint, localChanCfg.HtlcBasePoint.PubKey,
14,411✔
129
                ),
14,411✔
130
                LocalHtlcKey: input.TweakPubKey(
14,411✔
131
                        localChanCfg.HtlcBasePoint.PubKey, commitPoint,
14,411✔
132
                ),
14,411✔
133
                RemoteHtlcKey: input.TweakPubKey(
14,411✔
134
                        remoteChanCfg.HtlcBasePoint.PubKey, commitPoint,
14,411✔
135
                ),
14,411✔
136
        }
14,411✔
137

14,411✔
138
        // We'll now compute the to_local, to_remote, and revocation key based
14,411✔
139
        // on the current commitment point. All keys are tweaked each state in
14,411✔
140
        // order to ensure the keys from each state are unlinkable. To create
14,411✔
141
        // the revocation key, we take the opposite party's revocation base
14,411✔
142
        // point and combine that with the current commitment point.
14,411✔
143
        var (
14,411✔
144
                toLocalBasePoint    *btcec.PublicKey
14,411✔
145
                toRemoteBasePoint   *btcec.PublicKey
14,411✔
146
                revocationBasePoint *btcec.PublicKey
14,411✔
147
        )
14,411✔
148
        if whoseCommit.IsLocal() {
19,918✔
149
                toLocalBasePoint = localChanCfg.DelayBasePoint.PubKey
5,507✔
150
                toRemoteBasePoint = remoteChanCfg.PaymentBasePoint.PubKey
5,507✔
151
                revocationBasePoint = remoteChanCfg.RevocationBasePoint.PubKey
5,507✔
152
        } else {
14,411✔
153
                toLocalBasePoint = remoteChanCfg.DelayBasePoint.PubKey
8,904✔
154
                toRemoteBasePoint = localChanCfg.PaymentBasePoint.PubKey
8,904✔
155
                revocationBasePoint = localChanCfg.RevocationBasePoint.PubKey
8,904✔
156
        }
8,904✔
157

158
        // With the base points assigned, we can now derive the actual keys
159
        // using the base point, and the current commitment tweak.
160
        keyRing.ToLocalKey = input.TweakPubKey(toLocalBasePoint, commitPoint)
14,411✔
161
        keyRing.RevocationKey = input.DeriveRevocationPubkey(
14,411✔
162
                revocationBasePoint, commitPoint,
14,411✔
163
        )
14,411✔
164

14,411✔
165
        // If this commitment should omit the tweak for the remote point, then
14,411✔
166
        // we'll use that directly, and ignore the commitPoint tweak.
14,411✔
167
        if tweaklessCommit {
26,970✔
168
                keyRing.ToRemoteKey = toRemoteBasePoint
12,559✔
169

12,559✔
170
                // If this is not our commitment, the above ToRemoteKey will be
12,559✔
171
                // ours, and we blank out the local commitment tweak to
12,559✔
172
                // indicate that the key should not be tweaked when signing.
12,559✔
173
                if whoseCommit.IsRemote() {
20,384✔
174
                        keyRing.LocalCommitKeyTweak = nil
7,825✔
175
                }
7,825✔
176
        } else {
1,852✔
177
                keyRing.ToRemoteKey = input.TweakPubKey(
1,852✔
178
                        toRemoteBasePoint, commitPoint,
1,852✔
179
                )
1,852✔
180
        }
1,852✔
181

182
        return keyRing
14,411✔
183
}
184

185
// WitnessScriptDesc holds the output script and the witness script for p2wsh
186
// outputs.
187
type WitnessScriptDesc struct {
188
        // OutputScript is the output's PkScript.
189
        OutputScript []byte
190

191
        // WitnessScript is the full script required to properly redeem the
192
        // output. This field should be set to the full script if a p2wsh
193
        // output is being signed. For p2wkh it should be set equal to the
194
        // PkScript.
195
        WitnessScript []byte
196
}
197

198
// PkScript is the public key script that commits to the final
199
// contract.
200
func (w *WitnessScriptDesc) PkScript() []byte {
1,454,299✔
201
        return w.OutputScript
1,454,299✔
202
}
1,454,299✔
203

204
// WitnessScriptToSign returns the witness script that we'll use when signing
205
// for the remote party, and also verifying signatures on our transactions. As
206
// an example, when we create an outgoing HTLC for the remote party, we want to
207
// sign their success path.
208
func (w *WitnessScriptDesc) WitnessScriptToSign() []byte {
476,569✔
209
        return w.WitnessScript
476,569✔
210
}
476,569✔
211

212
// WitnessScriptForPath returns the witness script for the given spending path.
213
// An error is returned if the path is unknown. This is useful as when
214
// constructing a control block for a given path, one also needs witness script
215
// being signed.
216
func (w *WitnessScriptDesc) WitnessScriptForPath(
217
        _ input.ScriptPath) ([]byte, error) {
296✔
218

296✔
219
        return w.WitnessScript, nil
296✔
220
}
296✔
221

222
// CommitScriptToSelf constructs the public key script for the output on the
223
// commitment transaction paying to the "owner" of said commitment transaction.
224
// The `initiator` argument should correspond to the owner of the commitment
225
// transaction which we are generating the to_local script for. If the other
226
// party learns of the preimage to the revocation hash, then they can claim all
227
// the settled funds in the channel, plus the unsettled funds.
228
func CommitScriptToSelf(chanType channeldb.ChannelType, initiator bool,
229
        selfKey, revokeKey *btcec.PublicKey, csvDelay, leaseExpiry uint32,
230
        auxLeaf input.AuxTapLeaf) (input.ScriptDescriptor, error) {
11,117✔
231

11,117✔
232
        switch {
11,117✔
233
        // For taproot scripts, we'll need to make a slightly modified script
234
        // where a NUMS key is used to force a script path reveal of either the
235
        // revocation or the CSV timeout.
236
        //
237
        // Our "redeem" script here is just the taproot witness program.
238
        case chanType.IsTaproot():
266✔
239
                return input.NewLocalCommitScriptTree(
266✔
240
                        csvDelay, selfKey, revokeKey, auxLeaf,
266✔
241
                )
266✔
242

243
        // If we are the initiator of a leased channel, then we have an
244
        // additional CLTV requirement in addition to the usual CSV
245
        // requirement.
UNCOV
246
        case initiator && chanType.HasLeaseExpiration():
×
UNCOV
247
                toLocalRedeemScript, err := input.LeaseCommitScriptToSelf(
×
UNCOV
248
                        selfKey, revokeKey, csvDelay, leaseExpiry,
×
UNCOV
249
                )
×
UNCOV
250
                if err != nil {
×
251
                        return nil, err
×
252
                }
×
253

UNCOV
254
                toLocalScriptHash, err := input.WitnessScriptHash(
×
UNCOV
255
                        toLocalRedeemScript,
×
UNCOV
256
                )
×
UNCOV
257
                if err != nil {
×
258
                        return nil, err
×
259
                }
×
260

UNCOV
261
                return &WitnessScriptDesc{
×
UNCOV
262
                        OutputScript:  toLocalScriptHash,
×
UNCOV
263
                        WitnessScript: toLocalRedeemScript,
×
UNCOV
264
                }, nil
×
265

266
        default:
10,851✔
267
                toLocalRedeemScript, err := input.CommitScriptToSelf(
10,851✔
268
                        csvDelay, selfKey, revokeKey,
10,851✔
269
                )
10,851✔
270
                if err != nil {
10,851✔
271
                        return nil, err
×
272
                }
×
273

274
                toLocalScriptHash, err := input.WitnessScriptHash(
10,851✔
275
                        toLocalRedeemScript,
10,851✔
276
                )
10,851✔
277
                if err != nil {
10,851✔
278
                        return nil, err
×
279
                }
×
280

281
                return &WitnessScriptDesc{
10,851✔
282
                        OutputScript:  toLocalScriptHash,
10,851✔
283
                        WitnessScript: toLocalRedeemScript,
10,851✔
284
                }, nil
10,851✔
285
        }
286
}
287

288
// CommitScriptToRemote derives the appropriate to_remote script based on the
289
// channel's commitment type. The `initiator` argument should correspond to the
290
// owner of the commitment transaction which we are generating the to_remote
291
// script for. The second return value is the CSV delay of the output script,
292
// what must be satisfied in order to spend the output.
293
func CommitScriptToRemote(chanType channeldb.ChannelType, initiator bool,
294
        remoteKey *btcec.PublicKey, leaseExpiry uint32,
295
        auxLeaf input.AuxTapLeaf) (input.ScriptDescriptor, uint32, error) {
11,061✔
296

11,061✔
297
        switch {
11,061✔
298
        // If we are not the initiator of a leased channel, then the remote
299
        // party has an additional CLTV requirement in addition to the 1 block
300
        // CSV requirement.
UNCOV
301
        case chanType.HasLeaseExpiration() && !initiator:
×
UNCOV
302
                script, err := input.LeaseCommitScriptToRemoteConfirmed(
×
UNCOV
303
                        remoteKey, leaseExpiry,
×
UNCOV
304
                )
×
UNCOV
305
                if err != nil {
×
306
                        return nil, 0, err
×
307
                }
×
308

UNCOV
309
                p2wsh, err := input.WitnessScriptHash(script)
×
UNCOV
310
                if err != nil {
×
311
                        return nil, 0, err
×
312
                }
×
313

UNCOV
314
                return &WitnessScriptDesc{
×
UNCOV
315
                        OutputScript:  p2wsh,
×
UNCOV
316
                        WitnessScript: script,
×
UNCOV
317
                }, 1, nil
×
318

319
        // For taproot channels, we'll use a slightly different format, where
320
        // we use a NUMS key to force the remote party to take a script path,
321
        // with the sole tap leaf enforcing the 1 CSV delay.
322
        case chanType.IsTaproot():
262✔
323
                toRemoteScriptTree, err := input.NewRemoteCommitScriptTree(
262✔
324
                        remoteKey, auxLeaf,
262✔
325
                )
262✔
326
                if err != nil {
262✔
327
                        return nil, 0, err
×
328
                }
×
329

330
                return toRemoteScriptTree, 1, nil
262✔
331

332
        // If this channel type has anchors, we derive the delayed to_remote
333
        // script.
334
        case chanType.HasAnchors():
278✔
335
                script, err := input.CommitScriptToRemoteConfirmed(remoteKey)
278✔
336
                if err != nil {
278✔
337
                        return nil, 0, err
×
338
                }
×
339

340
                p2wsh, err := input.WitnessScriptHash(script)
278✔
341
                if err != nil {
278✔
342
                        return nil, 0, err
×
343
                }
×
344

345
                return &WitnessScriptDesc{
278✔
346
                        OutputScript:  p2wsh,
278✔
347
                        WitnessScript: script,
278✔
348
                }, 1, nil
278✔
349

350
        default:
10,521✔
351
                // Otherwise the to_remote will be a simple p2wkh.
10,521✔
352
                p2wkh, err := input.CommitScriptUnencumbered(remoteKey)
10,521✔
353
                if err != nil {
10,521✔
354
                        return nil, 0, err
×
355
                }
×
356

357
                // Since this is a regular P2WKH, the WitnessScipt and PkScript
358
                // should both be set to the script hash.
359
                return &WitnessScriptDesc{
10,521✔
360
                        OutputScript:  p2wkh,
10,521✔
361
                        WitnessScript: p2wkh,
10,521✔
362
                }, 0, nil
10,521✔
363
        }
364
}
365

366
// HtlcSigHashType returns the sighash type to use for HTLC success and timeout
367
// transactions given the channel type.
368
func HtlcSigHashType(chanType channeldb.ChannelType) txscript.SigHashType {
6,979✔
369
        if chanType.HasAnchors() {
7,310✔
370
                return txscript.SigHashSingle | txscript.SigHashAnyOneCanPay
331✔
371
        }
331✔
372

373
        return txscript.SigHashAll
6,648✔
374
}
375

376
// HtlcSignDetails converts the passed parameters to a SignDetails valid for
377
// this channel type. For non-anchor channels this will return nil.
378
func HtlcSignDetails(chanType channeldb.ChannelType, signDesc input.SignDescriptor,
379
        sigHash txscript.SigHashType, peerSig input.Signature) *input.SignDetails {
96✔
380

96✔
381
        // Non-anchor channels don't need sign details, as the HTLC second
96✔
382
        // level cannot be altered.
96✔
383
        if !chanType.HasAnchors() {
137✔
384
                return nil
41✔
385
        }
41✔
386

387
        return &input.SignDetails{
55✔
388
                SignDesc:    signDesc,
55✔
389
                SigHashType: sigHash,
55✔
390
                PeerSig:     peerSig,
55✔
391
        }
55✔
392
}
393

394
// HtlcSecondLevelInputSequence dictates the sequence number we must use on the
395
// input to a second level HTLC transaction.
396
func HtlcSecondLevelInputSequence(chanType channeldb.ChannelType) uint32 {
476,405✔
397
        if chanType.HasAnchors() {
476,761✔
398
                return 1
356✔
399
        }
356✔
400

401
        return 0
476,049✔
402
}
403

404
// sweepSigHash returns the sign descriptor to use when signing a sweep
405
// transaction. For taproot channels, we'll use this to always sweep with
406
// sighash default.
407
func sweepSigHash(chanType channeldb.ChannelType) txscript.SigHashType {
324✔
408
        if chanType.IsTaproot() {
352✔
409
                return txscript.SigHashDefault
28✔
410
        }
28✔
411

412
        return txscript.SigHashAll
296✔
413
}
414

415
// SecondLevelHtlcScript derives the appropriate second level HTLC script based
416
// on the channel's commitment type. It is the uniform script that's used as the
417
// output for the second-level HTLC transactions. The second level transaction
418
// act as a sort of covenant, ensuring that a 2-of-2 multi-sig output can only
419
// be spent in a particular way, and to a particular output. The `initiator`
420
// argument should correspond to the owner of the commitment transaction which
421
// we are generating the to_local script for.
422
func SecondLevelHtlcScript(chanType channeldb.ChannelType, initiator bool,
423
        revocationKey, delayKey *btcec.PublicKey, csvDelay, leaseExpiry uint32,
424
        auxLeaf input.AuxTapLeaf) (input.ScriptDescriptor, error) {
476,500✔
425

476,500✔
426
        switch {
476,500✔
427
        // For taproot channels, the pkScript is a segwit v1 p2tr output.
428
        case chanType.IsTaproot():
149✔
429
                return input.TaprootSecondLevelScriptTree(
149✔
430
                        revocationKey, delayKey, csvDelay, auxLeaf,
149✔
431
                )
149✔
432

433
        // If we are the initiator of a leased channel, then we have an
434
        // additional CLTV requirement in addition to the usual CSV
435
        // requirement.
UNCOV
436
        case initiator && chanType.HasLeaseExpiration():
×
UNCOV
437
                witnessScript, err := input.LeaseSecondLevelHtlcScript(
×
UNCOV
438
                        revocationKey, delayKey, csvDelay, leaseExpiry,
×
UNCOV
439
                )
×
UNCOV
440
                if err != nil {
×
441
                        return nil, err
×
442
                }
×
443

UNCOV
444
                pkScript, err := input.WitnessScriptHash(witnessScript)
×
UNCOV
445
                if err != nil {
×
446
                        return nil, err
×
447
                }
×
448

UNCOV
449
                return &WitnessScriptDesc{
×
UNCOV
450
                        OutputScript:  pkScript,
×
UNCOV
451
                        WitnessScript: witnessScript,
×
UNCOV
452
                }, nil
×
453

454
        default:
476,351✔
455
                witnessScript, err := input.SecondLevelHtlcScript(
476,351✔
456
                        revocationKey, delayKey, csvDelay,
476,351✔
457
                )
476,351✔
458
                if err != nil {
476,351✔
459
                        return nil, err
×
460
                }
×
461

462
                pkScript, err := input.WitnessScriptHash(witnessScript)
476,351✔
463
                if err != nil {
476,351✔
464
                        return nil, err
×
465
                }
×
466

467
                return &WitnessScriptDesc{
476,351✔
468
                        OutputScript:  pkScript,
476,351✔
469
                        WitnessScript: witnessScript,
476,351✔
470
                }, nil
476,351✔
471
        }
472
}
473

474
// CommitWeight returns the base commitment weight before adding HTLCs.
475
func CommitWeight(chanType channeldb.ChannelType) lntypes.WeightUnit {
32,968✔
476
        switch {
32,968✔
477
        case chanType.IsTaproot():
522✔
478
                return input.TaprootCommitWeight
522✔
479

480
        // If this commitment has anchors, it will be slightly heavier.
481
        case chanType.HasAnchors():
1,838✔
482
                return input.AnchorCommitWeight
1,838✔
483

484
        default:
30,608✔
485
                return input.CommitWeight
30,608✔
486
        }
487
}
488

489
// HtlcTimeoutFee returns the fee in satoshis required for an HTLC timeout
490
// transaction based on the current fee rate.
491
func HtlcTimeoutFee(chanType channeldb.ChannelType,
492
        feePerKw chainfee.SatPerKWeight) btcutil.Amount {
4,295,352✔
493

4,295,352✔
494
        switch {
4,295,352✔
495
        // For zero-fee HTLC channels, this will always be zero, regardless of
496
        // feerate.
497
        case chanType.ZeroHtlcTxFee() || chanType.IsTaproot():
856✔
498
                return 0
856✔
499

500
        case chanType.HasAnchors():
588✔
501
                return feePerKw.FeeForWeight(input.HtlcTimeoutWeightConfirmed)
588✔
502

503
        default:
4,293,908✔
504
                return feePerKw.FeeForWeight(input.HtlcTimeoutWeight)
4,293,908✔
505
        }
506
}
507

508
// HtlcSuccessFee returns the fee in satoshis required for an HTLC success
509
// transaction based on the current fee rate.
510
func HtlcSuccessFee(chanType channeldb.ChannelType,
511
        feePerKw chainfee.SatPerKWeight) btcutil.Amount {
4,425,659✔
512

4,425,659✔
513
        switch {
4,425,659✔
514
        // For zero-fee HTLC channels, this will always be zero, regardless of
515
        // feerate.
516
        case chanType.ZeroHtlcTxFee() || chanType.IsTaproot():
1,307✔
517
                return 0
1,307✔
518

519
        case chanType.HasAnchors():
1,179✔
520
                return feePerKw.FeeForWeight(input.HtlcSuccessWeightConfirmed)
1,179✔
521

522
        default:
4,423,173✔
523
                return feePerKw.FeeForWeight(input.HtlcSuccessWeight)
4,423,173✔
524
        }
525
}
526

527
// CommitScriptAnchors return the scripts to use for the local and remote
528
// anchor.
529
func CommitScriptAnchors(chanType channeldb.ChannelType,
530
        localChanCfg, remoteChanCfg *channeldb.ChannelConfig,
531
        keyRing *CommitmentKeyRing) (
532
        input.ScriptDescriptor, input.ScriptDescriptor, error) {
428✔
533

428✔
534
        var (
428✔
535
                anchorScript func(
428✔
536
                        key *btcec.PublicKey) (input.ScriptDescriptor, error)
428✔
537

428✔
538
                keySelector func(*channeldb.ChannelConfig,
428✔
539
                        bool) *btcec.PublicKey
428✔
540
        )
428✔
541

428✔
542
        switch {
428✔
543
        // For taproot channels, the anchor is slightly different: the top
544
        // level key is now the (relative) local delay and remote public key,
545
        // since these are fully revealed once the commitment hits the chain.
546
        case chanType.IsTaproot():
179✔
547
                anchorScript = func(
179✔
548
                        key *btcec.PublicKey) (input.ScriptDescriptor, error) {
537✔
549

358✔
550
                        return input.NewAnchorScriptTree(key)
358✔
551
                }
358✔
552

553
                keySelector = func(cfg *channeldb.ChannelConfig,
179✔
554
                        local bool) *btcec.PublicKey {
537✔
555

358✔
556
                        if local {
537✔
557
                                return keyRing.ToLocalKey
179✔
558
                        }
179✔
559

560
                        return keyRing.ToRemoteKey
179✔
561
                }
562

563
        // For normal channels we'll use the multi-sig keys since those are
564
        // revealed when the channel closes
565
        default:
249✔
566
                // For normal channels, we'll create a p2wsh script based on
249✔
567
                // the target key.
249✔
568
                anchorScript = func(
249✔
569
                        key *btcec.PublicKey) (input.ScriptDescriptor, error) {
747✔
570

498✔
571
                        script, err := input.CommitScriptAnchor(key)
498✔
572
                        if err != nil {
498✔
573
                                return nil, err
×
574
                        }
×
575

576
                        scriptHash, err := input.WitnessScriptHash(script)
498✔
577
                        if err != nil {
498✔
578
                                return nil, err
×
579
                        }
×
580

581
                        return &WitnessScriptDesc{
498✔
582
                                OutputScript:  scriptHash,
498✔
583
                                WitnessScript: script,
498✔
584
                        }, nil
498✔
585
                }
586

587
                // For the existing channels, we'll always select the multi-sig
588
                // key from the party's channel config.
589
                keySelector = func(cfg *channeldb.ChannelConfig,
249✔
590
                        _ bool) *btcec.PublicKey {
747✔
591

498✔
592
                        return cfg.MultiSigKey.PubKey
498✔
593
                }
498✔
594
        }
595

596
        // Get the script used for the anchor output spendable by the local
597
        // node.
598
        localAnchor, err := anchorScript(keySelector(localChanCfg, true))
428✔
599
        if err != nil {
428✔
600
                return nil, nil, err
×
601
        }
×
602

603
        // And the anchor spendable by the remote node.
604
        remoteAnchor, err := anchorScript(keySelector(remoteChanCfg, false))
428✔
605
        if err != nil {
428✔
606
                return nil, nil, err
×
607
        }
×
608

609
        return localAnchor, remoteAnchor, nil
428✔
610
}
611

612
// CommitmentBuilder is a type that wraps the type of channel we are dealing
613
// with, and abstracts the various ways of constructing commitment
614
// transactions.
615
type CommitmentBuilder struct {
616
        // chanState is the underlying channel's state struct, used to
617
        // determine the type of channel we are dealing with, and relevant
618
        // parameters.
619
        chanState *channeldb.OpenChannel
620

621
        // obfuscator is a 48-bit state hint that's used to obfuscate the
622
        // current state number on the commitment transactions.
623
        obfuscator [StateHintSize]byte
624

625
        // auxLeafStore is an interface that allows us to fetch auxiliary
626
        // tapscript leaves for the commitment output.
627
        auxLeafStore fn.Option[AuxLeafStore]
628
}
629

630
// NewCommitmentBuilder creates a new CommitmentBuilder from chanState.
631
func NewCommitmentBuilder(chanState *channeldb.OpenChannel,
632
        leafStore fn.Option[AuxLeafStore]) *CommitmentBuilder {
800✔
633

800✔
634
        // The anchor channel type MUST be tweakless.
800✔
635
        if chanState.ChanType.HasAnchors() && !chanState.ChanType.IsTweakless() {
800✔
636
                panic("invalid channel type combination")
×
637
        }
638

639
        return &CommitmentBuilder{
800✔
640
                chanState:    chanState,
800✔
641
                obfuscator:   createStateHintObfuscator(chanState),
800✔
642
                auxLeafStore: leafStore,
800✔
643
        }
800✔
644
}
645

646
// createStateHintObfuscator derives and assigns the state hint obfuscator for
647
// the channel, which is used to encode the commitment height in the sequence
648
// number of commitment transaction inputs.
649
func createStateHintObfuscator(state *channeldb.OpenChannel) [StateHintSize]byte {
976✔
650
        if state.IsInitiator {
1,531✔
651
                return DeriveStateHintObfuscator(
555✔
652
                        state.LocalChanCfg.PaymentBasePoint.PubKey,
555✔
653
                        state.RemoteChanCfg.PaymentBasePoint.PubKey,
555✔
654
                )
555✔
655
        }
555✔
656

657
        return DeriveStateHintObfuscator(
421✔
658
                state.RemoteChanCfg.PaymentBasePoint.PubKey,
421✔
659
                state.LocalChanCfg.PaymentBasePoint.PubKey,
421✔
660
        )
421✔
661
}
662

663
// unsignedCommitmentTx is the final commitment created from evaluating an HTLC
664
// view at a given height, along with some meta data.
665
type unsignedCommitmentTx struct {
666
        // txn is the final, unsigned commitment transaction for this view.
667
        txn *wire.MsgTx
668

669
        // fee is the total fee of the commitment transaction.
670
        fee btcutil.Amount
671

672
        // ourBalance is our balance on this commitment *after* subtracting
673
        // commitment fees and anchor outputs. This can be different than the
674
        // balances before creating the commitment transaction as one party must
675
        // pay the commitment fee.
676
        ourBalance lnwire.MilliSatoshi
677

678
        // theirBalance is their balance of this commitment *after* subtracting
679
        // commitment fees and anchor outputs. This can be different than the
680
        // balances before creating the commitment transaction as one party must
681
        // pay the commitment fee.
682
        theirBalance lnwire.MilliSatoshi
683

684
        // cltvs is a sorted list of CLTV deltas for each HTLC on the commitment
685
        // transaction. Any non-htlc outputs will have a CLTV delay of zero.
686
        cltvs []uint32
687
}
688

689
// createUnsignedCommitmentTx generates the unsigned commitment transaction for
690
// a commitment view and returns it as part of the unsignedCommitmentTx. The
691
// passed in balances should be balances *before* subtracting any commitment
692
// fees, but after anchor outputs.
693
func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance,
694
        theirBalance lnwire.MilliSatoshi, whoseCommit lntypes.ChannelParty,
695
        feePerKw chainfee.SatPerKWeight, height uint64, originalHtlcView,
696
        filteredHTLCView *HtlcView, keyRing *CommitmentKeyRing,
697
        prevCommit *commitment) (*unsignedCommitmentTx, error) {
6,877✔
698

6,877✔
699
        dustLimit := cb.chanState.LocalChanCfg.DustLimit
6,877✔
700
        if whoseCommit.IsRemote() {
10,323✔
701
                dustLimit = cb.chanState.RemoteChanCfg.DustLimit
3,446✔
702
        }
3,446✔
703

704
        numHTLCs := int64(0)
6,877✔
705
        for _, htlc := range filteredHTLCView.Updates.Local {
417,127✔
706
                if HtlcIsDust(
410,250✔
707
                        cb.chanState.ChanType, false, whoseCommit, feePerKw,
410,250✔
708
                        htlc.Amount.ToSatoshis(), dustLimit,
410,250✔
709
                ) {
582,343✔
710

172,093✔
711
                        continue
172,093✔
712
                }
713

714
                numHTLCs++
238,157✔
715
        }
716
        for _, htlc := range filteredHTLCView.Updates.Remote {
417,116✔
717
                if HtlcIsDust(
410,239✔
718
                        cb.chanState.ChanType, true, whoseCommit, feePerKw,
410,239✔
719
                        htlc.Amount.ToSatoshis(), dustLimit,
410,239✔
720
                ) {
582,332✔
721

172,093✔
722
                        continue
172,093✔
723
                }
724

725
                numHTLCs++
238,146✔
726
        }
727

728
        // Next, we'll calculate the fee for the commitment transaction based
729
        // on its total weight. Once we have the total weight, we'll multiply
730
        // by the current fee-per-kw, then divide by 1000 to get the proper
731
        // fee.
732
        totalCommitWeight := CommitWeight(cb.chanState.ChanType) +
6,877✔
733
                lntypes.WeightUnit(input.HTLCWeight*numHTLCs)
6,877✔
734

6,877✔
735
        // With the weight known, we can now calculate the commitment fee,
6,877✔
736
        // ensuring that we account for any dust outputs trimmed above.
6,877✔
737
        commitFee := feePerKw.FeeForWeight(totalCommitWeight)
6,877✔
738
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
6,877✔
739

6,877✔
740
        // Currently, within the protocol, the initiator always pays the fees.
6,877✔
741
        // So we'll subtract the fee amount from the balance of the current
6,877✔
742
        // initiator. If the initiator is unable to pay the fee fully, then
6,877✔
743
        // their entire output is consumed.
6,877✔
744
        switch {
6,877✔
745
        case cb.chanState.IsInitiator && commitFee > ourBalance.ToSatoshis():
×
746
                ourBalance = 0
×
747

748
        case cb.chanState.IsInitiator:
3,442✔
749
                ourBalance -= commitFeeMSat
3,442✔
750

751
        case !cb.chanState.IsInitiator && commitFee > theirBalance.ToSatoshis():
×
752
                theirBalance = 0
×
753

754
        case !cb.chanState.IsInitiator:
3,435✔
755
                theirBalance -= commitFeeMSat
3,435✔
756
        }
757

758
        var commitTx *wire.MsgTx
6,877✔
759

6,877✔
760
        // Before we create the commitment transaction below, we'll try to see
6,877✔
761
        // if there're any aux leaves that need to be a part of the tapscript
6,877✔
762
        // tree. We'll only do this if we have a custom blob defined though.
6,877✔
763
        auxResult, err := fn.MapOptionZ(
6,877✔
764
                cb.auxLeafStore,
6,877✔
765
                func(s AuxLeafStore) fn.Result[CommitDiffAuxResult] {
13,687✔
766
                        return auxLeavesFromView(
6,810✔
767
                                s, cb.chanState, prevCommit.customBlob,
6,810✔
768
                                originalHtlcView, whoseCommit, ourBalance,
6,810✔
769
                                theirBalance, *keyRing,
6,810✔
770
                        )
6,810✔
771
                },
6,810✔
772
        ).Unpack()
773
        if err != nil {
6,877✔
774
                return nil, fmt.Errorf("unable to fetch aux leaves: %w", err)
×
775
        }
×
776

777
        // Depending on whether the transaction is ours or not, we call
778
        // CreateCommitTx with parameters matching the perspective, to generate
779
        // a new commitment transaction with all the latest unsettled/un-timed
780
        // out HTLCs.
781
        var leaseExpiry uint32
6,877✔
782
        if cb.chanState.ChanType.HasLeaseExpiration() {
6,877✔
UNCOV
783
                leaseExpiry = cb.chanState.ThawHeight
×
UNCOV
784
        }
×
785
        if whoseCommit.IsLocal() {
10,308✔
786
                commitTx, err = CreateCommitTx(
3,431✔
787
                        cb.chanState.ChanType, fundingTxIn(cb.chanState), keyRing,
3,431✔
788
                        &cb.chanState.LocalChanCfg, &cb.chanState.RemoteChanCfg,
3,431✔
789
                        ourBalance.ToSatoshis(), theirBalance.ToSatoshis(),
3,431✔
790
                        numHTLCs, cb.chanState.IsInitiator, leaseExpiry,
3,431✔
791
                        auxResult.AuxLeaves,
3,431✔
792
                )
3,431✔
793
        } else {
6,877✔
794
                commitTx, err = CreateCommitTx(
3,446✔
795
                        cb.chanState.ChanType, fundingTxIn(cb.chanState), keyRing,
3,446✔
796
                        &cb.chanState.RemoteChanCfg, &cb.chanState.LocalChanCfg,
3,446✔
797
                        theirBalance.ToSatoshis(), ourBalance.ToSatoshis(),
3,446✔
798
                        numHTLCs, !cb.chanState.IsInitiator, leaseExpiry,
3,446✔
799
                        auxResult.AuxLeaves,
3,446✔
800
                )
3,446✔
801
        }
3,446✔
802
        if err != nil {
6,877✔
803
                return nil, err
×
804
        }
×
805

806
        // Similarly, we'll now attempt to extract the set of aux leaves for
807
        // the set of incoming and outgoing HTLCs.
808
        incomingAuxLeaves := fn.MapOption(
6,877✔
809
                func(leaves CommitAuxLeaves) input.HtlcAuxLeaves {
6,877✔
810
                        return leaves.IncomingHtlcLeaves
×
811
                },
×
812
        )(auxResult.AuxLeaves)
813
        outgoingAuxLeaves := fn.MapOption(
6,877✔
814
                func(leaves CommitAuxLeaves) input.HtlcAuxLeaves {
6,877✔
815
                        return leaves.OutgoingHtlcLeaves
×
816
                },
×
817
        )(auxResult.AuxLeaves)
818

819
        // We'll now add all the HTLC outputs to the commitment transaction.
820
        // Each output includes an off-chain 2-of-2 covenant clause, so we'll
821
        // need the objective local/remote keys for this particular commitment
822
        // as well. For any non-dust HTLCs that are manifested on the commitment
823
        // transaction, we'll also record its CLTV which is required to sort the
824
        // commitment transaction below. The slice is initially sized to the
825
        // number of existing outputs, since any outputs already added are
826
        // commitment outputs and should correspond to zero values for the
827
        // purposes of sorting.
828
        cltvs := make([]uint32, len(commitTx.TxOut))
6,877✔
829
        htlcIndexes := make([]input.HtlcIndex, len(commitTx.TxOut))
6,877✔
830
        for _, htlc := range filteredHTLCView.Updates.Local {
417,127✔
831
                if HtlcIsDust(
410,250✔
832
                        cb.chanState.ChanType, false, whoseCommit, feePerKw,
410,250✔
833
                        htlc.Amount.ToSatoshis(), dustLimit,
410,250✔
834
                ) {
582,343✔
835

172,093✔
836
                        continue
172,093✔
837
                }
838

839
                auxLeaf := fn.ChainOption(
238,157✔
840
                        func(leaves input.HtlcAuxLeaves) input.AuxTapLeaf {
238,157✔
841
                                return leaves[htlc.HtlcIndex].AuxTapLeaf
×
842
                        },
×
843
                )(outgoingAuxLeaves)
844

845
                err := addHTLC(
238,157✔
846
                        commitTx, whoseCommit, false, htlc, keyRing,
238,157✔
847
                        cb.chanState.ChanType, auxLeaf,
238,157✔
848
                )
238,157✔
849
                if err != nil {
238,157✔
850
                        return nil, err
×
851
                }
×
852

853
                // We want to add the CLTV and HTLC index to their respective
854
                // slices, even if we already pre-allocated them.
855
                cltvs = append(cltvs, htlc.Timeout)               //nolint
238,157✔
856
                htlcIndexes = append(htlcIndexes, htlc.HtlcIndex) //nolint
238,157✔
857
        }
858
        for _, htlc := range filteredHTLCView.Updates.Remote {
417,116✔
859
                if HtlcIsDust(
410,239✔
860
                        cb.chanState.ChanType, true, whoseCommit, feePerKw,
410,239✔
861
                        htlc.Amount.ToSatoshis(), dustLimit,
410,239✔
862
                ) {
582,332✔
863

172,093✔
864
                        continue
172,093✔
865
                }
866

867
                auxLeaf := fn.ChainOption(
238,146✔
868
                        func(leaves input.HtlcAuxLeaves) input.AuxTapLeaf {
238,146✔
869
                                return leaves[htlc.HtlcIndex].AuxTapLeaf
×
870
                        },
×
871
                )(incomingAuxLeaves)
872

873
                err := addHTLC(
238,146✔
874
                        commitTx, whoseCommit, true, htlc, keyRing,
238,146✔
875
                        cb.chanState.ChanType, auxLeaf,
238,146✔
876
                )
238,146✔
877
                if err != nil {
238,146✔
878
                        return nil, err
×
879
                }
×
880

881
                // We want to add the CLTV and HTLC index to their respective
882
                // slices, even if we already pre-allocated them.
883
                cltvs = append(cltvs, htlc.Timeout)               //nolint
238,146✔
884
                htlcIndexes = append(htlcIndexes, htlc.HtlcIndex) //nolint
238,146✔
885
        }
886

887
        // Set the state hint of the commitment transaction to facilitate
888
        // quickly recovering the necessary penalty state in the case of an
889
        // uncooperative broadcast.
890
        err = SetStateNumHint(commitTx, height, cb.obfuscator)
6,877✔
891
        if err != nil {
6,877✔
892
                return nil, err
×
893
        }
×
894

895
        // Sort the transactions according to the agreed upon canonical
896
        // ordering (which might be customized for custom channel types, but
897
        // deterministic and both parties will arrive at the same result). This
898
        // lets us skip sending the entire transaction over, instead we'll just
899
        // send signatures.
900
        commitSort := auxResult.CommitSortFunc.UnwrapOr(DefaultCommitSort)
6,877✔
901
        err = commitSort(commitTx, cltvs, htlcIndexes)
6,877✔
902
        if err != nil {
6,877✔
903
                return nil, fmt.Errorf("unable to sort commitment "+
×
904
                        "transaction: %w", err)
×
905
        }
×
906

907
        // Next, we'll ensure that we don't accidentally create a commitment
908
        // transaction which would be invalid by consensus.
909
        uTx := btcutil.NewTx(commitTx)
6,877✔
910
        if err := blockchain.CheckTransactionSanity(uTx); err != nil {
6,877✔
911
                return nil, err
×
912
        }
×
913

914
        // Finally, we'll assert that were not attempting to draw more out of
915
        // the channel that was originally placed within it.
916
        var totalOut btcutil.Amount
6,877✔
917
        for _, txOut := range commitTx.TxOut {
497,438✔
918
                totalOut += btcutil.Amount(txOut.Value)
490,561✔
919
        }
490,561✔
920
        if totalOut+commitFee > cb.chanState.Capacity {
6,877✔
921
                return nil, fmt.Errorf("height=%v, for ChannelPoint(%v) "+
×
922
                        "attempts to consume %v while channel capacity is %v",
×
923
                        height, cb.chanState.FundingOutpoint,
×
924
                        totalOut+commitFee, cb.chanState.Capacity)
×
925
        }
×
926

927
        return &unsignedCommitmentTx{
6,877✔
928
                txn:          commitTx,
6,877✔
929
                fee:          commitFee,
6,877✔
930
                ourBalance:   ourBalance,
6,877✔
931
                theirBalance: theirBalance,
6,877✔
932
                cltvs:        cltvs,
6,877✔
933
        }, nil
6,877✔
934
}
935

936
// CreateCommitTx creates a commitment transaction, spending from specified
937
// funding output. The commitment transaction contains two outputs: one local
938
// output paying to the "owner" of the commitment transaction which can be
939
// spent after a relative block delay or revocation event, and a remote output
940
// paying the counterparty within the channel, which can be spent immediately
941
// or after a delay depending on the commitment type. The `initiator` argument
942
// should correspond to the owner of the commitment transaction we are creating.
943
func CreateCommitTx(chanType channeldb.ChannelType,
944
        fundingOutput wire.TxIn, keyRing *CommitmentKeyRing,
945
        localChanCfg, remoteChanCfg *channeldb.ChannelConfig,
946
        amountToLocal, amountToRemote btcutil.Amount,
947
        numHTLCs int64, initiator bool, leaseExpiry uint32,
948
        auxLeaves fn.Option[CommitAuxLeaves]) (*wire.MsgTx, error) {
7,673✔
949

7,673✔
950
        // First, we create the script for the delayed "pay-to-self" output.
7,673✔
951
        // This output has 2 main redemption clauses: either we can redeem the
7,673✔
952
        // output after a relative block delay, or the remote node can claim
7,673✔
953
        // the funds with the revocation key if we broadcast a revoked
7,673✔
954
        // commitment transaction.
7,673✔
955
        localAuxLeaf := fn.MapOption(func(l CommitAuxLeaves) input.AuxTapLeaf {
7,673✔
956
                return l.LocalAuxLeaf
×
957
        })(auxLeaves)
×
958
        toLocalScript, err := CommitScriptToSelf(
7,673✔
959
                chanType, initiator, keyRing.ToLocalKey, keyRing.RevocationKey,
7,673✔
960
                uint32(localChanCfg.CsvDelay), leaseExpiry,
7,673✔
961
                fn.FlattenOption(localAuxLeaf),
7,673✔
962
        )
7,673✔
963
        if err != nil {
7,673✔
964
                return nil, err
×
965
        }
×
966

967
        // Next, we create the script paying to the remote.
968
        remoteAuxLeaf := fn.MapOption(func(l CommitAuxLeaves) input.AuxTapLeaf {
7,673✔
969
                return l.RemoteAuxLeaf
×
970
        })(auxLeaves)
×
971
        toRemoteScript, _, err := CommitScriptToRemote(
7,673✔
972
                chanType, initiator, keyRing.ToRemoteKey, leaseExpiry,
7,673✔
973
                fn.FlattenOption(remoteAuxLeaf),
7,673✔
974
        )
7,673✔
975
        if err != nil {
7,673✔
976
                return nil, err
×
977
        }
×
978

979
        // Now that both output scripts have been created, we can finally create
980
        // the transaction itself. We use a transaction version of 2 since CSV
981
        // will fail unless the tx version is >= 2.
982
        commitTx := wire.NewMsgTx(2)
7,673✔
983
        commitTx.AddTxIn(&fundingOutput)
7,673✔
984

7,673✔
985
        // Avoid creating dust outputs within the commitment transaction.
7,673✔
986
        localOutput := amountToLocal >= localChanCfg.DustLimit
7,673✔
987
        if localOutput {
15,274✔
988
                commitTx.AddTxOut(&wire.TxOut{
7,601✔
989
                        PkScript: toLocalScript.PkScript(),
7,601✔
990
                        Value:    int64(amountToLocal),
7,601✔
991
                })
7,601✔
992
        }
7,601✔
993

994
        remoteOutput := amountToRemote >= localChanCfg.DustLimit
7,673✔
995
        if remoteOutput {
15,276✔
996
                commitTx.AddTxOut(&wire.TxOut{
7,603✔
997
                        PkScript: toRemoteScript.PkScript(),
7,603✔
998
                        Value:    int64(amountToRemote),
7,603✔
999
                })
7,603✔
1000
        }
7,603✔
1001

1002
        // If this channel type has anchors, we'll also add those.
1003
        if chanType.HasAnchors() {
8,066✔
1004
                localAnchor, remoteAnchor, err := CommitScriptAnchors(
393✔
1005
                        chanType, localChanCfg, remoteChanCfg, keyRing,
393✔
1006
                )
393✔
1007
                if err != nil {
393✔
1008
                        return nil, err
×
1009
                }
×
1010

1011
                // Add local anchor output only if we have a commitment output
1012
                // or there are HTLCs.
1013
                if localOutput || numHTLCs > 0 {
770✔
1014
                        commitTx.AddTxOut(&wire.TxOut{
377✔
1015
                                PkScript: localAnchor.PkScript(),
377✔
1016
                                Value:    int64(AnchorSize),
377✔
1017
                        })
377✔
1018
                }
377✔
1019

1020
                // Add anchor output to remote only if they have a commitment
1021
                // output or there are HTLCs.
1022
                if remoteOutput || numHTLCs > 0 {
770✔
1023
                        commitTx.AddTxOut(&wire.TxOut{
377✔
1024
                                PkScript: remoteAnchor.PkScript(),
377✔
1025
                                Value:    int64(AnchorSize),
377✔
1026
                        })
377✔
1027
                }
377✔
1028
        }
1029

1030
        return commitTx, nil
7,673✔
1031
}
1032

1033
// CoopCloseBalance returns the final balances that should be used to create
1034
// the cooperative close tx, given the channel type and transaction fee.
1035
func CoopCloseBalance(chanType channeldb.ChannelType, isInitiator bool,
1036
        coopCloseFee, ourBalance, theirBalance,
1037
        commitFee btcutil.Amount) (btcutil.Amount, btcutil.Amount, error) {
38✔
1038

38✔
1039
        // We'll make sure we account for the complete balance by adding the
38✔
1040
        // current dangling commitment fee to the balance of the initiator.
38✔
1041
        initiatorDelta := commitFee
38✔
1042

38✔
1043
        // Since the initiator's balance also is stored after subtracting the
38✔
1044
        // anchor values, add that back in case this was an anchor commitment.
38✔
1045
        if chanType.HasAnchors() {
42✔
1046
                initiatorDelta += 2 * AnchorSize
4✔
1047
        }
4✔
1048

1049
        // The initiator will pay the full coop close fee, subtract that value
1050
        // from their balance.
1051
        initiatorDelta -= coopCloseFee
38✔
1052

38✔
1053
        if isInitiator {
58✔
1054
                ourBalance += initiatorDelta
20✔
1055
        } else {
38✔
1056
                theirBalance += initiatorDelta
18✔
1057
        }
18✔
1058

1059
        // During fee negotiation it should always be verified that the
1060
        // initiator can pay the proposed fee, but we do a sanity check just to
1061
        // be sure here.
1062
        if ourBalance < 0 || theirBalance < 0 {
39✔
1063
                return 0, 0, fmt.Errorf("initiator cannot afford proposed " +
1✔
1064
                        "coop close fee")
1✔
1065
        }
1✔
1066

1067
        return ourBalance, theirBalance, nil
37✔
1068
}
1069

1070
// genSegwitV0HtlcScript generates the HTLC scripts for a normal segwit v0
1071
// channel.
1072
func genSegwitV0HtlcScript(chanType channeldb.ChannelType,
1073
        isIncoming bool, whoseCommit lntypes.ChannelParty, timeout uint32,
1074
        rHash [32]byte, keyRing *CommitmentKeyRing,
1075
) (*WitnessScriptDesc, error) {
476,661✔
1076

476,661✔
1077
        var (
476,661✔
1078
                witnessScript []byte
476,661✔
1079
                err           error
476,661✔
1080
        )
476,661✔
1081

476,661✔
1082
        // Choose scripts based on channel type.
476,661✔
1083
        confirmedHtlcSpends := false
476,661✔
1084
        if chanType.HasAnchors() {
476,896✔
1085
                confirmedHtlcSpends = true
235✔
1086
        }
235✔
1087

1088
        // Generate the proper redeem scripts for the HTLC output modified by
1089
        // two-bits denoting if this is an incoming HTLC, and if the HTLC is
1090
        // being applied to their commitment transaction or ours.
1091
        switch {
476,661✔
1092
        // The HTLC is paying to us, and being applied to our commitment
1093
        // transaction. So we need to use the receiver's version of the HTLC
1094
        // script.
1095
        case isIncoming && whoseCommit.IsLocal():
119,470✔
1096
                witnessScript, err = input.ReceiverHTLCScript(
119,470✔
1097
                        timeout, keyRing.RemoteHtlcKey, keyRing.LocalHtlcKey,
119,470✔
1098
                        keyRing.RevocationKey, rHash[:], confirmedHtlcSpends,
119,470✔
1099
                )
119,470✔
1100

1101
        // We're being paid via an HTLC by the remote party, and the HTLC is
1102
        // being added to their commitment transaction, so we use the sender's
1103
        // version of the HTLC script.
1104
        case isIncoming && whoseCommit.IsRemote():
118,819✔
1105
                witnessScript, err = input.SenderHTLCScript(
118,819✔
1106
                        keyRing.RemoteHtlcKey, keyRing.LocalHtlcKey,
118,819✔
1107
                        keyRing.RevocationKey, rHash[:], confirmedHtlcSpends,
118,819✔
1108
                )
118,819✔
1109

1110
        // We're sending an HTLC which is being added to our commitment
1111
        // transaction. Therefore, we need to use the sender's version of the
1112
        // HTLC script.
1113
        case !isIncoming && whoseCommit.IsLocal():
118,834✔
1114
                witnessScript, err = input.SenderHTLCScript(
118,834✔
1115
                        keyRing.LocalHtlcKey, keyRing.RemoteHtlcKey,
118,834✔
1116
                        keyRing.RevocationKey, rHash[:], confirmedHtlcSpends,
118,834✔
1117
                )
118,834✔
1118

1119
        // Finally, we're paying the remote party via an HTLC, which is being
1120
        // added to their commitment transaction. Therefore, we use the
1121
        // receiver's version of the HTLC script.
1122
        case !isIncoming && whoseCommit.IsRemote():
119,538✔
1123
                witnessScript, err = input.ReceiverHTLCScript(
119,538✔
1124
                        timeout, keyRing.LocalHtlcKey, keyRing.RemoteHtlcKey,
119,538✔
1125
                        keyRing.RevocationKey, rHash[:], confirmedHtlcSpends,
119,538✔
1126
                )
119,538✔
1127
        }
1128
        if err != nil {
476,661✔
1129
                return nil, err
×
1130
        }
×
1131

1132
        // Now that we have the redeem scripts, create the P2WSH public key
1133
        // script for the output itself.
1134
        htlcP2WSH, err := input.WitnessScriptHash(witnessScript)
476,661✔
1135
        if err != nil {
476,661✔
1136
                return nil, err
×
1137
        }
×
1138

1139
        return &WitnessScriptDesc{
476,661✔
1140
                OutputScript:  htlcP2WSH,
476,661✔
1141
                WitnessScript: witnessScript,
476,661✔
1142
        }, nil
476,661✔
1143
}
1144

1145
// GenTaprootHtlcScript generates the HTLC scripts for a taproot+musig2
1146
// channel.
1147
func GenTaprootHtlcScript(isIncoming bool, whoseCommit lntypes.ChannelParty,
1148
        timeout uint32, rHash [32]byte, keyRing *CommitmentKeyRing,
1149
        auxLeaf input.AuxTapLeaf) (*input.HtlcScriptTree, error) {
201✔
1150

201✔
1151
        var (
201✔
1152
                htlcScriptTree *input.HtlcScriptTree
201✔
1153
                err            error
201✔
1154
        )
201✔
1155

201✔
1156
        // Generate the proper redeem scripts for the HTLC output modified by
201✔
1157
        // two-bits denoting if this is an incoming HTLC, and if the HTLC is
201✔
1158
        // being applied to their commitment transaction or ours.
201✔
1159
        switch {
201✔
1160
        // The HTLC is paying to us, and being applied to our commitment
1161
        // transaction. So we need to use the receiver's version of HTLC the
1162
        // script.
1163
        case isIncoming && whoseCommit.IsLocal():
52✔
1164
                htlcScriptTree, err = input.ReceiverHTLCScriptTaproot(
52✔
1165
                        timeout, keyRing.RemoteHtlcKey, keyRing.LocalHtlcKey,
52✔
1166
                        keyRing.RevocationKey, rHash[:], whoseCommit, auxLeaf,
52✔
1167
                )
52✔
1168

1169
        // We're being paid via an HTLC by the remote party, and the HTLC is
1170
        // being added to their commitment transaction, so we use the sender's
1171
        // version of the HTLC script.
1172
        case isIncoming && whoseCommit.IsRemote():
44✔
1173
                htlcScriptTree, err = input.SenderHTLCScriptTaproot(
44✔
1174
                        keyRing.RemoteHtlcKey, keyRing.LocalHtlcKey,
44✔
1175
                        keyRing.RevocationKey, rHash[:], whoseCommit, auxLeaf,
44✔
1176
                )
44✔
1177

1178
        // We're sending an HTLC which is being added to our commitment
1179
        // transaction. Therefore, we need to use the sender's version of the
1180
        // HTLC script.
1181
        case !isIncoming && whoseCommit.IsLocal():
48✔
1182
                htlcScriptTree, err = input.SenderHTLCScriptTaproot(
48✔
1183
                        keyRing.LocalHtlcKey, keyRing.RemoteHtlcKey,
48✔
1184
                        keyRing.RevocationKey, rHash[:], whoseCommit, auxLeaf,
48✔
1185
                )
48✔
1186

1187
        // Finally, we're paying the remote party via an HTLC, which is being
1188
        // added to their commitment transaction. Therefore, we use the
1189
        // receiver's version of the HTLC script.
1190
        case !isIncoming && whoseCommit.IsRemote():
57✔
1191
                htlcScriptTree, err = input.ReceiverHTLCScriptTaproot(
57✔
1192
                        timeout, keyRing.LocalHtlcKey, keyRing.RemoteHtlcKey,
57✔
1193
                        keyRing.RevocationKey, rHash[:], whoseCommit, auxLeaf,
57✔
1194
                )
57✔
1195
        }
1196

1197
        return htlcScriptTree, err
201✔
1198
}
1199

1200
// genHtlcScript generates the proper P2WSH public key scripts for the HTLC
1201
// output modified by two-bits denoting if this is an incoming HTLC, and if the
1202
// HTLC is being applied to their commitment transaction or ours. A script
1203
// multiplexer for the various spending paths is returned. The script path that
1204
// we need to sign for the remote party (2nd level HTLCs) is also returned
1205
// along side the multiplexer.
1206
func genHtlcScript(chanType channeldb.ChannelType, isIncoming bool,
1207
        whoseCommit lntypes.ChannelParty, timeout uint32, rHash [32]byte,
1208
        keyRing *CommitmentKeyRing,
1209
        auxLeaf input.AuxTapLeaf) (input.ScriptDescriptor, error) {
476,862✔
1210

476,862✔
1211
        if !chanType.IsTaproot() {
953,523✔
1212
                return genSegwitV0HtlcScript(
476,661✔
1213
                        chanType, isIncoming, whoseCommit, timeout, rHash,
476,661✔
1214
                        keyRing,
476,661✔
1215
                )
476,661✔
1216
        }
476,661✔
1217

1218
        return GenTaprootHtlcScript(
201✔
1219
                isIncoming, whoseCommit, timeout, rHash, keyRing, auxLeaf,
201✔
1220
        )
201✔
1221
}
1222

1223
// addHTLC adds a new HTLC to the passed commitment transaction. One of four
1224
// full scripts will be generated for the HTLC output depending on if the HTLC
1225
// is incoming and if it's being applied to our commitment transaction or that
1226
// of the remote node's. Additionally, in order to be able to efficiently
1227
// locate the added HTLC on the commitment transaction from the
1228
// paymentDescriptor that generated it, the generated script is stored within
1229
// the descriptor itself.
1230
func addHTLC(commitTx *wire.MsgTx, whoseCommit lntypes.ChannelParty,
1231
        isIncoming bool, paymentDesc *paymentDescriptor,
1232
        keyRing *CommitmentKeyRing, chanType channeldb.ChannelType,
1233
        auxLeaf input.AuxTapLeaf) error {
476,303✔
1234

476,303✔
1235
        timeout := paymentDesc.Timeout
476,303✔
1236
        rHash := paymentDesc.RHash
476,303✔
1237

476,303✔
1238
        scriptInfo, err := genHtlcScript(
476,303✔
1239
                chanType, isIncoming, whoseCommit, timeout, rHash, keyRing,
476,303✔
1240
                auxLeaf,
476,303✔
1241
        )
476,303✔
1242
        if err != nil {
476,303✔
1243
                return err
×
1244
        }
×
1245

1246
        pkScript := scriptInfo.PkScript()
476,303✔
1247

476,303✔
1248
        // Add the new HTLC outputs to the respective commitment transactions.
476,303✔
1249
        amountPending := int64(paymentDesc.Amount.ToSatoshis())
476,303✔
1250
        commitTx.AddTxOut(wire.NewTxOut(amountPending, pkScript))
476,303✔
1251

476,303✔
1252
        // Store the pkScript of this particular paymentDescriptor so we can
476,303✔
1253
        // quickly locate it within the commitment transaction later.
476,303✔
1254
        if whoseCommit.IsLocal() {
714,449✔
1255
                paymentDesc.ourPkScript = pkScript
238,146✔
1256

238,146✔
1257
                paymentDesc.ourWitnessScript = scriptInfo.WitnessScriptToSign()
238,146✔
1258
        } else {
476,303✔
1259
                paymentDesc.theirPkScript = pkScript
238,157✔
1260

238,157✔
1261
                //nolint:lll
238,157✔
1262
                paymentDesc.theirWitnessScript = scriptInfo.WitnessScriptToSign()
238,157✔
1263
        }
238,157✔
1264

1265
        return nil
476,303✔
1266
}
1267

1268
// findOutputIndexesFromRemote finds the index of our and their outputs from
1269
// the remote commitment transaction. It derives the key ring to compute the
1270
// output scripts and compares them against the outputs inside the commitment
1271
// to find the match.
1272
func findOutputIndexesFromRemote(revocationPreimage *chainhash.Hash,
1273
        chanState *channeldb.OpenChannel,
1274
        leafStore fn.Option[AuxLeafStore]) (uint32, uint32, error) {
3,359✔
1275

3,359✔
1276
        // Init the output indexes as empty.
3,359✔
1277
        ourIndex := uint32(channeldb.OutputIndexEmpty)
3,359✔
1278
        theirIndex := uint32(channeldb.OutputIndexEmpty)
3,359✔
1279

3,359✔
1280
        chanCommit := chanState.RemoteCommitment
3,359✔
1281
        _, commitmentPoint := btcec.PrivKeyFromBytes(revocationPreimage[:])
3,359✔
1282

3,359✔
1283
        // With the commitment point generated, we can now derive the king ring
3,359✔
1284
        // which will be used to generate the output scripts.
3,359✔
1285
        keyRing := DeriveCommitmentKeys(
3,359✔
1286
                commitmentPoint, lntypes.Remote, chanState.ChanType,
3,359✔
1287
                &chanState.LocalChanCfg, &chanState.RemoteChanCfg,
3,359✔
1288
        )
3,359✔
1289

3,359✔
1290
        // Since it's remote commitment chain, we'd used the mirrored values.
3,359✔
1291
        //
3,359✔
1292
        // We use the remote's channel config for the csv delay.
3,359✔
1293
        theirDelay := uint32(chanState.RemoteChanCfg.CsvDelay)
3,359✔
1294

3,359✔
1295
        // If we are the initiator of this channel, then it's be false from the
3,359✔
1296
        // remote's PoV.
3,359✔
1297
        isRemoteInitiator := !chanState.IsInitiator
3,359✔
1298

3,359✔
1299
        var leaseExpiry uint32
3,359✔
1300
        if chanState.ChanType.HasLeaseExpiration() {
3,359✔
UNCOV
1301
                leaseExpiry = chanState.ThawHeight
×
UNCOV
1302
        }
×
1303

1304
        // If we have a custom blob, then we'll attempt to fetch the aux leaves
1305
        // for this state.
1306
        auxResult, err := fn.MapOptionZ(
3,359✔
1307
                leafStore, func(a AuxLeafStore) fn.Result[CommitDiffAuxResult] {
6,674✔
1308
                        return a.FetchLeavesFromCommit(
3,315✔
1309
                                NewAuxChanState(chanState), chanCommit,
3,315✔
1310
                                *keyRing,
3,315✔
1311
                        )
3,315✔
1312
                },
3,315✔
1313
        ).Unpack()
1314
        if err != nil {
3,359✔
1315
                return ourIndex, theirIndex, fmt.Errorf("unable to fetch aux "+
×
1316
                        "leaves: %w", err)
×
1317
        }
×
1318

1319
        // Map the scripts from our PoV. When facing a local commitment, the
1320
        // to_local output belongs to us and the to_remote output belongs to
1321
        // them. When facing a remote commitment, the to_local output belongs to
1322
        // them and the to_remote output belongs to us.
1323

1324
        // Compute the to_local script. From our PoV, when facing a remote
1325
        // commitment, the to_local output belongs to them.
1326
        localAuxLeaf := fn.ChainOption(
3,359✔
1327
                func(l CommitAuxLeaves) input.AuxTapLeaf {
3,359✔
1328
                        return l.LocalAuxLeaf
×
1329
                },
×
1330
        )(auxResult.AuxLeaves)
1331
        theirScript, err := CommitScriptToSelf(
3,359✔
1332
                chanState.ChanType, isRemoteInitiator, keyRing.ToLocalKey,
3,359✔
1333
                keyRing.RevocationKey, theirDelay, leaseExpiry, localAuxLeaf,
3,359✔
1334
        )
3,359✔
1335
        if err != nil {
3,359✔
1336
                return ourIndex, theirIndex, err
×
1337
        }
×
1338

1339
        // Compute the to_remote script. From our PoV, when facing a remote
1340
        // commitment, the to_remote output belongs to us.
1341
        remoteAuxLeaf := fn.ChainOption(
3,359✔
1342
                func(l CommitAuxLeaves) input.AuxTapLeaf {
3,359✔
1343
                        return l.RemoteAuxLeaf
×
1344
                },
×
1345
        )(auxResult.AuxLeaves)
1346
        ourScript, _, err := CommitScriptToRemote(
3,359✔
1347
                chanState.ChanType, isRemoteInitiator, keyRing.ToRemoteKey,
3,359✔
1348
                leaseExpiry, remoteAuxLeaf,
3,359✔
1349
        )
3,359✔
1350
        if err != nil {
3,359✔
1351
                return ourIndex, theirIndex, err
×
1352
        }
×
1353

1354
        // Now compare the scripts to find our/their output index.
1355
        for i, txOut := range chanCommit.CommitTx.TxOut {
248,017✔
1356
                switch {
244,658✔
1357
                case bytes.Equal(txOut.PkScript, ourScript.PkScript()):
3,164✔
1358
                        ourIndex = uint32(i)
3,164✔
1359
                case bytes.Equal(txOut.PkScript, theirScript.PkScript()):
3,163✔
1360
                        theirIndex = uint32(i)
3,163✔
1361
                }
1362
        }
1363

1364
        return ourIndex, theirIndex, nil
3,359✔
1365
}
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