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

lightningnetwork / lnd / 9915780197

13 Jul 2024 12:30AM UTC coverage: 49.268% (-9.1%) from 58.413%
9915780197

push

github

web-flow
Merge pull request #8653 from ProofOfKeags/fn-prim

DynComms [0/n]: `fn` package additions

92837 of 188433 relevant lines covered (49.27%)

1.55 hits per line

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

89.06
/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/input"
15
        "github.com/lightningnetwork/lnd/lntypes"
16
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
17
        "github.com/lightningnetwork/lnd/lnwire"
18
)
19

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

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

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

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

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

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

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

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

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

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

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

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

3✔
109
        tweaklessCommit := chanType.IsTweakless()
3✔
110

3✔
111
        // Depending on if this is our commit or not, we'll choose the correct
3✔
112
        // base point.
3✔
113
        localBasePoint := localChanCfg.PaymentBasePoint
3✔
114
        if isOurCommit {
6✔
115
                localBasePoint = localChanCfg.DelayBasePoint
3✔
116
        }
3✔
117

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

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

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

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

3✔
164
        // If this commitment should omit the tweak for the remote point, then
3✔
165
        // we'll use that directly, and ignore the commitPoint tweak.
3✔
166
        if tweaklessCommit {
6✔
167
                keyRing.ToRemoteKey = toRemoteBasePoint
3✔
168

3✔
169
                // If this is not our commitment, the above ToRemoteKey will be
3✔
170
                // ours, and we blank out the local commitment tweak to
3✔
171
                // indicate that the key should not be tweaked when signing.
3✔
172
                if !isOurCommit {
6✔
173
                        keyRing.LocalCommitKeyTweak = nil
3✔
174
                }
3✔
175
        } else {
3✔
176
                keyRing.ToRemoteKey = input.TweakPubKey(
3✔
177
                        toRemoteBasePoint, commitPoint,
3✔
178
                )
3✔
179
        }
3✔
180

181
        return keyRing
3✔
182
}
183

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

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

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

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

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

3✔
218
        return w.WitnessScript, nil
3✔
219
}
3✔
220

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

3✔
232
        switch {
3✔
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():
3✔
239
                return input.NewLocalCommitScriptTree(
3✔
240
                        csvDelay, selfKey, revokeKey,
3✔
241
                )
3✔
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.
246
        case initiator && chanType.HasLeaseExpiration():
3✔
247
                toLocalRedeemScript, err := input.LeaseCommitScriptToSelf(
3✔
248
                        selfKey, revokeKey, csvDelay, leaseExpiry,
3✔
249
                )
3✔
250
                if err != nil {
3✔
251
                        return nil, err
×
252
                }
×
253

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

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

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

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

281
                return &WitnessScriptDesc{
3✔
282
                        OutputScript:  toLocalScriptHash,
3✔
283
                        WitnessScript: toLocalRedeemScript,
3✔
284
                }, nil
3✔
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,
295
        leaseExpiry uint32) (input.ScriptDescriptor, uint32, error) {
3✔
296

3✔
297
        switch {
3✔
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.
301
        case chanType.HasLeaseExpiration() && !initiator:
3✔
302
                script, err := input.LeaseCommitScriptToRemoteConfirmed(
3✔
303
                        remoteKey, leaseExpiry,
3✔
304
                )
3✔
305
                if err != nil {
3✔
306
                        return nil, 0, err
×
307
                }
×
308

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

314
                return &WitnessScriptDesc{
3✔
315
                        OutputScript:  p2wsh,
3✔
316
                        WitnessScript: script,
3✔
317
                }, 1, nil
3✔
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():
3✔
323
                toRemoteScriptTree, err := input.NewRemoteCommitScriptTree(
3✔
324
                        remoteKey,
3✔
325
                )
3✔
326
                if err != nil {
3✔
327
                        return nil, 0, err
×
328
                }
×
329

330
                return toRemoteScriptTree, 1, nil
3✔
331

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

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

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

350
        default:
3✔
351
                // Otherwise the to_remote will be a simple p2wkh.
3✔
352
                p2wkh, err := input.CommitScriptUnencumbered(remoteKey)
3✔
353
                if err != nil {
3✔
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{
3✔
360
                        OutputScript:  p2wkh,
3✔
361
                        WitnessScript: p2wkh,
3✔
362
                }, 0, nil
3✔
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 {
3✔
369
        if chanType.HasAnchors() {
6✔
370
                return txscript.SigHashSingle | txscript.SigHashAnyOneCanPay
3✔
371
        }
3✔
372

373
        return txscript.SigHashAll
3✔
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 {
3✔
380

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

387
        return &input.SignDetails{
3✔
388
                SignDesc:    signDesc,
3✔
389
                SigHashType: sigHash,
3✔
390
                PeerSig:     peerSig,
3✔
391
        }
3✔
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 {
3✔
397
        if chanType.HasAnchors() {
6✔
398
                return 1
3✔
399
        }
3✔
400

401
        return 0
3✔
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 {
3✔
408
        if chanType.IsTaproot() {
6✔
409
                return txscript.SigHashDefault
3✔
410
        }
3✔
411

412
        return txscript.SigHashAll
3✔
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,
424
        csvDelay, leaseExpiry uint32) (input.ScriptDescriptor, error) {
3✔
425

3✔
426
        switch {
3✔
427
        // For taproot channels, the pkScript is a segwit v1 p2tr output.
428
        case chanType.IsTaproot():
3✔
429
                return input.TaprootSecondLevelScriptTree(
3✔
430
                        revocationKey, delayKey, csvDelay,
3✔
431
                )
3✔
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.
436
        case initiator && chanType.HasLeaseExpiration():
3✔
437
                witnessScript, err := input.LeaseSecondLevelHtlcScript(
3✔
438
                        revocationKey, delayKey, csvDelay, leaseExpiry,
3✔
439
                )
3✔
440
                if err != nil {
3✔
441
                        return nil, err
×
442
                }
×
443

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

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

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

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

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

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

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

484
        default:
3✔
485
                return input.CommitWeight
3✔
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 {
3✔
493

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

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

503
        default:
3✔
504
                return feePerKw.FeeForWeight(input.HtlcTimeoutWeight)
3✔
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 {
3✔
512

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

519
        case chanType.HasAnchors():
×
520
                return feePerKw.FeeForWeight(input.HtlcSuccessWeightConfirmed)
×
521

522
        default:
3✔
523
                return feePerKw.FeeForWeight(input.HtlcSuccessWeight)
3✔
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) {
3✔
533

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

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

3✔
542
        switch {
3✔
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():
3✔
547
                anchorScript = func(key *btcec.PublicKey,
3✔
548
                ) (input.ScriptDescriptor, error) {
6✔
549

3✔
550
                        return input.NewAnchorScriptTree(
3✔
551
                                key,
3✔
552
                        )
3✔
553
                }
3✔
554

555
                keySelector = func(cfg *channeldb.ChannelConfig,
3✔
556
                        local bool) *btcec.PublicKey {
6✔
557

3✔
558
                        if local {
6✔
559
                                return keyRing.ToLocalKey
3✔
560
                        }
3✔
561

562
                        return keyRing.ToRemoteKey
3✔
563
                }
564

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

3✔
573
                        script, err := input.CommitScriptAnchor(key)
3✔
574
                        if err != nil {
3✔
575
                                return nil, err
×
576
                        }
×
577

578
                        scriptHash, err := input.WitnessScriptHash(script)
3✔
579
                        if err != nil {
3✔
580
                                return nil, err
×
581
                        }
×
582

583
                        return &WitnessScriptDesc{
3✔
584
                                OutputScript:  scriptHash,
3✔
585
                                WitnessScript: script,
3✔
586
                        }, nil
3✔
587
                }
588

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

3✔
594
                        return cfg.MultiSigKey.PubKey
3✔
595
                }
3✔
596
        }
597

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

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

611
        return localAnchor, remoteAnchor, nil
3✔
612
}
613

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

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

628
// NewCommitmentBuilder creates a new CommitmentBuilder from chanState.
629
func NewCommitmentBuilder(chanState *channeldb.OpenChannel) *CommitmentBuilder {
3✔
630
        // The anchor channel type MUST be tweakless.
3✔
631
        if chanState.ChanType.HasAnchors() && !chanState.ChanType.IsTweakless() {
3✔
632
                panic("invalid channel type combination")
×
633
        }
634

635
        return &CommitmentBuilder{
3✔
636
                chanState:  chanState,
3✔
637
                obfuscator: createStateHintObfuscator(chanState),
3✔
638
        }
3✔
639
}
640

641
// createStateHintObfuscator derives and assigns the state hint obfuscator for
642
// the channel, which is used to encode the commitment height in the sequence
643
// number of commitment transaction inputs.
644
func createStateHintObfuscator(state *channeldb.OpenChannel) [StateHintSize]byte {
3✔
645
        if state.IsInitiator {
6✔
646
                return DeriveStateHintObfuscator(
3✔
647
                        state.LocalChanCfg.PaymentBasePoint.PubKey,
3✔
648
                        state.RemoteChanCfg.PaymentBasePoint.PubKey,
3✔
649
                )
3✔
650
        }
3✔
651

652
        return DeriveStateHintObfuscator(
3✔
653
                state.RemoteChanCfg.PaymentBasePoint.PubKey,
3✔
654
                state.LocalChanCfg.PaymentBasePoint.PubKey,
3✔
655
        )
3✔
656
}
657

658
// unsignedCommitmentTx is the final commitment created from evaluating an HTLC
659
// view at a given height, along with some meta data.
660
type unsignedCommitmentTx struct {
661
        // txn is the final, unsigned commitment transaction for this view.
662
        txn *wire.MsgTx
663

664
        // fee is the total fee of the commitment transaction.
665
        fee btcutil.Amount
666

667
        // ourBalance is our balance on this commitment *after* subtracting
668
        // commitment fees and anchor outputs. This can be different than the
669
        // balances before creating the commitment transaction as one party must
670
        // pay the commitment fee.
671
        ourBalance lnwire.MilliSatoshi
672

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

679
        // cltvs is a sorted list of CLTV deltas for each HTLC on the commitment
680
        // transaction. Any non-htlc outputs will have a CLTV delay of zero.
681
        cltvs []uint32
682
}
683

684
// createUnsignedCommitmentTx generates the unsigned commitment transaction for
685
// a commitment view and returns it as part of the unsignedCommitmentTx. The
686
// passed in balances should be balances *before* subtracting any commitment
687
// fees, but after anchor outputs.
688
func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance,
689
        theirBalance lnwire.MilliSatoshi, isOurs bool,
690
        feePerKw chainfee.SatPerKWeight, height uint64,
691
        filteredHTLCView *htlcView,
692
        keyRing *CommitmentKeyRing) (*unsignedCommitmentTx, error) {
3✔
693

3✔
694
        dustLimit := cb.chanState.LocalChanCfg.DustLimit
3✔
695
        if !isOurs {
6✔
696
                dustLimit = cb.chanState.RemoteChanCfg.DustLimit
3✔
697
        }
3✔
698

699
        numHTLCs := int64(0)
3✔
700
        for _, htlc := range filteredHTLCView.ourUpdates {
6✔
701
                if HtlcIsDust(
3✔
702
                        cb.chanState.ChanType, false, isOurs, feePerKw,
3✔
703
                        htlc.Amount.ToSatoshis(), dustLimit,
3✔
704
                ) {
6✔
705

3✔
706
                        continue
3✔
707
                }
708

709
                numHTLCs++
3✔
710
        }
711
        for _, htlc := range filteredHTLCView.theirUpdates {
6✔
712
                if HtlcIsDust(
3✔
713
                        cb.chanState.ChanType, true, isOurs, feePerKw,
3✔
714
                        htlc.Amount.ToSatoshis(), dustLimit,
3✔
715
                ) {
6✔
716

3✔
717
                        continue
3✔
718
                }
719

720
                numHTLCs++
3✔
721
        }
722

723
        // Next, we'll calculate the fee for the commitment transaction based
724
        // on its total weight. Once we have the total weight, we'll multiply
725
        // by the current fee-per-kw, then divide by 1000 to get the proper
726
        // fee.
727
        totalCommitWeight := CommitWeight(cb.chanState.ChanType) +
3✔
728
                lntypes.WeightUnit(input.HTLCWeight*numHTLCs)
3✔
729

3✔
730
        // With the weight known, we can now calculate the commitment fee,
3✔
731
        // ensuring that we account for any dust outputs trimmed above.
3✔
732
        commitFee := feePerKw.FeeForWeight(totalCommitWeight)
3✔
733
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
3✔
734

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

743
        case cb.chanState.IsInitiator:
3✔
744
                ourBalance -= commitFeeMSat
3✔
745

746
        case !cb.chanState.IsInitiator && commitFee > theirBalance.ToSatoshis():
×
747
                theirBalance = 0
×
748

749
        case !cb.chanState.IsInitiator:
3✔
750
                theirBalance -= commitFeeMSat
3✔
751
        }
752

753
        var (
3✔
754
                commitTx *wire.MsgTx
3✔
755
                err      error
3✔
756
        )
3✔
757

3✔
758
        // Depending on whether the transaction is ours or not, we call
3✔
759
        // CreateCommitTx with parameters matching the perspective, to generate
3✔
760
        // a new commitment transaction with all the latest unsettled/un-timed
3✔
761
        // out HTLCs.
3✔
762
        var leaseExpiry uint32
3✔
763
        if cb.chanState.ChanType.HasLeaseExpiration() {
6✔
764
                leaseExpiry = cb.chanState.ThawHeight
3✔
765
        }
3✔
766
        if isOurs {
6✔
767
                commitTx, err = CreateCommitTx(
3✔
768
                        cb.chanState.ChanType, fundingTxIn(cb.chanState), keyRing,
3✔
769
                        &cb.chanState.LocalChanCfg, &cb.chanState.RemoteChanCfg,
3✔
770
                        ourBalance.ToSatoshis(), theirBalance.ToSatoshis(),
3✔
771
                        numHTLCs, cb.chanState.IsInitiator, leaseExpiry,
3✔
772
                )
3✔
773
        } else {
6✔
774
                commitTx, err = CreateCommitTx(
3✔
775
                        cb.chanState.ChanType, fundingTxIn(cb.chanState), keyRing,
3✔
776
                        &cb.chanState.RemoteChanCfg, &cb.chanState.LocalChanCfg,
3✔
777
                        theirBalance.ToSatoshis(), ourBalance.ToSatoshis(),
3✔
778
                        numHTLCs, !cb.chanState.IsInitiator, leaseExpiry,
3✔
779
                )
3✔
780
        }
3✔
781
        if err != nil {
3✔
782
                return nil, err
×
783
        }
×
784

785
        // We'll now add all the HTLC outputs to the commitment transaction.
786
        // Each output includes an off-chain 2-of-2 covenant clause, so we'll
787
        // need the objective local/remote keys for this particular commitment
788
        // as well. For any non-dust HTLCs that are manifested on the commitment
789
        // transaction, we'll also record its CLTV which is required to sort the
790
        // commitment transaction below. The slice is initially sized to the
791
        // number of existing outputs, since any outputs already added are
792
        // commitment outputs and should correspond to zero values for the
793
        // purposes of sorting.
794
        cltvs := make([]uint32, len(commitTx.TxOut))
3✔
795
        for _, htlc := range filteredHTLCView.ourUpdates {
6✔
796
                if HtlcIsDust(
3✔
797
                        cb.chanState.ChanType, false, isOurs, feePerKw,
3✔
798
                        htlc.Amount.ToSatoshis(), dustLimit,
3✔
799
                ) {
6✔
800

3✔
801
                        continue
3✔
802
                }
803

804
                err := addHTLC(
3✔
805
                        commitTx, isOurs, false, htlc, keyRing,
3✔
806
                        cb.chanState.ChanType,
3✔
807
                )
3✔
808
                if err != nil {
3✔
809
                        return nil, err
×
810
                }
×
811
                cltvs = append(cltvs, htlc.Timeout) // nolint:makezero
3✔
812
        }
813
        for _, htlc := range filteredHTLCView.theirUpdates {
6✔
814
                if HtlcIsDust(
3✔
815
                        cb.chanState.ChanType, true, isOurs, feePerKw,
3✔
816
                        htlc.Amount.ToSatoshis(), dustLimit,
3✔
817
                ) {
6✔
818

3✔
819
                        continue
3✔
820
                }
821

822
                err := addHTLC(
3✔
823
                        commitTx, isOurs, true, htlc, keyRing,
3✔
824
                        cb.chanState.ChanType,
3✔
825
                )
3✔
826
                if err != nil {
3✔
827
                        return nil, err
×
828
                }
×
829
                cltvs = append(cltvs, htlc.Timeout) // nolint:makezero
3✔
830
        }
831

832
        // Set the state hint of the commitment transaction to facilitate
833
        // quickly recovering the necessary penalty state in the case of an
834
        // uncooperative broadcast.
835
        err = SetStateNumHint(commitTx, height, cb.obfuscator)
3✔
836
        if err != nil {
3✔
837
                return nil, err
×
838
        }
×
839

840
        // Sort the transactions according to the agreed upon canonical
841
        // ordering. This lets us skip sending the entire transaction over,
842
        // instead we'll just send signatures.
843
        InPlaceCommitSort(commitTx, cltvs)
3✔
844

3✔
845
        // Next, we'll ensure that we don't accidentally create a commitment
3✔
846
        // transaction which would be invalid by consensus.
3✔
847
        uTx := btcutil.NewTx(commitTx)
3✔
848
        if err := blockchain.CheckTransactionSanity(uTx); err != nil {
3✔
849
                return nil, err
×
850
        }
×
851

852
        // Finally, we'll assert that were not attempting to draw more out of
853
        // the channel that was originally placed within it.
854
        var totalOut btcutil.Amount
3✔
855
        for _, txOut := range commitTx.TxOut {
6✔
856
                totalOut += btcutil.Amount(txOut.Value)
3✔
857
        }
3✔
858
        if totalOut+commitFee > cb.chanState.Capacity {
3✔
859
                return nil, fmt.Errorf("height=%v, for ChannelPoint(%v) "+
×
860
                        "attempts to consume %v while channel capacity is %v",
×
861
                        height, cb.chanState.FundingOutpoint,
×
862
                        totalOut+commitFee, cb.chanState.Capacity)
×
863
        }
×
864

865
        return &unsignedCommitmentTx{
3✔
866
                txn:          commitTx,
3✔
867
                fee:          commitFee,
3✔
868
                ourBalance:   ourBalance,
3✔
869
                theirBalance: theirBalance,
3✔
870
                cltvs:        cltvs,
3✔
871
        }, nil
3✔
872
}
873

874
// CreateCommitTx creates a commitment transaction, spending from specified
875
// funding output. The commitment transaction contains two outputs: one local
876
// output paying to the "owner" of the commitment transaction which can be
877
// spent after a relative block delay or revocation event, and a remote output
878
// paying the counterparty within the channel, which can be spent immediately
879
// or after a delay depending on the commitment type. The `initiator` argument
880
// should correspond to the owner of the commitment transaction we are creating.
881
func CreateCommitTx(chanType channeldb.ChannelType,
882
        fundingOutput wire.TxIn, keyRing *CommitmentKeyRing,
883
        localChanCfg, remoteChanCfg *channeldb.ChannelConfig,
884
        amountToLocal, amountToRemote btcutil.Amount,
885
        numHTLCs int64, initiator bool, leaseExpiry uint32) (*wire.MsgTx, error) {
3✔
886

3✔
887
        // First, we create the script for the delayed "pay-to-self" output.
3✔
888
        // This output has 2 main redemption clauses: either we can redeem the
3✔
889
        // output after a relative block delay, or the remote node can claim
3✔
890
        // the funds with the revocation key if we broadcast a revoked
3✔
891
        // commitment transaction.
3✔
892
        toLocalScript, err := CommitScriptToSelf(
3✔
893
                chanType, initiator, keyRing.ToLocalKey, keyRing.RevocationKey,
3✔
894
                uint32(localChanCfg.CsvDelay), leaseExpiry,
3✔
895
        )
3✔
896
        if err != nil {
3✔
897
                return nil, err
×
898
        }
×
899

900
        // Next, we create the script paying to the remote.
901
        toRemoteScript, _, err := CommitScriptToRemote(
3✔
902
                chanType, initiator, keyRing.ToRemoteKey, leaseExpiry,
3✔
903
        )
3✔
904
        if err != nil {
3✔
905
                return nil, err
×
906
        }
×
907

908
        // Now that both output scripts have been created, we can finally create
909
        // the transaction itself. We use a transaction version of 2 since CSV
910
        // will fail unless the tx version is >= 2.
911
        commitTx := wire.NewMsgTx(2)
3✔
912
        commitTx.AddTxIn(&fundingOutput)
3✔
913

3✔
914
        // Avoid creating dust outputs within the commitment transaction.
3✔
915
        localOutput := amountToLocal >= localChanCfg.DustLimit
3✔
916
        if localOutput {
6✔
917
                commitTx.AddTxOut(&wire.TxOut{
3✔
918
                        PkScript: toLocalScript.PkScript(),
3✔
919
                        Value:    int64(amountToLocal),
3✔
920
                })
3✔
921
        }
3✔
922

923
        remoteOutput := amountToRemote >= localChanCfg.DustLimit
3✔
924
        if remoteOutput {
6✔
925
                commitTx.AddTxOut(&wire.TxOut{
3✔
926
                        PkScript: toRemoteScript.PkScript(),
3✔
927
                        Value:    int64(amountToRemote),
3✔
928
                })
3✔
929
        }
3✔
930

931
        // If this channel type has anchors, we'll also add those.
932
        if chanType.HasAnchors() {
6✔
933
                localAnchor, remoteAnchor, err := CommitScriptAnchors(
3✔
934
                        chanType, localChanCfg, remoteChanCfg, keyRing,
3✔
935
                )
3✔
936
                if err != nil {
3✔
937
                        return nil, err
×
938
                }
×
939

940
                // Add local anchor output only if we have a commitment output
941
                // or there are HTLCs.
942
                if localOutput || numHTLCs > 0 {
6✔
943
                        commitTx.AddTxOut(&wire.TxOut{
3✔
944
                                PkScript: localAnchor.PkScript(),
3✔
945
                                Value:    int64(anchorSize),
3✔
946
                        })
3✔
947
                }
3✔
948

949
                // Add anchor output to remote only if they have a commitment
950
                // output or there are HTLCs.
951
                if remoteOutput || numHTLCs > 0 {
6✔
952
                        commitTx.AddTxOut(&wire.TxOut{
3✔
953
                                PkScript: remoteAnchor.PkScript(),
3✔
954
                                Value:    int64(anchorSize),
3✔
955
                        })
3✔
956
                }
3✔
957
        }
958

959
        return commitTx, nil
3✔
960
}
961

962
// CoopCloseBalance returns the final balances that should be used to create
963
// the cooperative close tx, given the channel type and transaction fee.
964
func CoopCloseBalance(chanType channeldb.ChannelType, isInitiator bool,
965
        coopCloseFee btcutil.Amount, localCommit channeldb.ChannelCommitment) (
966
        btcutil.Amount, btcutil.Amount, error) {
3✔
967

3✔
968
        // Get both parties' balances from the latest commitment.
3✔
969
        ourBalance := localCommit.LocalBalance.ToSatoshis()
3✔
970
        theirBalance := localCommit.RemoteBalance.ToSatoshis()
3✔
971

3✔
972
        // We'll make sure we account for the complete balance by adding the
3✔
973
        // current dangling commitment fee to the balance of the initiator.
3✔
974
        initiatorDelta := localCommit.CommitFee
3✔
975

3✔
976
        // Since the initiator's balance also is stored after subtracting the
3✔
977
        // anchor values, add that back in case this was an anchor commitment.
3✔
978
        if chanType.HasAnchors() {
6✔
979
                initiatorDelta += 2 * anchorSize
3✔
980
        }
3✔
981

982
        // The initiator will pay the full coop close fee, subtract that value
983
        // from their balance.
984
        initiatorDelta -= coopCloseFee
3✔
985

3✔
986
        if isInitiator {
6✔
987
                ourBalance += initiatorDelta
3✔
988
        } else {
6✔
989
                theirBalance += initiatorDelta
3✔
990
        }
3✔
991

992
        // During fee negotiation it should always be verified that the
993
        // initiator can pay the proposed fee, but we do a sanity check just to
994
        // be sure here.
995
        if ourBalance < 0 || theirBalance < 0 {
3✔
996
                return 0, 0, fmt.Errorf("initiator cannot afford proposed " +
×
997
                        "coop close fee")
×
998
        }
×
999

1000
        return ourBalance, theirBalance, nil
3✔
1001
}
1002

1003
// genSegwitV0HtlcScript generates the HTLC scripts for a normal segwit v0
1004
// channel.
1005
func genSegwitV0HtlcScript(chanType channeldb.ChannelType,
1006
        isIncoming, ourCommit bool, timeout uint32, rHash [32]byte,
1007
        keyRing *CommitmentKeyRing) (*WitnessScriptDesc, error) {
3✔
1008

3✔
1009
        var (
3✔
1010
                witnessScript []byte
3✔
1011
                err           error
3✔
1012
        )
3✔
1013

3✔
1014
        // Choose scripts based on channel type.
3✔
1015
        confirmedHtlcSpends := false
3✔
1016
        if chanType.HasAnchors() {
6✔
1017
                confirmedHtlcSpends = true
3✔
1018
        }
3✔
1019

1020
        // Generate the proper redeem scripts for the HTLC output modified by
1021
        // two-bits denoting if this is an incoming HTLC, and if the HTLC is
1022
        // being applied to their commitment transaction or ours.
1023
        switch {
3✔
1024
        // The HTLC is paying to us, and being applied to our commitment
1025
        // transaction. So we need to use the receiver's version of the HTLC
1026
        // script.
1027
        case isIncoming && ourCommit:
3✔
1028
                witnessScript, err = input.ReceiverHTLCScript(
3✔
1029
                        timeout, keyRing.RemoteHtlcKey, keyRing.LocalHtlcKey,
3✔
1030
                        keyRing.RevocationKey, rHash[:], confirmedHtlcSpends,
3✔
1031
                )
3✔
1032

1033
        // We're being paid via an HTLC by the remote party, and the HTLC is
1034
        // being added to their commitment transaction, so we use the sender's
1035
        // version of the HTLC script.
1036
        case isIncoming && !ourCommit:
3✔
1037
                witnessScript, err = input.SenderHTLCScript(
3✔
1038
                        keyRing.RemoteHtlcKey, keyRing.LocalHtlcKey,
3✔
1039
                        keyRing.RevocationKey, rHash[:], confirmedHtlcSpends,
3✔
1040
                )
3✔
1041

1042
        // We're sending an HTLC which is being added to our commitment
1043
        // transaction. Therefore, we need to use the sender's version of the
1044
        // HTLC script.
1045
        case !isIncoming && ourCommit:
3✔
1046
                witnessScript, err = input.SenderHTLCScript(
3✔
1047
                        keyRing.LocalHtlcKey, keyRing.RemoteHtlcKey,
3✔
1048
                        keyRing.RevocationKey, rHash[:], confirmedHtlcSpends,
3✔
1049
                )
3✔
1050

1051
        // Finally, we're paying the remote party via an HTLC, which is being
1052
        // added to their commitment transaction. Therefore, we use the
1053
        // receiver's version of the HTLC script.
1054
        case !isIncoming && !ourCommit:
3✔
1055
                witnessScript, err = input.ReceiverHTLCScript(
3✔
1056
                        timeout, keyRing.LocalHtlcKey, keyRing.RemoteHtlcKey,
3✔
1057
                        keyRing.RevocationKey, rHash[:], confirmedHtlcSpends,
3✔
1058
                )
3✔
1059
        }
1060
        if err != nil {
3✔
1061
                return nil, err
×
1062
        }
×
1063

1064
        // Now that we have the redeem scripts, create the P2WSH public key
1065
        // script for the output itself.
1066
        htlcP2WSH, err := input.WitnessScriptHash(witnessScript)
3✔
1067
        if err != nil {
3✔
1068
                return nil, err
×
1069
        }
×
1070

1071
        return &WitnessScriptDesc{
3✔
1072
                OutputScript:  htlcP2WSH,
3✔
1073
                WitnessScript: witnessScript,
3✔
1074
        }, nil
3✔
1075
}
1076

1077
// genTaprootHtlcScript generates the HTLC scripts for a taproot+musig2
1078
// channel.
1079
func genTaprootHtlcScript(isIncoming, ourCommit bool, timeout uint32,
1080
        rHash [32]byte,
1081
        keyRing *CommitmentKeyRing) (*input.HtlcScriptTree, error) {
3✔
1082

3✔
1083
        var (
3✔
1084
                htlcScriptTree *input.HtlcScriptTree
3✔
1085
                err            error
3✔
1086
        )
3✔
1087

3✔
1088
        // Generate the proper redeem scripts for the HTLC output modified by
3✔
1089
        // two-bits denoting if this is an incoming HTLC, and if the HTLC is
3✔
1090
        // being applied to their commitment transaction or ours.
3✔
1091
        switch {
3✔
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 HTLC the
1094
        // script.
1095
        case isIncoming && ourCommit:
3✔
1096
                htlcScriptTree, err = input.ReceiverHTLCScriptTaproot(
3✔
1097
                        timeout, keyRing.RemoteHtlcKey, keyRing.LocalHtlcKey,
3✔
1098
                        keyRing.RevocationKey, rHash[:], ourCommit,
3✔
1099
                )
3✔
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 && !ourCommit:
3✔
1105
                htlcScriptTree, err = input.SenderHTLCScriptTaproot(
3✔
1106
                        keyRing.RemoteHtlcKey, keyRing.LocalHtlcKey,
3✔
1107
                        keyRing.RevocationKey, rHash[:], ourCommit,
3✔
1108
                )
3✔
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 && ourCommit:
3✔
1114
                htlcScriptTree, err = input.SenderHTLCScriptTaproot(
3✔
1115
                        keyRing.LocalHtlcKey, keyRing.RemoteHtlcKey,
3✔
1116
                        keyRing.RevocationKey, rHash[:], ourCommit,
3✔
1117
                )
3✔
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 && !ourCommit:
3✔
1123
                htlcScriptTree, err = input.ReceiverHTLCScriptTaproot(
3✔
1124
                        timeout, keyRing.LocalHtlcKey, keyRing.RemoteHtlcKey,
3✔
1125
                        keyRing.RevocationKey, rHash[:], ourCommit,
3✔
1126
                )
3✔
1127
        }
1128

1129
        return htlcScriptTree, err
3✔
1130
}
1131

1132
// genHtlcScript generates the proper P2WSH public key scripts for the HTLC
1133
// output modified by two-bits denoting if this is an incoming HTLC, and if the
1134
// HTLC is being applied to their commitment transaction or ours. A script
1135
// multiplexer for the various spending paths is returned. The script path that
1136
// we need to sign for the remote party (2nd level HTLCs) is also returned
1137
// along side the multiplexer.
1138
func genHtlcScript(chanType channeldb.ChannelType, isIncoming, ourCommit bool,
1139
        timeout uint32, rHash [32]byte, keyRing *CommitmentKeyRing,
1140
) (input.ScriptDescriptor, error) {
3✔
1141

3✔
1142
        if !chanType.IsTaproot() {
6✔
1143
                return genSegwitV0HtlcScript(
3✔
1144
                        chanType, isIncoming, ourCommit, timeout, rHash,
3✔
1145
                        keyRing,
3✔
1146
                )
3✔
1147
        }
3✔
1148

1149
        return genTaprootHtlcScript(
3✔
1150
                isIncoming, ourCommit, timeout, rHash, keyRing,
3✔
1151
        )
3✔
1152
}
1153

1154
// addHTLC adds a new HTLC to the passed commitment transaction. One of four
1155
// full scripts will be generated for the HTLC output depending on if the HTLC
1156
// is incoming and if it's being applied to our commitment transaction or that
1157
// of the remote node's. Additionally, in order to be able to efficiently
1158
// locate the added HTLC on the commitment transaction from the
1159
// PaymentDescriptor that generated it, the generated script is stored within
1160
// the descriptor itself.
1161
func addHTLC(commitTx *wire.MsgTx, ourCommit bool,
1162
        isIncoming bool, paymentDesc *PaymentDescriptor,
1163
        keyRing *CommitmentKeyRing, chanType channeldb.ChannelType) error {
3✔
1164

3✔
1165
        timeout := paymentDesc.Timeout
3✔
1166
        rHash := paymentDesc.RHash
3✔
1167

3✔
1168
        scriptInfo, err := genHtlcScript(
3✔
1169
                chanType, isIncoming, ourCommit, timeout, rHash, keyRing,
3✔
1170
        )
3✔
1171
        if err != nil {
3✔
1172
                return err
×
1173
        }
×
1174

1175
        pkScript := scriptInfo.PkScript()
3✔
1176

3✔
1177
        // Add the new HTLC outputs to the respective commitment transactions.
3✔
1178
        amountPending := int64(paymentDesc.Amount.ToSatoshis())
3✔
1179
        commitTx.AddTxOut(wire.NewTxOut(amountPending, pkScript))
3✔
1180

3✔
1181
        // Store the pkScript of this particular PaymentDescriptor so we can
3✔
1182
        // quickly locate it within the commitment transaction later.
3✔
1183
        if ourCommit {
6✔
1184
                paymentDesc.ourPkScript = pkScript
3✔
1185

3✔
1186
                paymentDesc.ourWitnessScript = scriptInfo.WitnessScriptToSign()
3✔
1187
        } else {
6✔
1188
                paymentDesc.theirPkScript = pkScript
3✔
1189

3✔
1190
                //nolint:lll
3✔
1191
                paymentDesc.theirWitnessScript = scriptInfo.WitnessScriptToSign()
3✔
1192
        }
3✔
1193

1194
        return nil
3✔
1195
}
1196

1197
// findOutputIndexesFromRemote finds the index of our and their outputs from
1198
// the remote commitment transaction. It derives the key ring to compute the
1199
// output scripts and compares them against the outputs inside the commitment
1200
// to find the match.
1201
func findOutputIndexesFromRemote(revocationPreimage *chainhash.Hash,
1202
        chanState *channeldb.OpenChannel) (uint32, uint32, error) {
3✔
1203

3✔
1204
        // Init the output indexes as empty.
3✔
1205
        ourIndex := uint32(channeldb.OutputIndexEmpty)
3✔
1206
        theirIndex := uint32(channeldb.OutputIndexEmpty)
3✔
1207

3✔
1208
        chanCommit := chanState.RemoteCommitment
3✔
1209
        _, commitmentPoint := btcec.PrivKeyFromBytes(revocationPreimage[:])
3✔
1210

3✔
1211
        // With the commitment point generated, we can now derive the king ring
3✔
1212
        // which will be used to generate the output scripts.
3✔
1213
        keyRing := DeriveCommitmentKeys(
3✔
1214
                commitmentPoint, false, chanState.ChanType,
3✔
1215
                &chanState.LocalChanCfg, &chanState.RemoteChanCfg,
3✔
1216
        )
3✔
1217

3✔
1218
        // Since it's remote commitment chain, we'd used the mirrored values.
3✔
1219
        //
3✔
1220
        // We use the remote's channel config for the csv delay.
3✔
1221
        theirDelay := uint32(chanState.RemoteChanCfg.CsvDelay)
3✔
1222

3✔
1223
        // If we are the initiator of this channel, then it's be false from the
3✔
1224
        // remote's PoV.
3✔
1225
        isRemoteInitiator := !chanState.IsInitiator
3✔
1226

3✔
1227
        var leaseExpiry uint32
3✔
1228
        if chanState.ChanType.HasLeaseExpiration() {
6✔
1229
                leaseExpiry = chanState.ThawHeight
3✔
1230
        }
3✔
1231

1232
        // Map the scripts from our PoV. When facing a local commitment, the to
1233
        // local output belongs to us and the to remote output belongs to them.
1234
        // When facing a remote commitment, the to local output belongs to them
1235
        // and the to remote output belongs to us.
1236

1237
        // Compute the to local script. From our PoV, when facing a remote
1238
        // commitment, the to local output belongs to them.
1239
        theirScript, err := CommitScriptToSelf(
3✔
1240
                chanState.ChanType, isRemoteInitiator, keyRing.ToLocalKey,
3✔
1241
                keyRing.RevocationKey, theirDelay, leaseExpiry,
3✔
1242
        )
3✔
1243
        if err != nil {
3✔
1244
                return ourIndex, theirIndex, err
×
1245
        }
×
1246

1247
        // Compute the to remote script. From our PoV, when facing a remote
1248
        // commitment, the to remote output belongs to us.
1249
        ourScript, _, err := CommitScriptToRemote(
3✔
1250
                chanState.ChanType, isRemoteInitiator, keyRing.ToRemoteKey,
3✔
1251
                leaseExpiry,
3✔
1252
        )
3✔
1253
        if err != nil {
3✔
1254
                return ourIndex, theirIndex, err
×
1255
        }
×
1256

1257
        // Now compare the scripts to find our/their output index.
1258
        for i, txOut := range chanCommit.CommitTx.TxOut {
6✔
1259
                switch {
3✔
1260
                case bytes.Equal(txOut.PkScript, ourScript.PkScript()):
3✔
1261
                        ourIndex = uint32(i)
3✔
1262
                case bytes.Equal(txOut.PkScript, theirScript.PkScript()):
3✔
1263
                        theirIndex = uint32(i)
3✔
1264
                }
1265
        }
1266

1267
        return ourIndex, theirIndex, nil
3✔
1268
}
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