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

lightningnetwork / lnd / 10524623857

23 Aug 2024 11:04AM UTC coverage: 58.665% (-0.1%) from 58.789%
10524623857

push

github

web-flow
Merge pull request #9025 from lightningnetwork/extract-from-staging-branch

[custom channels]: extract some independent commits from mega staging branch

167 of 677 new or added lines in 17 files covered. (24.67%)

553 existing lines in 23 files now uncovered.

126628 of 215851 relevant lines covered (58.66%)

28348.7 hits per line

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

86.88
/input/script_utils.go
1
package input
2

3
import (
4
        "bytes"
5
        "crypto/sha256"
6
        "encoding/hex"
7
        "fmt"
8

9
        "github.com/btcsuite/btcd/btcec/v2"
10
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
11
        "github.com/btcsuite/btcd/btcec/v2/schnorr"
12
        "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
13
        "github.com/btcsuite/btcd/btcutil"
14
        "github.com/btcsuite/btcd/txscript"
15
        "github.com/btcsuite/btcd/wire"
16
        "github.com/lightningnetwork/lnd/lntypes"
17
        "github.com/lightningnetwork/lnd/lnutils"
18
        "golang.org/x/crypto/ripemd160"
19
)
20

21
var (
22
        // TODO(roasbeef): remove these and use the one's defined in txscript
23
        // within testnet-L.
24

25
        // SequenceLockTimeSeconds is the 22nd bit which indicates the lock
26
        // time is in seconds.
27
        SequenceLockTimeSeconds = uint32(1 << 22)
28
)
29

30
// mustParsePubKey parses a hex encoded public key string into a public key and
31
// panic if parsing fails.
32
func mustParsePubKey(pubStr string) btcec.PublicKey {
73✔
33
        pubBytes, err := hex.DecodeString(pubStr)
73✔
34
        if err != nil {
73✔
35
                panic(err)
×
36
        }
37

38
        pub, err := btcec.ParsePubKey(pubBytes)
73✔
39
        if err != nil {
73✔
40
                panic(err)
×
41
        }
42

43
        return *pub
73✔
44
}
45

46
// TaprootNUMSHex is the hex encoded version of the taproot NUMs key.
47
const TaprootNUMSHex = "02dca094751109d0bd055d03565874e8276dd53e926b44e3bd1bb" +
48
        "6bf4bc130a279"
49

50
var (
51
        // TaprootNUMSKey is a NUMS key (nothing up my sleeves number) that has
52
        // no known private key. This was generated using the following script:
53
        // https://github.com/lightninglabs/lightning-node-connect/tree/
54
        // master/mailbox/numsgen, with the seed phrase "Lightning Simple
55
        // Taproot".
56
        TaprootNUMSKey = mustParsePubKey(TaprootNUMSHex)
57
)
58

59
// Signature is an interface for objects that can populate signatures during
60
// witness construction.
61
type Signature interface {
62
        // Serialize returns a DER-encoded ECDSA signature.
63
        Serialize() []byte
64

65
        // Verify return true if the ECDSA signature is valid for the passed
66
        // message digest under the provided public key.
67
        Verify([]byte, *btcec.PublicKey) bool
68
}
69

70
// ParseSignature parses a raw signature into an input.Signature instance. This
71
// routine supports parsing normal ECDSA DER encoded signatures, as well as
72
// schnorr signatures.
73
func ParseSignature(rawSig []byte) (Signature, error) {
103✔
74
        if len(rawSig) == schnorr.SignatureSize {
110✔
75
                return schnorr.ParseSignature(rawSig)
7✔
76
        }
7✔
77

78
        return ecdsa.ParseDERSignature(rawSig)
99✔
79
}
80

81
// WitnessScriptHash generates a pay-to-witness-script-hash public key script
82
// paying to a version 0 witness program paying to the passed redeem script.
83
func WitnessScriptHash(witnessScript []byte) ([]byte, error) {
965,802✔
84
        bldr := txscript.NewScriptBuilder(
965,802✔
85
                txscript.WithScriptAllocSize(P2WSHSize),
965,802✔
86
        )
965,802✔
87

965,802✔
88
        bldr.AddOp(txscript.OP_0)
965,802✔
89
        scriptHash := sha256.Sum256(witnessScript)
965,802✔
90
        bldr.AddData(scriptHash[:])
965,802✔
91
        return bldr.Script()
965,802✔
92
}
965,802✔
93

94
// WitnessPubKeyHash generates a pay-to-witness-pubkey-hash public key script
95
// paying to a version 0 witness program containing the passed serialized
96
// public key.
97
func WitnessPubKeyHash(pubkey []byte) ([]byte, error) {
36✔
98
        bldr := txscript.NewScriptBuilder(
36✔
99
                txscript.WithScriptAllocSize(P2WPKHSize),
36✔
100
        )
36✔
101

36✔
102
        bldr.AddOp(txscript.OP_0)
36✔
103
        pkhash := btcutil.Hash160(pubkey)
36✔
104
        bldr.AddData(pkhash)
36✔
105
        return bldr.Script()
36✔
106
}
36✔
107

108
// GenerateP2SH generates a pay-to-script-hash public key script paying to the
109
// passed redeem script.
110
func GenerateP2SH(script []byte) ([]byte, error) {
6✔
111
        bldr := txscript.NewScriptBuilder(
6✔
112
                txscript.WithScriptAllocSize(NestedP2WPKHSize),
6✔
113
        )
6✔
114

6✔
115
        bldr.AddOp(txscript.OP_HASH160)
6✔
116
        scripthash := btcutil.Hash160(script)
6✔
117
        bldr.AddData(scripthash)
6✔
118
        bldr.AddOp(txscript.OP_EQUAL)
6✔
119
        return bldr.Script()
6✔
120
}
6✔
121

122
// GenerateP2PKH generates a pay-to-public-key-hash public key script paying to
123
// the passed serialized public key.
124
func GenerateP2PKH(pubkey []byte) ([]byte, error) {
5✔
125
        bldr := txscript.NewScriptBuilder(
5✔
126
                txscript.WithScriptAllocSize(P2PKHSize),
5✔
127
        )
5✔
128

5✔
129
        bldr.AddOp(txscript.OP_DUP)
5✔
130
        bldr.AddOp(txscript.OP_HASH160)
5✔
131
        pkhash := btcutil.Hash160(pubkey)
5✔
132
        bldr.AddData(pkhash)
5✔
133
        bldr.AddOp(txscript.OP_EQUALVERIFY)
5✔
134
        bldr.AddOp(txscript.OP_CHECKSIG)
5✔
135
        return bldr.Script()
5✔
136
}
5✔
137

138
// GenerateUnknownWitness generates the maximum-sized witness public key script
139
// consisting of a version push and a 40-byte data push.
140
func GenerateUnknownWitness() ([]byte, error) {
486✔
141
        bldr := txscript.NewScriptBuilder()
486✔
142

486✔
143
        bldr.AddOp(txscript.OP_0)
486✔
144
        witnessScript := make([]byte, 40)
486✔
145
        bldr.AddData(witnessScript)
486✔
146
        return bldr.Script()
486✔
147
}
486✔
148

149
// GenMultiSigScript generates the non-p2sh'd multisig script for 2 of 2
150
// pubkeys.
151
func GenMultiSigScript(aPub, bPub []byte) ([]byte, error) {
1,193✔
152
        if len(aPub) != 33 || len(bPub) != 33 {
1,193✔
153
                return nil, fmt.Errorf("pubkey size error: compressed " +
×
154
                        "pubkeys only")
×
155
        }
×
156

157
        // Swap to sort pubkeys if needed. Keys are sorted in lexicographical
158
        // order. The signatures within the scriptSig must also adhere to the
159
        // order, ensuring that the signatures for each public key appears in
160
        // the proper order on the stack.
161
        if bytes.Compare(aPub, bPub) == 1 {
1,673✔
162
                aPub, bPub = bPub, aPub
480✔
163
        }
480✔
164

165
        bldr := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
1,193✔
166
                MultiSigSize,
1,193✔
167
        ))
1,193✔
168
        bldr.AddOp(txscript.OP_2)
1,193✔
169
        bldr.AddData(aPub) // Add both pubkeys (sorted).
1,193✔
170
        bldr.AddData(bPub)
1,193✔
171
        bldr.AddOp(txscript.OP_2)
1,193✔
172
        bldr.AddOp(txscript.OP_CHECKMULTISIG)
1,193✔
173
        return bldr.Script()
1,193✔
174
}
175

176
// GenFundingPkScript creates a redeem script, and its matching p2wsh
177
// output for the funding transaction.
178
func GenFundingPkScript(aPub, bPub []byte, amt int64) ([]byte, *wire.TxOut, error) {
260✔
179
        // As a sanity check, ensure that the passed amount is above zero.
260✔
180
        if amt <= 0 {
260✔
181
                return nil, nil, fmt.Errorf("can't create FundTx script with " +
×
182
                        "zero, or negative coins")
×
183
        }
×
184

185
        // First, create the 2-of-2 multi-sig script itself.
186
        witnessScript, err := GenMultiSigScript(aPub, bPub)
260✔
187
        if err != nil {
260✔
188
                return nil, nil, err
×
189
        }
×
190

191
        // With the 2-of-2 script in had, generate a p2wsh script which pays
192
        // to the funding script.
193
        pkScript, err := WitnessScriptHash(witnessScript)
260✔
194
        if err != nil {
260✔
195
                return nil, nil, err
×
196
        }
×
197

198
        return witnessScript, wire.NewTxOut(amt, pkScript), nil
260✔
199
}
200

201
// GenTaprootFundingScript constructs the taproot-native funding output that
202
// uses musig2 to create a single aggregated key to anchor the channel.
203
func GenTaprootFundingScript(aPub, bPub *btcec.PublicKey,
204
        amt int64) ([]byte, *wire.TxOut, error) {
58✔
205

58✔
206
        // Similar to the existing p2wsh funding script, we'll always make sure
58✔
207
        // we sort the keys before any major operations. In order to ensure
58✔
208
        // that there's no other way this output can be spent, we'll use a BIP
58✔
209
        // 86 tweak here during aggregation.
58✔
210
        //
58✔
211
        // TODO(roasbeef): revisit if BIP 86 is needed here?
58✔
212
        combinedKey, _, _, err := musig2.AggregateKeys(
58✔
213
                []*btcec.PublicKey{aPub, bPub}, true,
58✔
214
                musig2.WithBIP86KeyTweak(),
58✔
215
        )
58✔
216
        if err != nil {
58✔
217
                return nil, nil, fmt.Errorf("unable to combine keys: %w", err)
×
218
        }
×
219

220
        // Now that we have the combined key, we can create a taproot pkScript
221
        // from this, and then make the txout given the amount.
222
        pkScript, err := PayToTaprootScript(combinedKey.FinalKey)
58✔
223
        if err != nil {
58✔
224
                return nil, nil, fmt.Errorf("unable to make taproot "+
×
225
                        "pkscript: %w", err)
×
226
        }
×
227

228
        txOut := wire.NewTxOut(amt, pkScript)
58✔
229

58✔
230
        // For the "witness program" we just return the raw pkScript since the
58✔
231
        // output we create can _only_ be spent with a musig2 signature.
58✔
232
        return pkScript, txOut, nil
58✔
233
}
234

235
// SpendMultiSig generates the witness stack required to redeem the 2-of-2 p2wsh
236
// multi-sig output.
237
func SpendMultiSig(witnessScript, pubA []byte, sigA Signature,
238
        pubB []byte, sigB Signature) [][]byte {
144✔
239

144✔
240
        witness := make([][]byte, 4)
144✔
241

144✔
242
        // When spending a p2wsh multi-sig script, rather than an OP_0, we add
144✔
243
        // a nil stack element to eat the extra pop.
144✔
244
        witness[0] = nil
144✔
245

144✔
246
        // When initially generating the witnessScript, we sorted the serialized
144✔
247
        // public keys in descending order. So we do a quick comparison in order
144✔
248
        // ensure the signatures appear on the Script Virtual Machine stack in
144✔
249
        // the correct order.
144✔
250
        if bytes.Compare(pubA, pubB) == 1 {
181✔
251
                witness[1] = append(sigB.Serialize(), byte(txscript.SigHashAll))
37✔
252
                witness[2] = append(sigA.Serialize(), byte(txscript.SigHashAll))
37✔
253
        } else {
147✔
254
                witness[1] = append(sigA.Serialize(), byte(txscript.SigHashAll))
110✔
255
                witness[2] = append(sigB.Serialize(), byte(txscript.SigHashAll))
110✔
256
        }
110✔
257

258
        // Finally, add the preimage as the last witness element.
259
        witness[3] = witnessScript
144✔
260

144✔
261
        return witness
144✔
262
}
263

264
// FindScriptOutputIndex finds the index of the public key script output
265
// matching 'script'. Additionally, a boolean is returned indicating if a
266
// matching output was found at all.
267
//
268
// NOTE: The search stops after the first matching script is found.
269
func FindScriptOutputIndex(tx *wire.MsgTx, script []byte) (bool, uint32) {
87✔
270
        found := false
87✔
271
        index := uint32(0)
87✔
272
        for i, txOut := range tx.TxOut {
205✔
273
                if bytes.Equal(txOut.PkScript, script) {
203✔
274
                        found = true
85✔
275
                        index = uint32(i)
85✔
276
                        break
85✔
277
                }
278
        }
279

280
        return found, index
87✔
281
}
282

283
// Ripemd160H calculates the ripemd160 of the passed byte slice. This is used to
284
// calculate the intermediate hash for payment pre-images. Payment hashes are
285
// the result of ripemd160(sha256(paymentPreimage)). As a result, the value
286
// passed in should be the sha256 of the payment hash.
287
func Ripemd160H(d []byte) []byte {
475,670✔
288
        h := ripemd160.New()
475,670✔
289
        h.Write(d)
475,670✔
290
        return h.Sum(nil)
475,670✔
291
}
475,670✔
292

293
// SenderHTLCScript constructs the public key script for an outgoing HTLC
294
// output payment for the sender's version of the commitment transaction. The
295
// possible script paths from this output include:
296
//
297
//   - The sender timing out the HTLC using the second level HTLC timeout
298
//     transaction.
299
//   - The receiver of the HTLC claiming the output on-chain with the payment
300
//     preimage.
301
//   - The receiver of the HTLC sweeping all the funds in the case that a
302
//     revoked commitment transaction bearing this HTLC was broadcast.
303
//
304
// If confirmedSpend=true, a 1 OP_CSV check will be added to the non-revocation
305
// cases, to allow sweeping only after confirmation.
306
//
307
// Possible Input Scripts:
308
//
309
//        SENDR: <0> <sendr sig>  <recvr sig> <0> (spend using HTLC timeout transaction)
310
//        RECVR: <recvr sig>  <preimage>
311
//        REVOK: <revoke sig> <revoke key>
312
//         * receiver revoke
313
//
314
// Offered HTLC Output Script:
315
//
316
//         OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
317
//         OP_IF
318
//                OP_CHECKSIG
319
//         OP_ELSE
320
//                <recv htlc key>
321
//                OP_SWAP OP_SIZE 32 OP_EQUAL
322
//                OP_NOTIF
323
//                    OP_DROP 2 OP_SWAP <sender htlc key> 2 OP_CHECKMULTISIG
324
//                OP_ELSE
325
//                    OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
326
//                    OP_CHECKSIG
327
//                OP_ENDIF
328
//                [1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed
329
//                spend only.
330
//         OP_ENDIF
331
func SenderHTLCScript(senderHtlcKey, receiverHtlcKey,
332
        revocationKey *btcec.PublicKey, paymentHash []byte,
333
        confirmedSpend bool) ([]byte, error) {
237,532✔
334

237,532✔
335
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
237,532✔
336
                OfferedHtlcScriptSizeConfirmed,
237,532✔
337
        ))
237,532✔
338

237,532✔
339
        // The opening operations are used to determine if this is the receiver
237,532✔
340
        // of the HTLC attempting to sweep all the funds due to a contract
237,532✔
341
        // breach. In this case, they'll place the revocation key at the top of
237,532✔
342
        // the stack.
237,532✔
343
        builder.AddOp(txscript.OP_DUP)
237,532✔
344
        builder.AddOp(txscript.OP_HASH160)
237,532✔
345
        builder.AddData(btcutil.Hash160(revocationKey.SerializeCompressed()))
237,532✔
346
        builder.AddOp(txscript.OP_EQUAL)
237,532✔
347

237,532✔
348
        // If the hash matches, then this is the revocation clause. The output
237,532✔
349
        // can be spent if the check sig operation passes.
237,532✔
350
        builder.AddOp(txscript.OP_IF)
237,532✔
351
        builder.AddOp(txscript.OP_CHECKSIG)
237,532✔
352

237,532✔
353
        // Otherwise, this may either be the receiver of the HTLC claiming with
237,532✔
354
        // the pre-image, or the sender of the HTLC sweeping the output after
237,532✔
355
        // it has timed out.
237,532✔
356
        builder.AddOp(txscript.OP_ELSE)
237,532✔
357

237,532✔
358
        // We'll do a bit of set up by pushing the receiver's key on the top of
237,532✔
359
        // the stack. This will be needed later if we decide that this is the
237,532✔
360
        // sender activating the time out clause with the HTLC timeout
237,532✔
361
        // transaction.
237,532✔
362
        builder.AddData(receiverHtlcKey.SerializeCompressed())
237,532✔
363

237,532✔
364
        // Atm, the top item of the stack is the receiverKey's so we use a swap
237,532✔
365
        // to expose what is either the payment pre-image or a signature.
237,532✔
366
        builder.AddOp(txscript.OP_SWAP)
237,532✔
367

237,532✔
368
        // With the top item swapped, check if it's 32 bytes. If so, then this
237,532✔
369
        // *may* be the payment pre-image.
237,532✔
370
        builder.AddOp(txscript.OP_SIZE)
237,532✔
371
        builder.AddInt64(32)
237,532✔
372
        builder.AddOp(txscript.OP_EQUAL)
237,532✔
373

237,532✔
374
        // If it isn't then this might be the sender of the HTLC activating the
237,532✔
375
        // time out clause.
237,532✔
376
        builder.AddOp(txscript.OP_NOTIF)
237,532✔
377

237,532✔
378
        // We'll drop the OP_IF return value off the top of the stack so we can
237,532✔
379
        // reconstruct the multi-sig script used as an off-chain covenant. If
237,532✔
380
        // two valid signatures are provided, then the output will be deemed as
237,532✔
381
        // spendable.
237,532✔
382
        builder.AddOp(txscript.OP_DROP)
237,532✔
383
        builder.AddOp(txscript.OP_2)
237,532✔
384
        builder.AddOp(txscript.OP_SWAP)
237,532✔
385
        builder.AddData(senderHtlcKey.SerializeCompressed())
237,532✔
386
        builder.AddOp(txscript.OP_2)
237,532✔
387
        builder.AddOp(txscript.OP_CHECKMULTISIG)
237,532✔
388

237,532✔
389
        // Otherwise, then the only other case is that this is the receiver of
237,532✔
390
        // the HTLC sweeping it on-chain with the payment pre-image.
237,532✔
391
        builder.AddOp(txscript.OP_ELSE)
237,532✔
392

237,532✔
393
        // Hash the top item of the stack and compare it with the hash160 of
237,532✔
394
        // the payment hash, which is already the sha256 of the payment
237,532✔
395
        // pre-image. By using this little trick we're able to save space
237,532✔
396
        // on-chain as the witness includes a 20-byte hash rather than a
237,532✔
397
        // 32-byte hash.
237,532✔
398
        builder.AddOp(txscript.OP_HASH160)
237,532✔
399
        builder.AddData(Ripemd160H(paymentHash))
237,532✔
400
        builder.AddOp(txscript.OP_EQUALVERIFY)
237,532✔
401

237,532✔
402
        // This checks the receiver's signature so that a third party with
237,532✔
403
        // knowledge of the payment preimage still cannot steal the output.
237,532✔
404
        builder.AddOp(txscript.OP_CHECKSIG)
237,532✔
405

237,532✔
406
        // Close out the OP_IF statement above.
237,532✔
407
        builder.AddOp(txscript.OP_ENDIF)
237,532✔
408

237,532✔
409
        // Add 1 block CSV delay if a confirmation is required for the
237,532✔
410
        // non-revocation clauses.
237,532✔
411
        if confirmedSpend {
237,619✔
412
                builder.AddOp(txscript.OP_1)
87✔
413
                builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
87✔
414
                builder.AddOp(txscript.OP_DROP)
87✔
415
        }
87✔
416

417
        // Close out the OP_IF statement at the top of the script.
418
        builder.AddOp(txscript.OP_ENDIF)
237,532✔
419

237,532✔
420
        return builder.Script()
237,532✔
421
}
422

423
// SenderHtlcSpendRevokeWithKey constructs a valid witness allowing the receiver of an
424
// HTLC to claim the output with knowledge of the revocation private key in the
425
// scenario that the sender of the HTLC broadcasts a previously revoked
426
// commitment transaction. A valid spend requires knowledge of the private key
427
// that corresponds to their revocation base point and also the private key from
428
// the per commitment point, and a valid signature under the combined public
429
// key.
430
func SenderHtlcSpendRevokeWithKey(signer Signer, signDesc *SignDescriptor,
431
        revokeKey *btcec.PublicKey, sweepTx *wire.MsgTx) (wire.TxWitness, error) {
5✔
432

5✔
433
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
5✔
434
        if err != nil {
5✔
435
                return nil, err
×
436
        }
×
437

438
        // The stack required to sweep a revoke HTLC output consists simply of
439
        // the exact witness stack as one of a regular p2wkh spend. The only
440
        // difference is that the keys used were derived in an adversarial
441
        // manner in order to encode the revocation contract into a sig+key
442
        // pair.
443
        witnessStack := wire.TxWitness(make([][]byte, 3))
5✔
444
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
5✔
445
        witnessStack[1] = revokeKey.SerializeCompressed()
5✔
446
        witnessStack[2] = signDesc.WitnessScript
5✔
447

5✔
448
        return witnessStack, nil
5✔
449
}
450

451
// SenderHtlcSpendRevoke constructs a valid witness allowing the receiver of an
452
// HTLC to claim the output with knowledge of the revocation private key in the
453
// scenario that the sender of the HTLC broadcasts a previously revoked
454
// commitment transaction.  This method first derives the appropriate revocation
455
// key, and requires that the provided SignDescriptor has a local revocation
456
// basepoint and commitment secret in the PubKey and DoubleTweak fields,
457
// respectively.
458
func SenderHtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
459
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
4✔
460

4✔
461
        revokeKey, err := deriveRevokePubKey(signDesc)
4✔
462
        if err != nil {
4✔
463
                return nil, err
×
464
        }
×
465

466
        return SenderHtlcSpendRevokeWithKey(signer, signDesc, revokeKey, sweepTx)
4✔
467
}
468

469
// IsHtlcSpendRevoke is used to determine if the passed spend is spending a
470
// HTLC output using the revocation key.
471
func IsHtlcSpendRevoke(txIn *wire.TxIn, signDesc *SignDescriptor) (
472
        bool, error) {
7✔
473

7✔
474
        // For taproot channels, the revocation path only has a single witness,
7✔
475
        // as that's the key spend path.
7✔
476
        isTaproot := txscript.IsPayToTaproot(signDesc.Output.PkScript)
7✔
477
        if isTaproot {
10✔
478
                return len(txIn.Witness) == 1, nil
3✔
479
        }
3✔
480

481
        revokeKey, err := deriveRevokePubKey(signDesc)
4✔
482
        if err != nil {
4✔
483
                return false, err
×
484
        }
×
485

486
        if len(txIn.Witness) == 3 &&
4✔
487
                bytes.Equal(txIn.Witness[1], revokeKey.SerializeCompressed()) {
6✔
488

2✔
489
                return true, nil
2✔
490
        }
2✔
491

492
        return false, nil
2✔
493
}
494

495
// SenderHtlcSpendRedeem constructs a valid witness allowing the receiver of an
496
// HTLC to redeem the pending output in the scenario that the sender broadcasts
497
// their version of the commitment transaction. A valid spend requires
498
// knowledge of the payment preimage, and a valid signature under the receivers
499
// public key.
500
func SenderHtlcSpendRedeem(signer Signer, signDesc *SignDescriptor,
501
        sweepTx *wire.MsgTx, paymentPreimage []byte) (wire.TxWitness, error) {
14✔
502

14✔
503
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
14✔
504
        if err != nil {
14✔
505
                return nil, err
×
506
        }
×
507

508
        // The stack required to spend this output is simply the signature
509
        // generated above under the receiver's public key, and the payment
510
        // pre-image.
511
        witnessStack := wire.TxWitness(make([][]byte, 3))
14✔
512
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
14✔
513
        witnessStack[1] = paymentPreimage
14✔
514
        witnessStack[2] = signDesc.WitnessScript
14✔
515

14✔
516
        return witnessStack, nil
14✔
517
}
518

519
// SenderHtlcSpendTimeout constructs a valid witness allowing the sender of an
520
// HTLC to activate the time locked covenant clause of a soon to be expired
521
// HTLC.  This script simply spends the multi-sig output using the
522
// pre-generated HTLC timeout transaction.
523
func SenderHtlcSpendTimeout(receiverSig Signature,
524
        receiverSigHash txscript.SigHashType, signer Signer,
525
        signDesc *SignDescriptor, htlcTimeoutTx *wire.MsgTx) (
526
        wire.TxWitness, error) {
56✔
527

56✔
528
        sweepSig, err := signer.SignOutputRaw(htlcTimeoutTx, signDesc)
56✔
529
        if err != nil {
56✔
530
                return nil, err
×
531
        }
×
532

533
        // We place a zero as the first item of the evaluated witness stack in
534
        // order to force Script execution to the HTLC timeout clause. The
535
        // second zero is required to consume the extra pop due to a bug in the
536
        // original OP_CHECKMULTISIG.
537
        witnessStack := wire.TxWitness(make([][]byte, 5))
56✔
538
        witnessStack[0] = nil
56✔
539
        witnessStack[1] = append(receiverSig.Serialize(), byte(receiverSigHash))
56✔
540
        witnessStack[2] = append(sweepSig.Serialize(), byte(signDesc.HashType))
56✔
541
        witnessStack[3] = nil
56✔
542
        witnessStack[4] = signDesc.WitnessScript
56✔
543

56✔
544
        return witnessStack, nil
56✔
545
}
546

547
// SenderHTLCTapLeafTimeout returns the full tapscript leaf for the timeout
548
// path of the sender HTLC. This is a small script that allows the sender to
549
// timeout the HTLC after a period of time:
550
//
551
//        <local_key> OP_CHECKSIGVERIFY
552
//        <remote_key> OP_CHECKSIG
553
func SenderHTLCTapLeafTimeout(senderHtlcKey,
554
        receiverHtlcKey *btcec.PublicKey) (txscript.TapLeaf, error) {
32✔
555

32✔
556
        builder := txscript.NewScriptBuilder()
32✔
557

32✔
558
        builder.AddData(schnorr.SerializePubKey(senderHtlcKey))
32✔
559
        builder.AddOp(txscript.OP_CHECKSIGVERIFY)
32✔
560
        builder.AddData(schnorr.SerializePubKey(receiverHtlcKey))
32✔
561
        builder.AddOp(txscript.OP_CHECKSIG)
32✔
562

32✔
563
        timeoutLeafScript, err := builder.Script()
32✔
564
        if err != nil {
32✔
565
                return txscript.TapLeaf{}, err
×
566
        }
×
567

568
        return txscript.NewBaseTapLeaf(timeoutLeafScript), nil
32✔
569
}
570

571
// SenderHTLCTapLeafSuccess returns the full tapscript leaf for the success
572
// path of the sender HTLC. This is a small script that allows the receiver to
573
// redeem the HTLC with a pre-image:
574
//
575
//        OP_SIZE 32 OP_EQUALVERIFY OP_HASH160
576
//        <RIPEMD160(payment_hash)> OP_EQUALVERIFY
577
//        <remote_htlcpubkey> OP_CHECKSIG
578
//        1 OP_CHECKSEQUENCEVERIFY OP_DROP
579
func SenderHTLCTapLeafSuccess(receiverHtlcKey *btcec.PublicKey,
580
        paymentHash []byte) (txscript.TapLeaf, error) {
32✔
581

32✔
582
        builder := txscript.NewScriptBuilder()
32✔
583

32✔
584
        // Check that the pre-image is 32 bytes as required.
32✔
585
        builder.AddOp(txscript.OP_SIZE)
32✔
586
        builder.AddInt64(32)
32✔
587
        builder.AddOp(txscript.OP_EQUALVERIFY)
32✔
588

32✔
589
        // Check that the specified pre-image matches what we hard code into
32✔
590
        // the script.
32✔
591
        builder.AddOp(txscript.OP_HASH160)
32✔
592
        builder.AddData(Ripemd160H(paymentHash))
32✔
593
        builder.AddOp(txscript.OP_EQUALVERIFY)
32✔
594

32✔
595
        // Verify the remote party's signature, then make them wait 1 block
32✔
596
        // after confirmation to properly sweep.
32✔
597
        builder.AddData(schnorr.SerializePubKey(receiverHtlcKey))
32✔
598
        builder.AddOp(txscript.OP_CHECKSIG)
32✔
599
        builder.AddOp(txscript.OP_1)
32✔
600
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
32✔
601
        builder.AddOp(txscript.OP_DROP)
32✔
602

32✔
603
        successLeafScript, err := builder.Script()
32✔
604
        if err != nil {
32✔
605
                return txscript.TapLeaf{}, err
×
606
        }
×
607

608
        return txscript.NewBaseTapLeaf(successLeafScript), nil
32✔
609
}
610

611
// htlcType is an enum value that denotes what type of HTLC script this is.
612
type htlcType uint8
613

614
const (
615
        // htlcLocalIncoming represents an incoming HTLC on the local
616
        // commitment transaction.
617
        htlcLocalIncoming htlcType = iota
618

619
        // htlcLocalOutgoing represents an outgoing HTLC on the local
620
        // commitment transaction.
621
        htlcLocalOutgoing
622

623
        // htlcRemoteIncoming represents an incoming HTLC on the remote
624
        // commitment transaction.
625
        htlcRemoteIncoming
626

627
        // htlcRemoteOutgoing represents an outgoing HTLC on the remote
628
        // commitment transaction.
629
        htlcRemoteOutgoing
630
)
631

632
// HtlcScriptTree holds the taproot output key, as well as the two script path
633
// leaves that every taproot HTLC script depends on.
634
type HtlcScriptTree struct {
635
        ScriptTree
636

637
        // SuccessTapLeaf is the tapleaf for the redemption path.
638
        SuccessTapLeaf txscript.TapLeaf
639

640
        // TimeoutTapLeaf is the tapleaf for the timeout path.
641
        TimeoutTapLeaf txscript.TapLeaf
642

643
        htlcType htlcType
644
}
645

646
// WitnessScriptToSign returns the witness script that we'll use when signing
647
// for the remote party, and also verifying signatures on our transactions. As
648
// an example, when we create an outgoing HTLC for the remote party, we want to
649
// sign the success path for them, so we'll return the success path leaf.
650
func (h *HtlcScriptTree) WitnessScriptToSign() []byte {
54✔
651
        switch h.htlcType {
54✔
652
        // For incoming HLTCs on our local commitment, we care about verifying
653
        // the success path.
654
        case htlcLocalIncoming:
15✔
655
                return h.SuccessTapLeaf.Script
15✔
656

657
        // For incoming HTLCs on the remote party's commitment, we want to sign
658
        // the timeout path for them.
659
        case htlcRemoteIncoming:
12✔
660
                return h.TimeoutTapLeaf.Script
12✔
661

662
        // For outgoing HTLCs on our local commitment, we want to verify the
663
        // timeout path.
664
        case htlcLocalOutgoing:
16✔
665
                return h.TimeoutTapLeaf.Script
16✔
666

667
        // For outgoing HTLCs on the remote party's commitment, we want to sign
668
        // the success path for them.
669
        case htlcRemoteOutgoing:
20✔
670
                return h.SuccessTapLeaf.Script
20✔
671

672
        default:
×
673
                panic(fmt.Sprintf("unknown htlc type: %v", h.htlcType))
×
674
        }
675
}
676

677
// WitnessScriptForPath returns the witness script for the given spending path.
678
// An error is returned if the path is unknown.
679
func (h *HtlcScriptTree) WitnessScriptForPath(path ScriptPath) ([]byte, error) {
7✔
680
        switch path {
7✔
681
        case ScriptPathSuccess:
5✔
682
                return h.SuccessTapLeaf.Script, nil
5✔
683
        case ScriptPathTimeout:
5✔
684
                return h.TimeoutTapLeaf.Script, nil
5✔
685
        default:
×
686
                return nil, fmt.Errorf("unknown script path: %v", path)
×
687
        }
688
}
689

690
// CtrlBlockForPath returns the control block for the given spending path. For
691
// script types that don't have a control block, nil is returned.
692
func (h *HtlcScriptTree) CtrlBlockForPath(
693
        path ScriptPath) (*txscript.ControlBlock, error) {
3✔
694

3✔
695
        switch path {
3✔
696
        case ScriptPathSuccess:
3✔
697
                return lnutils.Ptr(MakeTaprootCtrlBlock(
3✔
698
                        h.SuccessTapLeaf.Script, h.InternalKey,
3✔
699
                        h.TapscriptTree,
3✔
700
                )), nil
3✔
701
        case ScriptPathTimeout:
3✔
702
                return lnutils.Ptr(MakeTaprootCtrlBlock(
3✔
703
                        h.TimeoutTapLeaf.Script, h.InternalKey,
3✔
704
                        h.TapscriptTree,
3✔
705
                )), nil
3✔
706
        default:
×
707
                return nil, fmt.Errorf("unknown script path: %v", path)
×
708
        }
709
}
710

711
// Tree returns the underlying ScriptTree of the HtlcScriptTree.
NEW
712
func (h *HtlcScriptTree) Tree() ScriptTree {
×
NEW
713
        return h.ScriptTree
×
NEW
714
}
×
715

716
// A compile time check to ensure HtlcScriptTree implements the
717
// TapscriptMultiplexer interface.
718
var _ TapscriptDescriptor = (*HtlcScriptTree)(nil)
719

720
// senderHtlcTapScriptTree builds the tapscript tree which is used to anchor
721
// the HTLC key for HTLCs on the sender's commitment.
722
func senderHtlcTapScriptTree(senderHtlcKey, receiverHtlcKey,
723
        revokeKey *btcec.PublicKey, payHash []byte,
724
        hType htlcType) (*HtlcScriptTree, error) {
32✔
725

32✔
726
        // First, we'll obtain the tap leaves for both the success and timeout
32✔
727
        // path.
32✔
728
        successTapLeaf, err := SenderHTLCTapLeafSuccess(
32✔
729
                receiverHtlcKey, payHash,
32✔
730
        )
32✔
731
        if err != nil {
32✔
732
                return nil, err
×
733
        }
×
734
        timeoutTapLeaf, err := SenderHTLCTapLeafTimeout(
32✔
735
                senderHtlcKey, receiverHtlcKey,
32✔
736
        )
32✔
737
        if err != nil {
32✔
738
                return nil, err
×
739
        }
×
740

741
        // With the two leaves obtained, we'll now make the tapscript tree,
742
        // then obtain the root from that
743
        tapscriptTree := txscript.AssembleTaprootScriptTree(
32✔
744
                successTapLeaf, timeoutTapLeaf,
32✔
745
        )
32✔
746

32✔
747
        tapScriptRoot := tapscriptTree.RootNode.TapHash()
32✔
748

32✔
749
        // With the tapscript root obtained, we'll tweak the revocation key
32✔
750
        // with this value to obtain the key that HTLCs will be sent to.
32✔
751
        htlcKey := txscript.ComputeTaprootOutputKey(
32✔
752
                revokeKey, tapScriptRoot[:],
32✔
753
        )
32✔
754

32✔
755
        return &HtlcScriptTree{
32✔
756
                ScriptTree: ScriptTree{
32✔
757
                        TaprootKey:    htlcKey,
32✔
758
                        TapscriptTree: tapscriptTree,
32✔
759
                        TapscriptRoot: tapScriptRoot[:],
32✔
760
                        InternalKey:   revokeKey,
32✔
761
                },
32✔
762
                SuccessTapLeaf: successTapLeaf,
32✔
763
                TimeoutTapLeaf: timeoutTapLeaf,
32✔
764
                htlcType:       hType,
32✔
765
        }, nil
32✔
766
}
767

768
// SenderHTLCScriptTaproot constructs the taproot witness program (schnorr key)
769
// for an outgoing HTLC on the sender's version of the commitment transaction.
770
// This method returns the top level tweaked public key that commits to both
771
// the script paths. This is also known as an offered HTLC.
772
//
773
// The returned key commits to a tapscript tree with two possible paths:
774
//
775
//   - Timeout path:
776
//     <local_key> OP_CHECKSIGVERIFY
777
//     <remote_key> OP_CHECKSIG
778
//
779
//   - Success path:
780
//     OP_SIZE 32 OP_EQUALVERIFY
781
//     OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
782
//     <remote_htlcpubkey> OP_CHECKSIG
783
//     1 OP_CHECKSEQUENCEVERIFY OP_DROP
784
//
785
// The timeout path can be spent with a witness of (sender timeout):
786
//
787
//        <receiver sig> <local sig> <timeout_script> <control_block>
788
//
789
// The success path can be spent with a valid control block, and a witness of
790
// (receiver redeem):
791
//
792
//        <receiver sig> <preimage> <success_script> <control_block>
793
//
794
// The top level keyspend key is the revocation key, which allows a defender to
795
// unilaterally spend the created output.
796
func SenderHTLCScriptTaproot(senderHtlcKey, receiverHtlcKey,
797
        revokeKey *btcec.PublicKey, payHash []byte,
798
        whoseCommit lntypes.ChannelParty) (*HtlcScriptTree, error) {
32✔
799

32✔
800
        var hType htlcType
32✔
801
        if whoseCommit.IsLocal() {
50✔
802
                hType = htlcLocalOutgoing
18✔
803
        } else {
35✔
804
                hType = htlcRemoteIncoming
17✔
805
        }
17✔
806

807
        // Given all the necessary parameters, we'll return the HTLC script
808
        // tree that includes the top level output script, as well as the two
809
        // tap leaf paths.
810
        return senderHtlcTapScriptTree(
32✔
811
                senderHtlcKey, receiverHtlcKey, revokeKey, payHash,
32✔
812
                hType,
32✔
813
        )
32✔
814
}
815

816
// maybeAppendSighashType appends a sighash type to the end of a signature if
817
// the sighash type isn't sighash default.
818
func maybeAppendSighash(sig Signature, sigHash txscript.SigHashType) []byte {
1,466✔
819
        sigBytes := sig.Serialize()
1,466✔
820
        if sigHash == txscript.SigHashDefault {
2,862✔
821
                return sigBytes
1,396✔
822
        }
1,396✔
823

824
        return append(sigBytes, byte(sigHash))
73✔
825
}
826

827
// SenderHTLCScriptTaprootRedeem creates a valid witness needed to redeem a
828
// sender taproot HTLC with the pre-image. The returned witness is valid and
829
// includes the control block required to spend the output. This is the offered
830
// HTLC claimed by the remote party.
831
func SenderHTLCScriptTaprootRedeem(signer Signer, signDesc *SignDescriptor,
832
        sweepTx *wire.MsgTx, preimage []byte, revokeKey *btcec.PublicKey,
833
        tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error) {
8✔
834

8✔
835
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
8✔
836
        if err != nil {
8✔
837
                return nil, err
×
838
        }
×
839

840
        // In addition to the signature and the witness/leaf script, we also
841
        // need to make a control block proof using the tapscript tree.
842
        var ctrlBlock []byte
8✔
843
        if signDesc.ControlBlock == nil {
13✔
844
                successControlBlock := MakeTaprootCtrlBlock(
5✔
845
                        signDesc.WitnessScript, revokeKey, tapscriptTree,
5✔
846
                )
5✔
847

5✔
848
                ctrlBytes, err := successControlBlock.ToBytes()
5✔
849
                if err != nil {
5✔
850
                        return nil, err
×
851
                }
×
852

853
                ctrlBlock = ctrlBytes
5✔
854
        } else {
3✔
855
                ctrlBlock = signDesc.ControlBlock
3✔
856
        }
3✔
857

858
        // The final witness stack is:
859
        //  <receiver sig> <preimage> <success_script> <control_block>
860
        witnessStack := make(wire.TxWitness, 4)
8✔
861
        witnessStack[0] = maybeAppendSighash(sweepSig, signDesc.HashType)
8✔
862
        witnessStack[1] = preimage
8✔
863
        witnessStack[2] = signDesc.WitnessScript
8✔
864
        witnessStack[3] = ctrlBlock
8✔
865

8✔
866
        return witnessStack, nil
8✔
867
}
868

869
// SenderHTLCScriptTaprootTimeout creates a valid witness needed to timeout an
870
// HTLC on the sender's commitment transaction. The returned witness is valid
871
// and includes the control block required to spend the output. This is a
872
// timeout of the offered HTLC by the sender.
873
func SenderHTLCScriptTaprootTimeout(receiverSig Signature,
874
        receiverSigHash txscript.SigHashType, signer Signer,
875
        signDesc *SignDescriptor, htlcTimeoutTx *wire.MsgTx,
876
        revokeKey *btcec.PublicKey,
877
        tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error) {
12✔
878

12✔
879
        sweepSig, err := signer.SignOutputRaw(htlcTimeoutTx, signDesc)
12✔
880
        if err != nil {
12✔
881
                return nil, err
×
882
        }
×
883

884
        // With the sweep signature obtained, we'll obtain the control block
885
        // proof needed to perform a valid spend for the timeout path.
886
        var ctrlBlockBytes []byte
12✔
887
        if signDesc.ControlBlock == nil {
24✔
888
                timeoutControlBlock := MakeTaprootCtrlBlock(
12✔
889
                        signDesc.WitnessScript, revokeKey, tapscriptTree,
12✔
890
                )
12✔
891
                ctrlBytes, err := timeoutControlBlock.ToBytes()
12✔
892
                if err != nil {
12✔
893
                        return nil, err
×
894
                }
×
895

896
                ctrlBlockBytes = ctrlBytes
12✔
897
        } else {
3✔
898
                ctrlBlockBytes = signDesc.ControlBlock
3✔
899
        }
3✔
900

901
        // The final witness stack is:
902
        //  <receiver sig> <local sig> <timeout_script> <control_block>
903
        witnessStack := make(wire.TxWitness, 4)
12✔
904
        witnessStack[0] = maybeAppendSighash(receiverSig, receiverSigHash)
12✔
905
        witnessStack[1] = maybeAppendSighash(sweepSig, signDesc.HashType)
12✔
906
        witnessStack[2] = signDesc.WitnessScript
12✔
907
        witnessStack[3] = ctrlBlockBytes
12✔
908

12✔
909
        return witnessStack, nil
12✔
910
}
911

912
// SenderHTLCScriptTaprootRevoke creates a valid witness needed to spend the
913
// revocation path of the HTLC. This uses a plain keyspend using the specified
914
// revocation key.
915
func SenderHTLCScriptTaprootRevoke(signer Signer, signDesc *SignDescriptor,
916
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
8✔
917

8✔
918
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
8✔
919
        if err != nil {
8✔
920
                return nil, err
×
921
        }
×
922

923
        // The witness stack in this case is pretty simple: we only need to
924
        // specify the signature generated.
925
        witnessStack := make(wire.TxWitness, 1)
8✔
926
        witnessStack[0] = maybeAppendSighash(sweepSig, signDesc.HashType)
8✔
927

8✔
928
        return witnessStack, nil
8✔
929
}
930

931
// ReceiverHTLCScript constructs the public key script for an incoming HTLC
932
// output payment for the receiver's version of the commitment transaction. The
933
// possible execution paths from this script include:
934
//   - The receiver of the HTLC uses its second level HTLC transaction to
935
//     advance the state of the HTLC into the delay+claim state.
936
//   - The sender of the HTLC sweeps all the funds of the HTLC as a breached
937
//     commitment was broadcast.
938
//   - The sender of the HTLC sweeps the HTLC on-chain after the timeout period
939
//     of the HTLC has passed.
940
//
941
// If confirmedSpend=true, a 1 OP_CSV check will be added to the non-revocation
942
// cases, to allow sweeping only after confirmation.
943
//
944
// Possible Input Scripts:
945
//
946
//        RECVR: <0> <sender sig> <recvr sig> <preimage> (spend using HTLC success transaction)
947
//        REVOK: <sig> <key>
948
//        SENDR: <sig> 0
949
//
950
// Received HTLC Output Script:
951
//
952
//         OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
953
//         OP_IF
954
//                 OP_CHECKSIG
955
//         OP_ELSE
956
//                <sendr htlc key>
957
//                OP_SWAP OP_SIZE 32 OP_EQUAL
958
//                OP_IF
959
//                    OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
960
//                    2 OP_SWAP <recvr htlc key> 2 OP_CHECKMULTISIG
961
//                OP_ELSE
962
//                    OP_DROP <cltv expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
963
//                    OP_CHECKSIG
964
//                OP_ENDIF
965
//                [1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed
966
//                spend only.
967
//         OP_ENDIF
968
func ReceiverHTLCScript(cltvExpiry uint32, senderHtlcKey,
969
        receiverHtlcKey, revocationKey *btcec.PublicKey,
970
        paymentHash []byte, confirmedSpend bool) ([]byte, error) {
237,922✔
971

237,922✔
972
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
237,922✔
973
                AcceptedHtlcScriptSizeConfirmed,
237,922✔
974
        ))
237,922✔
975

237,922✔
976
        // The opening operations are used to determine if this is the sender
237,922✔
977
        // of the HTLC attempting to sweep all the funds due to a contract
237,922✔
978
        // breach. In this case, they'll place the revocation key at the top of
237,922✔
979
        // the stack.
237,922✔
980
        builder.AddOp(txscript.OP_DUP)
237,922✔
981
        builder.AddOp(txscript.OP_HASH160)
237,922✔
982
        builder.AddData(btcutil.Hash160(revocationKey.SerializeCompressed()))
237,922✔
983
        builder.AddOp(txscript.OP_EQUAL)
237,922✔
984

237,922✔
985
        // If the hash matches, then this is the revocation clause. The output
237,922✔
986
        // can be spent if the check sig operation passes.
237,922✔
987
        builder.AddOp(txscript.OP_IF)
237,922✔
988
        builder.AddOp(txscript.OP_CHECKSIG)
237,922✔
989

237,922✔
990
        // Otherwise, this may either be the receiver of the HTLC starting the
237,922✔
991
        // claiming process via the second level HTLC success transaction and
237,922✔
992
        // the pre-image, or the sender of the HTLC sweeping the output after
237,922✔
993
        // it has timed out.
237,922✔
994
        builder.AddOp(txscript.OP_ELSE)
237,922✔
995

237,922✔
996
        // We'll do a bit of set up by pushing the sender's key on the top of
237,922✔
997
        // the stack. This will be needed later if we decide that this is the
237,922✔
998
        // receiver transitioning the output to the claim state using their
237,922✔
999
        // second-level HTLC success transaction.
237,922✔
1000
        builder.AddData(senderHtlcKey.SerializeCompressed())
237,922✔
1001

237,922✔
1002
        // Atm, the top item of the stack is the sender's key so we use a swap
237,922✔
1003
        // to expose what is either the payment pre-image or something else.
237,922✔
1004
        builder.AddOp(txscript.OP_SWAP)
237,922✔
1005

237,922✔
1006
        // With the top item swapped, check if it's 32 bytes. If so, then this
237,922✔
1007
        // *may* be the payment pre-image.
237,922✔
1008
        builder.AddOp(txscript.OP_SIZE)
237,922✔
1009
        builder.AddInt64(32)
237,922✔
1010
        builder.AddOp(txscript.OP_EQUAL)
237,922✔
1011

237,922✔
1012
        // If the item on the top of the stack is 32-bytes, then it is the
237,922✔
1013
        // proper size, so this indicates that the receiver of the HTLC is
237,922✔
1014
        // attempting to claim the output on-chain by transitioning the state
237,922✔
1015
        // of the HTLC to delay+claim.
237,922✔
1016
        builder.AddOp(txscript.OP_IF)
237,922✔
1017

237,922✔
1018
        // Next we'll hash the item on the top of the stack, if it matches the
237,922✔
1019
        // payment pre-image, then we'll continue. Otherwise, we'll end the
237,922✔
1020
        // script here as this is the invalid payment pre-image.
237,922✔
1021
        builder.AddOp(txscript.OP_HASH160)
237,922✔
1022
        builder.AddData(Ripemd160H(paymentHash))
237,922✔
1023
        builder.AddOp(txscript.OP_EQUALVERIFY)
237,922✔
1024

237,922✔
1025
        // If the payment hash matches, then we'll also need to satisfy the
237,922✔
1026
        // multi-sig covenant by providing both signatures of the sender and
237,922✔
1027
        // receiver. If the convenient is met, then we'll allow the spending of
237,922✔
1028
        // this output, but only by the HTLC success transaction.
237,922✔
1029
        builder.AddOp(txscript.OP_2)
237,922✔
1030
        builder.AddOp(txscript.OP_SWAP)
237,922✔
1031
        builder.AddData(receiverHtlcKey.SerializeCompressed())
237,922✔
1032
        builder.AddOp(txscript.OP_2)
237,922✔
1033
        builder.AddOp(txscript.OP_CHECKMULTISIG)
237,922✔
1034

237,922✔
1035
        // Otherwise, this might be the sender of the HTLC attempting to sweep
237,922✔
1036
        // it on-chain after the timeout.
237,922✔
1037
        builder.AddOp(txscript.OP_ELSE)
237,922✔
1038

237,922✔
1039
        // We'll drop the extra item (which is the output from evaluating the
237,922✔
1040
        // OP_EQUAL) above from the stack.
237,922✔
1041
        builder.AddOp(txscript.OP_DROP)
237,922✔
1042

237,922✔
1043
        // With that item dropped off, we can now enforce the absolute
237,922✔
1044
        // lock-time required to timeout the HTLC. If the time has passed, then
237,922✔
1045
        // we'll proceed with a checksig to ensure that this is actually the
237,922✔
1046
        // sender of he original HTLC.
237,922✔
1047
        builder.AddInt64(int64(cltvExpiry))
237,922✔
1048
        builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
237,922✔
1049
        builder.AddOp(txscript.OP_DROP)
237,922✔
1050
        builder.AddOp(txscript.OP_CHECKSIG)
237,922✔
1051

237,922✔
1052
        // Close out the inner if statement.
237,922✔
1053
        builder.AddOp(txscript.OP_ENDIF)
237,922✔
1054

237,922✔
1055
        // Add 1 block CSV delay for non-revocation clauses if confirmation is
237,922✔
1056
        // required.
237,922✔
1057
        if confirmedSpend {
238,050✔
1058
                builder.AddOp(txscript.OP_1)
128✔
1059
                builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
128✔
1060
                builder.AddOp(txscript.OP_DROP)
128✔
1061
        }
128✔
1062

1063
        // Close out the outer if statement.
1064
        builder.AddOp(txscript.OP_ENDIF)
237,922✔
1065

237,922✔
1066
        return builder.Script()
237,922✔
1067
}
1068

1069
// ReceiverHtlcSpendRedeem constructs a valid witness allowing the receiver of
1070
// an HTLC to redeem the conditional payment in the event that their commitment
1071
// transaction is broadcast. This clause transitions the state of the HLTC
1072
// output into the delay+claim state by activating the off-chain covenant bound
1073
// by the 2-of-2 multi-sig output. The HTLC success timeout transaction being
1074
// signed has a relative timelock delay enforced by its sequence number. This
1075
// delay give the sender of the HTLC enough time to revoke the output if this
1076
// is a breach commitment transaction.
1077
func ReceiverHtlcSpendRedeem(senderSig Signature,
1078
        senderSigHash txscript.SigHashType, paymentPreimage []byte,
1079
        signer Signer, signDesc *SignDescriptor, htlcSuccessTx *wire.MsgTx) (
1080
        wire.TxWitness, error) {
61✔
1081

61✔
1082
        // First, we'll generate a signature for the HTLC success transaction.
61✔
1083
        // The signDesc should be signing with the public key used as the
61✔
1084
        // receiver's public key and also the correct single tweak.
61✔
1085
        sweepSig, err := signer.SignOutputRaw(htlcSuccessTx, signDesc)
61✔
1086
        if err != nil {
61✔
1087
                return nil, err
×
1088
        }
×
1089

1090
        // The final witness stack is used the provide the script with the
1091
        // payment pre-image, and also execute the multi-sig clause after the
1092
        // pre-images matches. We add a nil item at the bottom of the stack in
1093
        // order to consume the extra pop within OP_CHECKMULTISIG.
1094
        witnessStack := wire.TxWitness(make([][]byte, 5))
61✔
1095
        witnessStack[0] = nil
61✔
1096
        witnessStack[1] = append(senderSig.Serialize(), byte(senderSigHash))
61✔
1097
        witnessStack[2] = append(sweepSig.Serialize(), byte(signDesc.HashType))
61✔
1098
        witnessStack[3] = paymentPreimage
61✔
1099
        witnessStack[4] = signDesc.WitnessScript
61✔
1100

61✔
1101
        return witnessStack, nil
61✔
1102
}
1103

1104
// ReceiverHtlcSpendRevokeWithKey constructs a valid witness allowing the sender of an
1105
// HTLC within a previously revoked commitment transaction to re-claim the
1106
// pending funds in the case that the receiver broadcasts this revoked
1107
// commitment transaction.
1108
func ReceiverHtlcSpendRevokeWithKey(signer Signer, signDesc *SignDescriptor,
1109
        revokeKey *btcec.PublicKey, sweepTx *wire.MsgTx) (wire.TxWitness, error) {
18✔
1110

18✔
1111
        // First, we'll generate a signature for the sweep transaction.  The
18✔
1112
        // signDesc should be signing with the public key used as the fully
18✔
1113
        // derived revocation public key and also the correct double tweak
18✔
1114
        // value.
18✔
1115
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
18✔
1116
        if err != nil {
18✔
1117
                return nil, err
×
1118
        }
×
1119

1120
        // We place a zero, then one as the first items in the evaluated
1121
        // witness stack in order to force script execution to the HTLC
1122
        // revocation clause.
1123
        witnessStack := wire.TxWitness(make([][]byte, 3))
18✔
1124
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
18✔
1125
        witnessStack[1] = revokeKey.SerializeCompressed()
18✔
1126
        witnessStack[2] = signDesc.WitnessScript
18✔
1127

18✔
1128
        return witnessStack, nil
18✔
1129
}
1130

1131
func deriveRevokePubKey(signDesc *SignDescriptor) (*btcec.PublicKey, error) {
25✔
1132
        if signDesc.KeyDesc.PubKey == nil {
25✔
1133
                return nil, fmt.Errorf("cannot generate witness with nil " +
×
1134
                        "KeyDesc pubkey")
×
1135
        }
×
1136

1137
        // Derive the revocation key using the local revocation base point and
1138
        // commitment point.
1139
        revokeKey := DeriveRevocationPubkey(
25✔
1140
                signDesc.KeyDesc.PubKey,
25✔
1141
                signDesc.DoubleTweak.PubKey(),
25✔
1142
        )
25✔
1143

25✔
1144
        return revokeKey, nil
25✔
1145
}
1146

1147
// ReceiverHtlcSpendRevoke constructs a valid witness allowing the sender of an
1148
// HTLC within a previously revoked commitment transaction to re-claim the
1149
// pending funds in the case that the receiver broadcasts this revoked
1150
// commitment transaction. This method first derives the appropriate revocation
1151
// key, and requires that the provided SignDescriptor has a local revocation
1152
// basepoint and commitment secret in the PubKey and DoubleTweak fields,
1153
// respectively.
1154
func ReceiverHtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
1155
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
17✔
1156

17✔
1157
        revokeKey, err := deriveRevokePubKey(signDesc)
17✔
1158
        if err != nil {
17✔
1159
                return nil, err
×
1160
        }
×
1161

1162
        return ReceiverHtlcSpendRevokeWithKey(signer, signDesc, revokeKey, sweepTx)
17✔
1163
}
1164

1165
// ReceiverHtlcSpendTimeout constructs a valid witness allowing the sender of
1166
// an HTLC to recover the pending funds after an absolute timeout in the
1167
// scenario that the receiver of the HTLC broadcasts their version of the
1168
// commitment transaction. If the caller has already set the lock time on the
1169
// spending transaction, than a value of -1 can be passed for the cltvExpiry
1170
// value.
1171
//
1172
// NOTE: The target input of the passed transaction MUST NOT have a final
1173
// sequence number. Otherwise, the OP_CHECKLOCKTIMEVERIFY check will fail.
1174
func ReceiverHtlcSpendTimeout(signer Signer, signDesc *SignDescriptor,
1175
        sweepTx *wire.MsgTx, cltvExpiry int32) (wire.TxWitness, error) {
11✔
1176

11✔
1177
        // If the caller set a proper timeout value, then we'll apply it
11✔
1178
        // directly to the transaction.
11✔
1179
        if cltvExpiry != -1 {
19✔
1180
                // The HTLC output has an absolute time period before we are
8✔
1181
                // permitted to recover the pending funds. Therefore we need to
8✔
1182
                // set the locktime on this sweeping transaction in order to
8✔
1183
                // pass Script verification.
8✔
1184
                sweepTx.LockTime = uint32(cltvExpiry)
8✔
1185
        }
8✔
1186

1187
        // With the lock time on the transaction set, we'll not generate a
1188
        // signature for the sweep transaction. The passed sign descriptor
1189
        // should be created using the raw public key of the sender (w/o the
1190
        // single tweak applied), and the single tweak set to the proper value
1191
        // taking into account the current state's point.
1192
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
11✔
1193
        if err != nil {
11✔
1194
                return nil, err
×
1195
        }
×
1196

1197
        witnessStack := wire.TxWitness(make([][]byte, 3))
11✔
1198
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
11✔
1199
        witnessStack[1] = nil
11✔
1200
        witnessStack[2] = signDesc.WitnessScript
11✔
1201

11✔
1202
        return witnessStack, nil
11✔
1203
}
1204

1205
// ReceiverHtlcTapLeafTimeout returns the full tapscript leaf for the timeout
1206
// path of the sender HTLC. This is a small script that allows the sender
1207
// timeout the HTLC after expiry:
1208
//
1209
//        <sender_htlcpubkey> OP_CHECKSIG
1210
//        1 OP_CHECKSEQUENCEVERIFY OP_DROP
1211
//        <cltv_expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
1212
func ReceiverHtlcTapLeafTimeout(senderHtlcKey *btcec.PublicKey,
1213
        cltvExpiry uint32) (txscript.TapLeaf, error) {
39✔
1214

39✔
1215
        builder := txscript.NewScriptBuilder()
39✔
1216

39✔
1217
        // The first part of the script will verify a signature from the
39✔
1218
        // sender authorizing the spend (the timeout).
39✔
1219
        builder.AddData(schnorr.SerializePubKey(senderHtlcKey))
39✔
1220
        builder.AddOp(txscript.OP_CHECKSIG)
39✔
1221
        builder.AddOp(txscript.OP_1)
39✔
1222
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
39✔
1223
        builder.AddOp(txscript.OP_DROP)
39✔
1224

39✔
1225
        // The second portion will ensure that the CLTV expiry on the spending
39✔
1226
        // transaction is correct.
39✔
1227
        builder.AddInt64(int64(cltvExpiry))
39✔
1228
        builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
39✔
1229
        builder.AddOp(txscript.OP_DROP)
39✔
1230

39✔
1231
        timeoutLeafScript, err := builder.Script()
39✔
1232
        if err != nil {
39✔
1233
                return txscript.TapLeaf{}, err
×
1234
        }
×
1235

1236
        return txscript.NewBaseTapLeaf(timeoutLeafScript), nil
39✔
1237
}
1238

1239
// ReceiverHtlcTapLeafSuccess returns the full tapscript leaf for the success
1240
// path for an HTLC on the receiver's commitment transaction. This script
1241
// allows the receiver to redeem an HTLC with knowledge of the preimage:
1242
//
1243
//        OP_SIZE 32 OP_EQUALVERIFY OP_HASH160
1244
//        <RIPEMD160(payment_hash)> OP_EQUALVERIFY
1245
//        <receiver_htlcpubkey> OP_CHECKSIGVERIFY
1246
//        <sender_htlcpubkey> OP_CHECKSIG
1247
func ReceiverHtlcTapLeafSuccess(receiverHtlcKey *btcec.PublicKey,
1248
        senderHtlcKey *btcec.PublicKey,
1249
        paymentHash []byte) (txscript.TapLeaf, error) {
39✔
1250

39✔
1251
        builder := txscript.NewScriptBuilder()
39✔
1252

39✔
1253
        // Check that the pre-image is 32 bytes as required.
39✔
1254
        builder.AddOp(txscript.OP_SIZE)
39✔
1255
        builder.AddInt64(32)
39✔
1256
        builder.AddOp(txscript.OP_EQUALVERIFY)
39✔
1257

39✔
1258
        // Check that the specified pre-image matches what we hard code into
39✔
1259
        // the script.
39✔
1260
        builder.AddOp(txscript.OP_HASH160)
39✔
1261
        builder.AddData(Ripemd160H(paymentHash))
39✔
1262
        builder.AddOp(txscript.OP_EQUALVERIFY)
39✔
1263

39✔
1264
        // Verify the "2-of-2" multi-sig that requires both parties to sign
39✔
1265
        // off.
39✔
1266
        builder.AddData(schnorr.SerializePubKey(receiverHtlcKey))
39✔
1267
        builder.AddOp(txscript.OP_CHECKSIGVERIFY)
39✔
1268
        builder.AddData(schnorr.SerializePubKey(senderHtlcKey))
39✔
1269
        builder.AddOp(txscript.OP_CHECKSIG)
39✔
1270

39✔
1271
        successLeafScript, err := builder.Script()
39✔
1272
        if err != nil {
39✔
1273
                return txscript.TapLeaf{}, err
×
1274
        }
×
1275

1276
        return txscript.NewBaseTapLeaf(successLeafScript), nil
39✔
1277
}
1278

1279
// receiverHtlcTapScriptTree builds the tapscript tree which is used to anchor
1280
// the HTLC key for HTLCs on the receiver's commitment.
1281
func receiverHtlcTapScriptTree(senderHtlcKey, receiverHtlcKey,
1282
        revokeKey *btcec.PublicKey, payHash []byte,
1283
        cltvExpiry uint32, hType htlcType) (*HtlcScriptTree, error) {
39✔
1284

39✔
1285
        // First, we'll obtain the tap leaves for both the success and timeout
39✔
1286
        // path.
39✔
1287
        successTapLeaf, err := ReceiverHtlcTapLeafSuccess(
39✔
1288
                receiverHtlcKey, senderHtlcKey, payHash,
39✔
1289
        )
39✔
1290
        if err != nil {
39✔
1291
                return nil, err
×
1292
        }
×
1293
        timeoutTapLeaf, err := ReceiverHtlcTapLeafTimeout(
39✔
1294
                senderHtlcKey, cltvExpiry,
39✔
1295
        )
39✔
1296
        if err != nil {
39✔
1297
                return nil, err
×
1298
        }
×
1299

1300
        // With the two leaves obtained, we'll now make the tapscript tree,
1301
        // then obtain the root from that
1302
        tapscriptTree := txscript.AssembleTaprootScriptTree(
39✔
1303
                timeoutTapLeaf, successTapLeaf,
39✔
1304
        )
39✔
1305

39✔
1306
        tapScriptRoot := tapscriptTree.RootNode.TapHash()
39✔
1307

39✔
1308
        // With the tapscript root obtained, we'll tweak the revocation key
39✔
1309
        // with this value to obtain the key that HTLCs will be sent to.
39✔
1310
        htlcKey := txscript.ComputeTaprootOutputKey(
39✔
1311
                revokeKey, tapScriptRoot[:],
39✔
1312
        )
39✔
1313

39✔
1314
        return &HtlcScriptTree{
39✔
1315
                ScriptTree: ScriptTree{
39✔
1316
                        TaprootKey:    htlcKey,
39✔
1317
                        TapscriptTree: tapscriptTree,
39✔
1318
                        TapscriptRoot: tapScriptRoot[:],
39✔
1319
                        InternalKey:   revokeKey,
39✔
1320
                },
39✔
1321
                SuccessTapLeaf: successTapLeaf,
39✔
1322
                TimeoutTapLeaf: timeoutTapLeaf,
39✔
1323
                htlcType:       hType,
39✔
1324
        }, nil
39✔
1325
}
1326

1327
// ReceiverHTLCScriptTaproot constructs the taproot witness program (schnor
1328
// key) for an incoming HTLC on the receiver's version of the commitment
1329
// transaction. This method returns the top level tweaked public key that
1330
// commits to both the script paths. From the PoV of the receiver, this is an
1331
// accepted HTLC.
1332
//
1333
// The returned key commits to a tapscript tree with two possible paths:
1334
//
1335
//   - The timeout path:
1336
//     <remote_htlcpubkey> OP_CHECKSIG
1337
//     1 OP_CHECKSEQUENCEVERIFY OP_DROP
1338
//     <cltv_expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
1339
//
1340
//   - Success path:
1341
//     OP_SIZE 32 OP_EQUALVERIFY
1342
//     OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
1343
//     <local_htlcpubkey> OP_CHECKSIGVERIFY
1344
//     <remote_htlcpubkey> OP_CHECKSIG
1345
//
1346
// The timeout path can be spent with a witness of:
1347
//   - <sender sig> <timeout_script> <control_block>
1348
//
1349
// The success path can be spent with a witness of:
1350
//   - <sender sig> <receiver sig> <preimage> <success_script> <control_block>
1351
//
1352
// The top level keyspend key is the revocation key, which allows a defender to
1353
// unilaterally spend the created output. Both the final output key as well as
1354
// the tap leaf are returned.
1355
func ReceiverHTLCScriptTaproot(cltvExpiry uint32,
1356
        senderHtlcKey, receiverHtlcKey, revocationKey *btcec.PublicKey,
1357
        payHash []byte, whoseCommit lntypes.ChannelParty,
1358
) (*HtlcScriptTree, error) {
39✔
1359

39✔
1360
        var hType htlcType
39✔
1361
        if whoseCommit.IsLocal() {
56✔
1362
                hType = htlcLocalIncoming
17✔
1363
        } else {
42✔
1364
                hType = htlcRemoteOutgoing
25✔
1365
        }
25✔
1366

1367
        // Given all the necessary parameters, we'll return the HTLC script
1368
        // tree that includes the top level output script, as well as the two
1369
        // tap leaf paths.
1370
        return receiverHtlcTapScriptTree(
39✔
1371
                senderHtlcKey, receiverHtlcKey, revocationKey, payHash,
39✔
1372
                cltvExpiry, hType,
39✔
1373
        )
39✔
1374
}
1375

1376
// ReceiverHTLCScriptTaprootRedeem creates a valid witness needed to redeem a
1377
// receiver taproot HTLC with the pre-image. The returned witness is valid and
1378
// includes the control block required to spend the output.
1379
func ReceiverHTLCScriptTaprootRedeem(senderSig Signature,
1380
        senderSigHash txscript.SigHashType, paymentPreimage []byte,
1381
        signer Signer, signDesc *SignDescriptor,
1382
        htlcSuccessTx *wire.MsgTx, revokeKey *btcec.PublicKey,
1383
        tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error) {
14✔
1384

14✔
1385
        // First, we'll generate a signature for the HTLC success transaction.
14✔
1386
        // The signDesc should be signing with the public key used as the
14✔
1387
        // receiver's public key and also the correct single tweak.
14✔
1388
        sweepSig, err := signer.SignOutputRaw(htlcSuccessTx, signDesc)
14✔
1389
        if err != nil {
14✔
1390
                return nil, err
×
1391
        }
×
1392

1393
        // In addition to the signature and the witness/leaf script, we also
1394
        // need to make a control block proof using the tapscript tree.
1395
        var ctrlBlock []byte
14✔
1396
        if signDesc.ControlBlock == nil {
28✔
1397
                redeemControlBlock := MakeTaprootCtrlBlock(
14✔
1398
                        signDesc.WitnessScript, revokeKey, tapscriptTree,
14✔
1399
                )
14✔
1400
                ctrlBytes, err := redeemControlBlock.ToBytes()
14✔
1401
                if err != nil {
14✔
1402
                        return nil, err
×
1403
                }
×
1404

1405
                ctrlBlock = ctrlBytes
14✔
1406
        } else {
3✔
1407
                ctrlBlock = signDesc.ControlBlock
3✔
1408
        }
3✔
1409

1410
        // The final witness stack is:
1411
        //  * <sender sig> <receiver sig> <preimage> <success_script>
1412
        //    <control_block>
1413
        witnessStack := wire.TxWitness(make([][]byte, 5))
14✔
1414
        witnessStack[0] = maybeAppendSighash(senderSig, senderSigHash)
14✔
1415
        witnessStack[1] = maybeAppendSighash(sweepSig, signDesc.HashType)
14✔
1416
        witnessStack[2] = paymentPreimage
14✔
1417
        witnessStack[3] = signDesc.WitnessScript
14✔
1418
        witnessStack[4] = ctrlBlock
14✔
1419

14✔
1420
        return witnessStack, nil
14✔
1421
}
1422

1423
// ReceiverHTLCScriptTaprootTimeout creates a valid witness needed to timeout
1424
// an HTLC on the receiver's commitment transaction after the timeout has
1425
// elapsed.
1426
func ReceiverHTLCScriptTaprootTimeout(signer Signer, signDesc *SignDescriptor,
1427
        sweepTx *wire.MsgTx, cltvExpiry int32, revokeKey *btcec.PublicKey,
1428
        tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error) {
10✔
1429

10✔
1430
        // If the caller set a proper timeout value, then we'll apply it
10✔
1431
        // directly to the transaction.
10✔
1432
        //
10✔
1433
        // TODO(roasbeef): helper func
10✔
1434
        if cltvExpiry != -1 {
17✔
1435
                // The HTLC output has an absolute time period before we are
7✔
1436
                // permitted to recover the pending funds. Therefore we need to
7✔
1437
                // set the locktime on this sweeping transaction in order to
7✔
1438
                // pass Script verification.
7✔
1439
                sweepTx.LockTime = uint32(cltvExpiry)
7✔
1440
        }
7✔
1441

1442
        // With the lock time on the transaction set, we'll now generate a
1443
        // signature for the sweep transaction. The passed sign descriptor
1444
        // should be created using the raw public key of the sender (w/o the
1445
        // single tweak applied), and the single tweak set to the proper value
1446
        // taking into account the current state's point.
1447
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
10✔
1448
        if err != nil {
10✔
1449
                return nil, err
×
1450
        }
×
1451

1452
        // In addition to the signature and the witness/leaf script, we also
1453
        // need to make a control block proof using the tapscript tree.
1454
        var ctrlBlock []byte
10✔
1455
        if signDesc.ControlBlock == nil {
17✔
1456
                timeoutControlBlock := MakeTaprootCtrlBlock(
7✔
1457
                        signDesc.WitnessScript, revokeKey, tapscriptTree,
7✔
1458
                )
7✔
1459
                ctrlBlock, err = timeoutControlBlock.ToBytes()
7✔
1460
                if err != nil {
7✔
1461
                        return nil, err
×
1462
                }
×
1463
        } else {
3✔
1464
                ctrlBlock = signDesc.ControlBlock
3✔
1465
        }
3✔
1466

1467
        // The final witness is pretty simple, we just need to present a valid
1468
        // signature for the script, and then provide the control block.
1469
        witnessStack := make(wire.TxWitness, 3)
10✔
1470
        witnessStack[0] = maybeAppendSighash(sweepSig, signDesc.HashType)
10✔
1471
        witnessStack[1] = signDesc.WitnessScript
10✔
1472
        witnessStack[2] = ctrlBlock
10✔
1473

10✔
1474
        return witnessStack, nil
10✔
1475
}
1476

1477
// ReceiverHTLCScriptTaprootRevoke creates a valid witness needed to spend the
1478
// revocation path of the HTLC from the PoV of the sender (offerer) of the
1479
// HTLC. This uses a plain keyspend using the specified revocation key.
1480
func ReceiverHTLCScriptTaprootRevoke(signer Signer, signDesc *SignDescriptor,
1481
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
6✔
1482

6✔
1483
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
6✔
1484
        if err != nil {
6✔
1485
                return nil, err
×
1486
        }
×
1487

1488
        // The witness stack in this case is pretty simple: we only need to
1489
        // specify the signature generated.
1490
        witnessStack := make(wire.TxWitness, 1)
6✔
1491
        witnessStack[0] = maybeAppendSighash(sweepSig, signDesc.HashType)
6✔
1492

6✔
1493
        return witnessStack, nil
6✔
1494
}
1495

1496
// SecondLevelHtlcScript is the uniform script that's used as the output for
1497
// the second-level HTLC transactions. The second level transaction act as a
1498
// sort of covenant, ensuring that a 2-of-2 multi-sig output can only be
1499
// spent in a particular way, and to a particular output.
1500
//
1501
// Possible Input Scripts:
1502
//
1503
//   - To revoke an HTLC output that has been transitioned to the claim+delay
1504
//     state:
1505
//     <revoke sig> 1
1506
//
1507
//   - To claim and HTLC output, either with a pre-image or due to a timeout:
1508
//     <delay sig> 0
1509
//
1510
// Output Script:
1511
//
1512
//         OP_IF
1513
//                <revoke key>
1514
//         OP_ELSE
1515
//                <delay in blocks>
1516
//                OP_CHECKSEQUENCEVERIFY
1517
//                OP_DROP
1518
//                <delay key>
1519
//         OP_ENDIF
1520
//         OP_CHECKSIG
1521
//
1522
// TODO(roasbeef): possible renames for second-level
1523
//   - transition?
1524
//   - covenant output
1525
func SecondLevelHtlcScript(revocationKey, delayKey *btcec.PublicKey,
1526
        csvDelay uint32) ([]byte, error) {
475,124✔
1527

475,124✔
1528
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
475,124✔
1529
                ToLocalScriptSize,
475,124✔
1530
        ))
475,124✔
1531

475,124✔
1532
        // If this is the revocation clause for this script is to be executed,
475,124✔
1533
        // the spender will push a 1, forcing us to hit the true clause of this
475,124✔
1534
        // if statement.
475,124✔
1535
        builder.AddOp(txscript.OP_IF)
475,124✔
1536

475,124✔
1537
        // If this is the revocation case, then we'll push the revocation
475,124✔
1538
        // public key on the stack.
475,124✔
1539
        builder.AddData(revocationKey.SerializeCompressed())
475,124✔
1540

475,124✔
1541
        // Otherwise, this is either the sender or receiver of the HTLC
475,124✔
1542
        // attempting to claim the HTLC output.
475,124✔
1543
        builder.AddOp(txscript.OP_ELSE)
475,124✔
1544

475,124✔
1545
        // In order to give the other party time to execute the revocation
475,124✔
1546
        // clause above, we require a relative timeout to pass before the
475,124✔
1547
        // output can be spent.
475,124✔
1548
        builder.AddInt64(int64(csvDelay))
475,124✔
1549
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
475,124✔
1550
        builder.AddOp(txscript.OP_DROP)
475,124✔
1551

475,124✔
1552
        // If the relative timelock passes, then we'll add the delay key to the
475,124✔
1553
        // stack to ensure that we properly authenticate the spending party.
475,124✔
1554
        builder.AddData(delayKey.SerializeCompressed())
475,124✔
1555

475,124✔
1556
        // Close out the if statement.
475,124✔
1557
        builder.AddOp(txscript.OP_ENDIF)
475,124✔
1558

475,124✔
1559
        // In either case, we'll ensure that only either the party possessing
475,124✔
1560
        // the revocation private key, or the delay private key is able to
475,124✔
1561
        // spend this output.
475,124✔
1562
        builder.AddOp(txscript.OP_CHECKSIG)
475,124✔
1563

475,124✔
1564
        return builder.Script()
475,124✔
1565
}
475,124✔
1566

1567
// TODO(roasbeef): move all taproot stuff to new file?
1568

1569
// TaprootSecondLevelTapLeaf constructs the tap leaf used as the sole script
1570
// path for a second level HTLC spend.
1571
//
1572
// The final script used is:
1573
//
1574
//        <local_delay_key> OP_CHECKSIG
1575
//        <to_self_delay> OP_CHECKSEQUENCEVERIFY OP_DROP
1576
func TaprootSecondLevelTapLeaf(delayKey *btcec.PublicKey,
1577
        csvDelay uint32) (txscript.TapLeaf, error) {
58✔
1578

58✔
1579
        builder := txscript.NewScriptBuilder()
58✔
1580

58✔
1581
        // Ensure the proper party can sign for this output.
58✔
1582
        builder.AddData(schnorr.SerializePubKey(delayKey))
58✔
1583
        builder.AddOp(txscript.OP_CHECKSIG)
58✔
1584

58✔
1585
        // Assuming the above passes, then we'll now ensure that the CSV delay
58✔
1586
        // has been upheld, dropping the int we pushed on. If the sig above is
58✔
1587
        // valid, then a 1 will be left on the stack.
58✔
1588
        builder.AddInt64(int64(csvDelay))
58✔
1589
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
58✔
1590
        builder.AddOp(txscript.OP_DROP)
58✔
1591

58✔
1592
        secondLevelLeafScript, err := builder.Script()
58✔
1593
        if err != nil {
58✔
1594
                return txscript.TapLeaf{}, err
×
1595
        }
×
1596

1597
        return txscript.NewBaseTapLeaf(secondLevelLeafScript), nil
58✔
1598
}
1599

1600
// SecondLevelHtlcTapscriptTree construct the indexed tapscript tree needed to
1601
// generate the taptweak to create the final output and also control block.
1602
func SecondLevelHtlcTapscriptTree(delayKey *btcec.PublicKey,
1603
        csvDelay uint32) (*txscript.IndexedTapScriptTree, error) {
58✔
1604

58✔
1605
        // First grab the second level leaf script we need to create the top
58✔
1606
        // level output.
58✔
1607
        secondLevelTapLeaf, err := TaprootSecondLevelTapLeaf(delayKey, csvDelay)
58✔
1608
        if err != nil {
58✔
1609
                return nil, err
×
1610
        }
×
1611

1612
        // Now that we have the sole second level script, we can create the
1613
        // tapscript tree that commits to both the leaves.
1614
        return txscript.AssembleTaprootScriptTree(secondLevelTapLeaf), nil
58✔
1615
}
1616

1617
// TaprootSecondLevelHtlcScript is the uniform script that's used as the output
1618
// for the second-level HTLC transaction. The second level transaction acts as
1619
// an off-chain 2-of-2 covenant that can only be spent a particular way and to
1620
// a particular output.
1621
//
1622
// Possible Input Scripts:
1623
//   - revocation sig
1624
//   - <local_delay_sig>
1625
//
1626
// The script main script lets the broadcaster spend after a delay the script
1627
// path:
1628
//
1629
//        <local_delay_key> OP_CHECKSIG
1630
//        <to_self_delay> OP_CHECKSEQUENCEVERIFY OP_DROP
1631
//
1632
// The keyspend path require knowledge of the top level revocation private key.
1633
func TaprootSecondLevelHtlcScript(revokeKey, delayKey *btcec.PublicKey,
1634
        csvDelay uint32) (*btcec.PublicKey, error) {
×
1635

×
1636
        // First, we'll make the tapscript tree that commits to the redemption
×
1637
        // path.
×
1638
        tapScriptTree, err := SecondLevelHtlcTapscriptTree(
×
1639
                delayKey, csvDelay,
×
1640
        )
×
1641
        if err != nil {
×
1642
                return nil, err
×
1643
        }
×
1644

1645
        tapScriptRoot := tapScriptTree.RootNode.TapHash()
×
1646

×
1647
        // With the tapscript root obtained, we'll tweak the revocation key
×
1648
        // with this value to obtain the key that the second level spend will
×
1649
        // create.
×
1650
        redemptionKey := txscript.ComputeTaprootOutputKey(
×
1651
                revokeKey, tapScriptRoot[:],
×
1652
        )
×
1653

×
1654
        return redemptionKey, nil
×
1655
}
1656

1657
// SecondLevelScriptTree is a tapscript tree used to spend the second level
1658
// HTLC output after the CSV delay has passed.
1659
type SecondLevelScriptTree struct {
1660
        ScriptTree
1661

1662
        // SuccessTapLeaf is the tapleaf for the redemption path.
1663
        SuccessTapLeaf txscript.TapLeaf
1664
}
1665

1666
// TaprootSecondLevelScriptTree constructs the tapscript tree used to spend the
1667
// second level HTLC output.
1668
func TaprootSecondLevelScriptTree(revokeKey, delayKey *btcec.PublicKey,
1669
        csvDelay uint32) (*SecondLevelScriptTree, error) {
55✔
1670

55✔
1671
        // First, we'll make the tapscript tree that commits to the redemption
55✔
1672
        // path.
55✔
1673
        tapScriptTree, err := SecondLevelHtlcTapscriptTree(
55✔
1674
                delayKey, csvDelay,
55✔
1675
        )
55✔
1676
        if err != nil {
55✔
1677
                return nil, err
×
1678
        }
×
1679

1680
        // With the tree constructed, we can make the pkscript which is the
1681
        // taproot output key itself.
1682
        tapScriptRoot := tapScriptTree.RootNode.TapHash()
55✔
1683
        outputKey := txscript.ComputeTaprootOutputKey(
55✔
1684
                revokeKey, tapScriptRoot[:],
55✔
1685
        )
55✔
1686

55✔
1687
        return &SecondLevelScriptTree{
55✔
1688
                ScriptTree: ScriptTree{
55✔
1689
                        TaprootKey:    outputKey,
55✔
1690
                        TapscriptTree: tapScriptTree,
55✔
1691
                        TapscriptRoot: tapScriptRoot[:],
55✔
1692
                        InternalKey:   revokeKey,
55✔
1693
                },
55✔
1694
                SuccessTapLeaf: tapScriptTree.LeafMerkleProofs[0].TapLeaf,
55✔
1695
        }, nil
55✔
1696
}
1697

1698
// WitnessScriptToSign returns the witness script that we'll use when signing
1699
// for the remote party, and also verifying signatures on our transactions. As
1700
// an example, when we create an outgoing HTLC for the remote party, we want to
1701
// sign their success path.
1702
func (s *SecondLevelScriptTree) WitnessScriptToSign() []byte {
×
1703
        return s.SuccessTapLeaf.Script
×
1704
}
×
1705

1706
// WitnessScriptForPath returns the witness script for the given spending path.
1707
// An error is returned if the path is unknown.
1708
func (s *SecondLevelScriptTree) WitnessScriptForPath(
1709
        path ScriptPath) ([]byte, error) {
7✔
1710

7✔
1711
        switch path {
7✔
1712
        case ScriptPathDelay:
×
1713
                fallthrough
×
1714
        case ScriptPathSuccess:
7✔
1715
                return s.SuccessTapLeaf.Script, nil
7✔
1716

1717
        default:
×
1718
                return nil, fmt.Errorf("unknown script path: %v", path)
×
1719
        }
1720
}
1721

1722
// CtrlBlockForPath returns the control block for the given spending path. For
1723
// script types that don't have a control block, nil is returned.
1724
func (s *SecondLevelScriptTree) CtrlBlockForPath(
1725
        path ScriptPath) (*txscript.ControlBlock, error) {
7✔
1726

7✔
1727
        switch path {
7✔
1728
        case ScriptPathDelay:
×
1729
                fallthrough
×
1730
        case ScriptPathSuccess:
7✔
1731
                return lnutils.Ptr(MakeTaprootCtrlBlock(
7✔
1732
                        s.SuccessTapLeaf.Script, s.InternalKey,
7✔
1733
                        s.TapscriptTree,
7✔
1734
                )), nil
7✔
1735

1736
        default:
×
1737
                return nil, fmt.Errorf("unknown script path: %v", path)
×
1738
        }
1739
}
1740

1741
// Tree returns the underlying ScriptTree of the SecondLevelScriptTree.
NEW
1742
func (s *SecondLevelScriptTree) Tree() ScriptTree {
×
NEW
1743
        return s.ScriptTree
×
NEW
1744
}
×
1745

1746
// A compile time check to ensure SecondLevelScriptTree implements the
1747
// TapscriptDescriptor interface.
1748
var _ TapscriptDescriptor = (*SecondLevelScriptTree)(nil)
1749

1750
// TaprootHtlcSpendRevoke spends a second-level HTLC output via the revocation
1751
// path. This uses the top level keyspend path to redeem the contested output.
1752
//
1753
// The passed SignDescriptor MUST have the proper witness script and also the
1754
// proper top-level tweak derived from the tapscript tree for the second level
1755
// output.
1756
func TaprootHtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
1757
        revokeTx *wire.MsgTx) (wire.TxWitness, error) {
5✔
1758

5✔
1759
        // We don't need any spacial modifications to the transaction as this
5✔
1760
        // is just sweeping a revoked HTLC output. So we'll generate a regular
5✔
1761
        // schnorr signature.
5✔
1762
        sweepSig, err := signer.SignOutputRaw(revokeTx, signDesc)
5✔
1763
        if err != nil {
5✔
1764
                return nil, err
×
1765
        }
×
1766

1767
        // The witness stack in this case is pretty simple: we only need to
1768
        // specify the signature generated.
1769
        witnessStack := make(wire.TxWitness, 1)
5✔
1770
        witnessStack[0] = maybeAppendSighash(sweepSig, signDesc.HashType)
5✔
1771

5✔
1772
        return witnessStack, nil
5✔
1773
}
1774

1775
// TaprootHtlcSpendSuccess spends a second-level HTLC output via the redemption
1776
// path. This should be used to sweep funds after the pre-image is known.
1777
//
1778
// NOTE: The caller MUST set the txn version, sequence number, and sign
1779
// descriptor's sig hash cache before invocation.
1780
func TaprootHtlcSpendSuccess(signer Signer, signDesc *SignDescriptor,
1781
        sweepTx *wire.MsgTx, revokeKey *btcec.PublicKey,
1782
        tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error) {
11✔
1783

11✔
1784
        // First, we'll generate the sweep signature based on the populated
11✔
1785
        // sign desc. This should give us a valid schnorr signature for the
11✔
1786
        // sole script path leaf.
11✔
1787
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
11✔
1788
        if err != nil {
11✔
1789
                return nil, err
×
1790
        }
×
1791

1792
        var ctrlBlock []byte
11✔
1793
        if signDesc.ControlBlock == nil {
17✔
1794
                // Now that we have the sweep signature, we'll construct the
6✔
1795
                // control block needed to spend the script path.
6✔
1796
                redeemControlBlock := MakeTaprootCtrlBlock(
6✔
1797
                        signDesc.WitnessScript, revokeKey, tapscriptTree,
6✔
1798
                )
6✔
1799

6✔
1800
                ctrlBlock, err = redeemControlBlock.ToBytes()
6✔
1801
                if err != nil {
6✔
1802
                        return nil, err
×
1803
                }
×
1804
        } else {
5✔
1805
                ctrlBlock = signDesc.ControlBlock
5✔
1806
        }
5✔
1807

1808
        // Now that we have the redeem control block, we can construct the
1809
        // final witness needed to spend the script:
1810
        //
1811
        //  <success sig> <success script> <control_block>
1812
        witnessStack := make(wire.TxWitness, 3)
11✔
1813
        witnessStack[0] = maybeAppendSighash(sweepSig, signDesc.HashType)
11✔
1814
        witnessStack[1] = signDesc.WitnessScript
11✔
1815
        witnessStack[2] = ctrlBlock
11✔
1816

11✔
1817
        return witnessStack, nil
11✔
1818
}
1819

1820
// LeaseSecondLevelHtlcScript is the uniform script that's used as the output
1821
// for the second-level HTLC transactions. The second level transaction acts as
1822
// a sort of covenant, ensuring that a 2-of-2 multi-sig output can only be
1823
// spent in a particular way, and to a particular output.
1824
//
1825
// Possible Input Scripts:
1826
//
1827
//   - To revoke an HTLC output that has been transitioned to the claim+delay
1828
//     state:
1829
//     <revoke sig> 1
1830
//
1831
//   - To claim an HTLC output, either with a pre-image or due to a timeout:
1832
//     <delay sig> 0
1833
//
1834
// Output Script:
1835
//
1836
//         OP_IF
1837
//                <revoke key>
1838
//         OP_ELSE
1839
//                <lease maturity in blocks>
1840
//                OP_CHECKLOCKTIMEVERIFY
1841
//                OP_DROP
1842
//                <delay in blocks>
1843
//                OP_CHECKSEQUENCEVERIFY
1844
//                OP_DROP
1845
//                <delay key>
1846
//         OP_ENDIF
1847
//         OP_CHECKSIG.
1848
func LeaseSecondLevelHtlcScript(revocationKey, delayKey *btcec.PublicKey,
1849
        csvDelay, cltvExpiry uint32) ([]byte, error) {
5✔
1850

5✔
1851
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
5✔
1852
                ToLocalScriptSize + LeaseWitnessScriptSizeOverhead,
5✔
1853
        ))
5✔
1854

5✔
1855
        // If this is the revocation clause for this script is to be executed,
5✔
1856
        // the spender will push a 1, forcing us to hit the true clause of this
5✔
1857
        // if statement.
5✔
1858
        builder.AddOp(txscript.OP_IF)
5✔
1859

5✔
1860
        // If this this is the revocation case, then we'll push the revocation
5✔
1861
        // public key on the stack.
5✔
1862
        builder.AddData(revocationKey.SerializeCompressed())
5✔
1863

5✔
1864
        // Otherwise, this is either the sender or receiver of the HTLC
5✔
1865
        // attempting to claim the HTLC output.
5✔
1866
        builder.AddOp(txscript.OP_ELSE)
5✔
1867

5✔
1868
        // The channel initiator always has the additional channel lease
5✔
1869
        // expiration constraint for outputs that pay to them which must be
5✔
1870
        // satisfied.
5✔
1871
        builder.AddInt64(int64(cltvExpiry))
5✔
1872
        builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
5✔
1873
        builder.AddOp(txscript.OP_DROP)
5✔
1874

5✔
1875
        // In order to give the other party time to execute the revocation
5✔
1876
        // clause above, we require a relative timeout to pass before the
5✔
1877
        // output can be spent.
5✔
1878
        builder.AddInt64(int64(csvDelay))
5✔
1879
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
5✔
1880
        builder.AddOp(txscript.OP_DROP)
5✔
1881

5✔
1882
        // If the relative timelock passes, then we'll add the delay key to the
5✔
1883
        // stack to ensure that we properly authenticate the spending party.
5✔
1884
        builder.AddData(delayKey.SerializeCompressed())
5✔
1885

5✔
1886
        // Close out the if statement.
5✔
1887
        builder.AddOp(txscript.OP_ENDIF)
5✔
1888

5✔
1889
        // In either case, we'll ensure that only either the party possessing
5✔
1890
        // the revocation private key, or the delay private key is able to
5✔
1891
        // spend this output.
5✔
1892
        builder.AddOp(txscript.OP_CHECKSIG)
5✔
1893

5✔
1894
        return builder.Script()
5✔
1895
}
5✔
1896

1897
// HtlcSpendSuccess spends a second-level HTLC output. This function is to be
1898
// used by the sender of an HTLC to claim the output after a relative timeout
1899
// or the receiver of the HTLC to claim on-chain with the pre-image.
1900
func HtlcSpendSuccess(signer Signer, signDesc *SignDescriptor,
1901
        sweepTx *wire.MsgTx, csvDelay uint32) (wire.TxWitness, error) {
11✔
1902

11✔
1903
        // We're required to wait a relative period of time before we can sweep
11✔
1904
        // the output in order to allow the other party to contest our claim of
11✔
1905
        // validity to this version of the commitment transaction.
11✔
1906
        sweepTx.TxIn[0].Sequence = LockTimeToSequence(false, csvDelay)
11✔
1907

11✔
1908
        // Finally, OP_CSV requires that the version of the transaction
11✔
1909
        // spending a pkscript with OP_CSV within it *must* be >= 2.
11✔
1910
        sweepTx.Version = 2
11✔
1911

11✔
1912
        // As we mutated the transaction, we'll re-calculate the sighashes for
11✔
1913
        // this instance.
11✔
1914
        signDesc.SigHashes = NewTxSigHashesV0Only(sweepTx)
11✔
1915

11✔
1916
        // With the proper sequence and version set, we'll now sign the timeout
11✔
1917
        // transaction using the passed signed descriptor. In order to generate
11✔
1918
        // a valid signature, then signDesc should be using the base delay
11✔
1919
        // public key, and the proper single tweak bytes.
11✔
1920
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
11✔
1921
        if err != nil {
11✔
1922
                return nil, err
×
1923
        }
×
1924

1925
        // We set a zero as the first element the witness stack (ignoring the
1926
        // witness script), in order to force execution to the second portion
1927
        // of the if clause.
1928
        witnessStack := wire.TxWitness(make([][]byte, 3))
11✔
1929
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
11✔
1930
        witnessStack[1] = nil
11✔
1931
        witnessStack[2] = signDesc.WitnessScript
11✔
1932

11✔
1933
        return witnessStack, nil
11✔
1934
}
1935

1936
// HtlcSpendRevoke spends a second-level HTLC output. This function is to be
1937
// used by the sender or receiver of an HTLC to claim the HTLC after a revoked
1938
// commitment transaction was broadcast.
1939
func HtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
1940
        revokeTx *wire.MsgTx) (wire.TxWitness, error) {
16✔
1941

16✔
1942
        // We don't need any spacial modifications to the transaction as this
16✔
1943
        // is just sweeping a revoked HTLC output. So we'll generate a regular
16✔
1944
        // witness signature.
16✔
1945
        sweepSig, err := signer.SignOutputRaw(revokeTx, signDesc)
16✔
1946
        if err != nil {
16✔
1947
                return nil, err
×
1948
        }
×
1949

1950
        // We set a one as the first element the witness stack (ignoring the
1951
        // witness script), in order to force execution to the revocation
1952
        // clause in the second level HTLC script.
1953
        witnessStack := wire.TxWitness(make([][]byte, 3))
16✔
1954
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
16✔
1955
        witnessStack[1] = []byte{1}
16✔
1956
        witnessStack[2] = signDesc.WitnessScript
16✔
1957

16✔
1958
        return witnessStack, nil
16✔
1959
}
1960

1961
// HtlcSecondLevelSpend exposes the public witness generation function for
1962
// spending an HTLC success transaction, either due to an expiring time lock or
1963
// having had the payment preimage. This method is able to spend any
1964
// second-level HTLC transaction, assuming the caller sets the locktime or
1965
// seqno properly.
1966
//
1967
// NOTE: The caller MUST set the txn version, sequence number, and sign
1968
// descriptor's sig hash cache before invocation.
1969
func HtlcSecondLevelSpend(signer Signer, signDesc *SignDescriptor,
1970
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
3✔
1971

3✔
1972
        // With the proper sequence and version set, we'll now sign the timeout
3✔
1973
        // transaction using the passed signed descriptor. In order to generate
3✔
1974
        // a valid signature, then signDesc should be using the base delay
3✔
1975
        // public key, and the proper single tweak bytes.
3✔
1976
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
3✔
1977
        if err != nil {
3✔
1978
                return nil, err
×
1979
        }
×
1980

1981
        // We set a zero as the first element the witness stack (ignoring the
1982
        // witness script), in order to force execution to the second portion
1983
        // of the if clause.
1984
        witnessStack := wire.TxWitness(make([][]byte, 3))
3✔
1985
        witnessStack[0] = append(sweepSig.Serialize(), byte(txscript.SigHashAll))
3✔
1986
        witnessStack[1] = nil
3✔
1987
        witnessStack[2] = signDesc.WitnessScript
3✔
1988

3✔
1989
        return witnessStack, nil
3✔
1990
}
1991

1992
// LockTimeToSequence converts the passed relative locktime to a sequence
1993
// number in accordance to BIP-68.
1994
// See: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki
1995
//   - (Compatibility)
1996
func LockTimeToSequence(isSeconds bool, locktime uint32) uint32 {
26✔
1997
        if !isSeconds {
52✔
1998
                // The locktime is to be expressed in confirmations.
26✔
1999
                return locktime
26✔
2000
        }
26✔
2001

2002
        // Set the 22nd bit which indicates the lock time is in seconds, then
2003
        // shift the locktime over by 9 since the time granularity is in
2004
        // 512-second intervals (2^9). This results in a max lock-time of
2005
        // 33,554,431 seconds, or 1.06 years.
2006
        return SequenceLockTimeSeconds | (locktime >> 9)
×
2007
}
2008

2009
// CommitScriptToSelf constructs the public key script for the output on the
2010
// commitment transaction paying to the "owner" of said commitment transaction.
2011
// If the other party learns of the preimage to the revocation hash, then they
2012
// can claim all the settled funds in the channel, plus the unsettled funds.
2013
//
2014
// Possible Input Scripts:
2015
//
2016
//        REVOKE:     <sig> 1
2017
//        SENDRSWEEP: <sig> <emptyvector>
2018
//
2019
// Output Script:
2020
//
2021
//        OP_IF
2022
//            <revokeKey>
2023
//        OP_ELSE
2024
//            <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
2025
//            <selfKey>
2026
//        OP_ENDIF
2027
//        OP_CHECKSIG
2028
func CommitScriptToSelf(csvTimeout uint32, selfKey, revokeKey *btcec.PublicKey) ([]byte, error) {
12,746✔
2029
        // This script is spendable under two conditions: either the
12,746✔
2030
        // 'csvTimeout' has passed and we can redeem our funds, or they can
12,746✔
2031
        // produce a valid signature with the revocation public key. The
12,746✔
2032
        // revocation public key will *only* be known to the other party if we
12,746✔
2033
        // have divulged the revocation hash, allowing them to homomorphically
12,746✔
2034
        // derive the proper private key which corresponds to the revoke public
12,746✔
2035
        // key.
12,746✔
2036
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
12,746✔
2037
                ToLocalScriptSize,
12,746✔
2038
        ))
12,746✔
2039

12,746✔
2040
        builder.AddOp(txscript.OP_IF)
12,746✔
2041

12,746✔
2042
        // If a valid signature using the revocation key is presented, then
12,746✔
2043
        // allow an immediate spend provided the proper signature.
12,746✔
2044
        builder.AddData(revokeKey.SerializeCompressed())
12,746✔
2045

12,746✔
2046
        builder.AddOp(txscript.OP_ELSE)
12,746✔
2047

12,746✔
2048
        // Otherwise, we can re-claim our funds after a CSV delay of
12,746✔
2049
        // 'csvTimeout' timeout blocks, and a valid signature.
12,746✔
2050
        builder.AddInt64(int64(csvTimeout))
12,746✔
2051
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
12,746✔
2052
        builder.AddOp(txscript.OP_DROP)
12,746✔
2053
        builder.AddData(selfKey.SerializeCompressed())
12,746✔
2054

12,746✔
2055
        builder.AddOp(txscript.OP_ENDIF)
12,746✔
2056

12,746✔
2057
        // Finally, we'll validate the signature against the public key that's
12,746✔
2058
        // left on the top of the stack.
12,746✔
2059
        builder.AddOp(txscript.OP_CHECKSIG)
12,746✔
2060

12,746✔
2061
        return builder.Script()
12,746✔
2062
}
12,746✔
2063

2064
// CommitScriptTree holds the taproot output key (in this case the revocation
2065
// key, or a NUMs point for the remote output) along with the tapscript leaf
2066
// that can spend the output after a delay.
2067
type CommitScriptTree struct {
2068
        ScriptTree
2069

2070
        // SettleLeaf is the leaf used to settle the output after the delay.
2071
        SettleLeaf txscript.TapLeaf
2072

2073
        // RevocationLeaf is the leaf used to spend the output with the
2074
        // revocation key signature.
2075
        RevocationLeaf txscript.TapLeaf
2076
}
2077

2078
// A compile time check to ensure CommitScriptTree implements the
2079
// TapscriptDescriptor interface.
2080
var _ TapscriptDescriptor = (*CommitScriptTree)(nil)
2081

2082
// WitnessScriptToSign returns the witness script that we'll use when signing
2083
// for the remote party, and also verifying signatures on our transactions. As
2084
// an example, when we create an outgoing HTLC for the remote party, we want to
2085
// sign their success path.
2086
func (c *CommitScriptTree) WitnessScriptToSign() []byte {
×
2087
        // TODO(roasbeef): abstraction leak here? always dependent
×
2088
        return nil
×
2089
}
×
2090

2091
// WitnessScriptForPath returns the witness script for the given spending path.
2092
// An error is returned if the path is unknown.
2093
func (c *CommitScriptTree) WitnessScriptForPath(
2094
        path ScriptPath) ([]byte, error) {
5✔
2095

5✔
2096
        switch path {
5✔
2097
        // For the commitment output, the delay and success path are the same,
2098
        // so we'll fall through here to success.
2099
        case ScriptPathDelay:
5✔
2100
                fallthrough
5✔
2101
        case ScriptPathSuccess:
5✔
2102
                return c.SettleLeaf.Script, nil
5✔
2103
        case ScriptPathRevocation:
3✔
2104
                return c.RevocationLeaf.Script, nil
3✔
2105
        default:
×
2106
                return nil, fmt.Errorf("unknown script path: %v", path)
×
2107
        }
2108
}
2109

2110
// CtrlBlockForPath returns the control block for the given spending path. For
2111
// script types that don't have a control block, nil is returned.
2112
func (c *CommitScriptTree) CtrlBlockForPath(
2113
        path ScriptPath) (*txscript.ControlBlock, error) {
5✔
2114

5✔
2115
        switch path {
5✔
2116
        case ScriptPathDelay:
5✔
2117
                fallthrough
5✔
2118
        case ScriptPathSuccess:
5✔
2119
                return lnutils.Ptr(MakeTaprootCtrlBlock(
5✔
2120
                        c.SettleLeaf.Script, c.InternalKey,
5✔
2121
                        c.TapscriptTree,
5✔
2122
                )), nil
5✔
2123
        case ScriptPathRevocation:
3✔
2124
                return lnutils.Ptr(MakeTaprootCtrlBlock(
3✔
2125
                        c.RevocationLeaf.Script, c.InternalKey,
3✔
2126
                        c.TapscriptTree,
3✔
2127
                )), nil
3✔
2128
        default:
×
2129
                return nil, fmt.Errorf("unknown script path: %v", path)
×
2130
        }
2131
}
2132

2133
// Tree returns the underlying ScriptTree of the CommitScriptTree.
NEW
2134
func (c *CommitScriptTree) Tree() ScriptTree {
×
NEW
2135
        return c.ScriptTree
×
NEW
2136
}
×
2137

2138
// NewLocalCommitScriptTree returns a new CommitScript tree that can be used to
2139
// create and spend the commitment output for the local party.
2140
func NewLocalCommitScriptTree(csvTimeout uint32,
2141
        selfKey, revokeKey *btcec.PublicKey) (*CommitScriptTree, error) {
1,344✔
2142

1,344✔
2143
        // First, we'll need to construct the tapLeaf that'll be our delay CSV
1,344✔
2144
        // clause.
1,344✔
2145
        delayScript, err := TaprootLocalCommitDelayScript(csvTimeout, selfKey)
1,344✔
2146
        if err != nil {
1,344✔
2147
                return nil, err
×
2148
        }
×
2149

2150
        // Next, we'll need to construct the revocation path, which is just a
2151
        // simple checksig script.
2152
        revokeScript, err := TaprootLocalCommitRevokeScript(selfKey, revokeKey)
1,344✔
2153
        if err != nil {
1,344✔
2154
                return nil, err
×
2155
        }
×
2156

2157
        // With both scripts computed, we'll now create a tapscript tree with
2158
        // the two leaves, and then obtain a root from that.
2159
        delayTapLeaf := txscript.NewBaseTapLeaf(delayScript)
1,344✔
2160
        revokeTapLeaf := txscript.NewBaseTapLeaf(revokeScript)
1,344✔
2161
        tapScriptTree := txscript.AssembleTaprootScriptTree(
1,344✔
2162
                delayTapLeaf, revokeTapLeaf,
1,344✔
2163
        )
1,344✔
2164
        tapScriptRoot := tapScriptTree.RootNode.TapHash()
1,344✔
2165

1,344✔
2166
        // Now that we have our root, we can arrive at the final output script
1,344✔
2167
        // by tweaking the internal key with this root.
1,344✔
2168
        toLocalOutputKey := txscript.ComputeTaprootOutputKey(
1,344✔
2169
                &TaprootNUMSKey, tapScriptRoot[:],
1,344✔
2170
        )
1,344✔
2171

1,344✔
2172
        return &CommitScriptTree{
1,344✔
2173
                ScriptTree: ScriptTree{
1,344✔
2174
                        TaprootKey:    toLocalOutputKey,
1,344✔
2175
                        TapscriptTree: tapScriptTree,
1,344✔
2176
                        TapscriptRoot: tapScriptRoot[:],
1,344✔
2177
                        InternalKey:   &TaprootNUMSKey,
1,344✔
2178
                },
1,344✔
2179
                SettleLeaf:     delayTapLeaf,
1,344✔
2180
                RevocationLeaf: revokeTapLeaf,
1,344✔
2181
        }, nil
1,344✔
2182
}
2183

2184
// TaprootLocalCommitDelayScript builds the tap leaf with the CSV delay script
2185
// for the to-local output.
2186
func TaprootLocalCommitDelayScript(csvTimeout uint32,
2187
        selfKey *btcec.PublicKey) ([]byte, error) {
1,344✔
2188

1,344✔
2189
        builder := txscript.NewScriptBuilder()
1,344✔
2190
        builder.AddData(schnorr.SerializePubKey(selfKey))
1,344✔
2191
        builder.AddOp(txscript.OP_CHECKSIG)
1,344✔
2192
        builder.AddInt64(int64(csvTimeout))
1,344✔
2193
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
1,344✔
2194
        builder.AddOp(txscript.OP_DROP)
1,344✔
2195

1,344✔
2196
        return builder.Script()
1,344✔
2197
}
1,344✔
2198

2199
// TaprootLocalCommitRevokeScript builds the tap leaf with the revocation path
2200
// for the to-local output.
2201
func TaprootLocalCommitRevokeScript(selfKey, revokeKey *btcec.PublicKey) (
2202
        []byte, error) {
1,346✔
2203

1,346✔
2204
        builder := txscript.NewScriptBuilder()
1,346✔
2205
        builder.AddData(schnorr.SerializePubKey(selfKey))
1,346✔
2206
        builder.AddOp(txscript.OP_DROP)
1,346✔
2207
        builder.AddData(schnorr.SerializePubKey(revokeKey))
1,346✔
2208
        builder.AddOp(txscript.OP_CHECKSIG)
1,346✔
2209

1,346✔
2210
        return builder.Script()
1,346✔
2211
}
1,346✔
2212

2213
// TaprootCommitScriptToSelf creates the taproot witness program that commits
2214
// to the revocation (script path) and delay path (script path) in a single
2215
// taproot output key. Both the delay script and the revocation script are part
2216
// of the tapscript tree to ensure that the internal key (the local delay key)
2217
// is always revealed.  This ensures that a 3rd party can always sweep the set
2218
// of anchor outputs.
2219
//
2220
// For the delay path we have the following tapscript leaf script:
2221
//
2222
//        <local_delayedpubkey> OP_CHECKSIG
2223
//        <to_self_delay> OP_CHECKSEQUENCEVERIFY OP_DROP
2224
//
2225
// This can then be spent with just:
2226
//
2227
//        <local_delayedsig> <to_delay_script> <delay_control_block>
2228
//
2229
// Where the to_delay_script is listed above, and the delay_control_block
2230
// computed as:
2231
//
2232
//        delay_control_block = (output_key_y_parity | 0xc0) || taproot_nums_key
2233
//
2234
// The revocation path is simply:
2235
//
2236
//        <local_delayedpubkey> OP_DROP
2237
//        <revocationkey> OP_CHECKSIG
2238
//
2239
// The revocation path can be spent with a control block similar to the above
2240
// (but contains the hash of the other script), and with the following witness:
2241
//
2242
//        <revocation_sig>
2243
//
2244
// We use a noop data push to ensure that the local public key is also revealed
2245
// on chain, which enables the anchor output to be swept.
2246
func TaprootCommitScriptToSelf(csvTimeout uint32,
2247
        selfKey, revokeKey *btcec.PublicKey) (*btcec.PublicKey, error) {
×
2248

×
2249
        commitScriptTree, err := NewLocalCommitScriptTree(
×
2250
                csvTimeout, selfKey, revokeKey,
×
2251
        )
×
2252
        if err != nil {
×
2253
                return nil, err
×
2254
        }
×
2255

2256
        return commitScriptTree.TaprootKey, nil
×
2257
}
2258

2259
// MakeTaprootCtrlBlock takes a leaf script, the internal key (usually the
2260
// revoke key), and a script tree and creates a valid control block for a spend
2261
// of the leaf.
2262
func MakeTaprootCtrlBlock(leafScript []byte, internalKey *btcec.PublicKey,
2263
        scriptTree *txscript.IndexedTapScriptTree) txscript.ControlBlock {
67✔
2264

67✔
2265
        tapLeafHash := txscript.NewBaseTapLeaf(leafScript).TapHash()
67✔
2266
        scriptIdx := scriptTree.LeafProofIndex[tapLeafHash]
67✔
2267
        settleMerkleProof := scriptTree.LeafMerkleProofs[scriptIdx]
67✔
2268

67✔
2269
        return settleMerkleProof.ToControlBlock(internalKey)
67✔
2270
}
67✔
2271

2272
// TaprootCommitSpendSuccess constructs a valid witness allowing a node to
2273
// sweep the settled taproot output after the delay has passed for a force
2274
// close.
2275
func TaprootCommitSpendSuccess(signer Signer, signDesc *SignDescriptor,
2276
        sweepTx *wire.MsgTx,
2277
        scriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error) {
9✔
2278

9✔
2279
        // First, we'll need to construct a valid control block to execute the
9✔
2280
        // leaf script for sweep settlement.
9✔
2281
        //
9✔
2282
        // TODO(roasbeef); make into closure instead? only need reovke key and
9✔
2283
        // scriptTree to make the ctrl block -- then default version that would
9✔
2284
        // take froms ign desc?
9✔
2285
        var ctrlBlockBytes []byte
9✔
2286
        if signDesc.ControlBlock == nil {
15✔
2287
                settleControlBlock := MakeTaprootCtrlBlock(
6✔
2288
                        signDesc.WitnessScript, &TaprootNUMSKey, scriptTree,
6✔
2289
                )
6✔
2290
                ctrlBytes, err := settleControlBlock.ToBytes()
6✔
2291
                if err != nil {
6✔
2292
                        return nil, err
×
2293
                }
×
2294

2295
                ctrlBlockBytes = ctrlBytes
6✔
2296
        } else {
3✔
2297
                ctrlBlockBytes = signDesc.ControlBlock
3✔
2298
        }
3✔
2299

2300
        // With the control block created, we'll now generate the signature we
2301
        // need to authorize the spend.
2302
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
9✔
2303
        if err != nil {
9✔
2304
                return nil, err
×
2305
        }
×
2306

2307
        // The final witness stack will be:
2308
        //
2309
        //  <sweep sig> <sweep script> <control block>
2310
        witnessStack := make(wire.TxWitness, 3)
9✔
2311
        witnessStack[0] = maybeAppendSighash(sweepSig, signDesc.HashType)
9✔
2312
        witnessStack[1] = signDesc.WitnessScript
9✔
2313
        witnessStack[2] = ctrlBlockBytes
9✔
2314

9✔
2315
        return witnessStack, nil
9✔
2316
}
2317

2318
// TaprootCommitSpendRevoke constructs a valid witness allowing a node to sweep
2319
// the revoked taproot output of a malicious peer.
2320
func TaprootCommitSpendRevoke(signer Signer, signDesc *SignDescriptor,
2321
        revokeTx *wire.MsgTx,
2322
        scriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error) {
692✔
2323

692✔
2324
        // First, we'll need to construct a valid control block to execute the
692✔
2325
        // leaf script for revocation path.
692✔
2326
        var ctrlBlockBytes []byte
692✔
2327
        if signDesc.ControlBlock == nil {
697✔
2328
                revokeCtrlBlock := MakeTaprootCtrlBlock(
5✔
2329
                        signDesc.WitnessScript, &TaprootNUMSKey, scriptTree,
5✔
2330
                )
5✔
2331
                revokeBytes, err := revokeCtrlBlock.ToBytes()
5✔
2332
                if err != nil {
5✔
2333
                        return nil, err
×
2334
                }
×
2335

2336
                ctrlBlockBytes = revokeBytes
5✔
2337
        } else {
687✔
2338
                ctrlBlockBytes = signDesc.ControlBlock
687✔
2339
        }
687✔
2340

2341
        // With the control block created, we'll now generate the signature we
2342
        // need to authorize the spend.
2343
        revokeSig, err := signer.SignOutputRaw(revokeTx, signDesc)
692✔
2344
        if err != nil {
692✔
2345
                return nil, err
×
2346
        }
×
2347

2348
        // The final witness stack will be:
2349
        //
2350
        //  <revoke sig sig> <revoke script> <control block>
2351
        witnessStack := make(wire.TxWitness, 3)
692✔
2352
        witnessStack[0] = maybeAppendSighash(revokeSig, signDesc.HashType)
692✔
2353
        witnessStack[1] = signDesc.WitnessScript
692✔
2354
        witnessStack[2] = ctrlBlockBytes
692✔
2355

692✔
2356
        return witnessStack, nil
692✔
2357
}
2358

2359
// LeaseCommitScriptToSelf constructs the public key script for the output on the
2360
// commitment transaction paying to the "owner" of said commitment transaction.
2361
// If the other party learns of the preimage to the revocation hash, then they
2362
// can claim all the settled funds in the channel, plus the unsettled funds.
2363
//
2364
// Possible Input Scripts:
2365
//
2366
//        REVOKE:     <sig> 1
2367
//        SENDRSWEEP: <sig> <emptyvector>
2368
//
2369
// Output Script:
2370
//
2371
//        OP_IF
2372
//            <revokeKey>
2373
//        OP_ELSE
2374
//            <absoluteLeaseExpiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
2375
//            <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
2376
//            <selfKey>
2377
//        OP_ENDIF
2378
//        OP_CHECKSIG
2379
func LeaseCommitScriptToSelf(selfKey, revokeKey *btcec.PublicKey,
2380
        csvTimeout, leaseExpiry uint32) ([]byte, error) {
5✔
2381

5✔
2382
        // This script is spendable under two conditions: either the
5✔
2383
        // 'csvTimeout' has passed and we can redeem our funds, or they can
5✔
2384
        // produce a valid signature with the revocation public key. The
5✔
2385
        // revocation public key will *only* be known to the other party if we
5✔
2386
        // have divulged the revocation hash, allowing them to homomorphically
5✔
2387
        // derive the proper private key which corresponds to the revoke public
5✔
2388
        // key.
5✔
2389
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
5✔
2390
                ToLocalScriptSize + LeaseWitnessScriptSizeOverhead,
5✔
2391
        ))
5✔
2392

5✔
2393
        builder.AddOp(txscript.OP_IF)
5✔
2394

5✔
2395
        // If a valid signature using the revocation key is presented, then
5✔
2396
        // allow an immediate spend provided the proper signature.
5✔
2397
        builder.AddData(revokeKey.SerializeCompressed())
5✔
2398

5✔
2399
        builder.AddOp(txscript.OP_ELSE)
5✔
2400

5✔
2401
        // Otherwise, we can re-claim our funds after once the CLTV lease
5✔
2402
        // maturity has been met, along with the CSV delay of 'csvTimeout'
5✔
2403
        // timeout blocks, and a valid signature.
5✔
2404
        builder.AddInt64(int64(leaseExpiry))
5✔
2405
        builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
5✔
2406
        builder.AddOp(txscript.OP_DROP)
5✔
2407

5✔
2408
        builder.AddInt64(int64(csvTimeout))
5✔
2409
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
5✔
2410
        builder.AddOp(txscript.OP_DROP)
5✔
2411

5✔
2412
        builder.AddData(selfKey.SerializeCompressed())
5✔
2413

5✔
2414
        builder.AddOp(txscript.OP_ENDIF)
5✔
2415

5✔
2416
        // Finally, we'll validate the signature against the public key that's
5✔
2417
        // left on the top of the stack.
5✔
2418
        builder.AddOp(txscript.OP_CHECKSIG)
5✔
2419

5✔
2420
        return builder.Script()
5✔
2421
}
5✔
2422

2423
// CommitSpendTimeout constructs a valid witness allowing the owner of a
2424
// particular commitment transaction to spend the output returning settled
2425
// funds back to themselves after a relative block timeout.  In order to
2426
// properly spend the transaction, the target input's sequence number should be
2427
// set accordingly based off of the target relative block timeout within the
2428
// redeem script.  Additionally, OP_CSV requires that the version of the
2429
// transaction spending a pkscript with OP_CSV within it *must* be >= 2.
2430
func CommitSpendTimeout(signer Signer, signDesc *SignDescriptor,
2431
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
9✔
2432

9✔
2433
        // Ensure the transaction version supports the validation of sequence
9✔
2434
        // locks and CSV semantics.
9✔
2435
        if sweepTx.Version < 2 {
9✔
2436
                return nil, fmt.Errorf("version of passed transaction MUST "+
×
2437
                        "be >= 2, not %v", sweepTx.Version)
×
2438
        }
×
2439

2440
        // With the sequence number in place, we're now able to properly sign
2441
        // off on the sweep transaction.
2442
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
9✔
2443
        if err != nil {
9✔
2444
                return nil, err
×
2445
        }
×
2446

2447
        // Place an empty byte as the first item in the evaluated witness stack
2448
        // to force script execution to the timeout spend clause. We need to
2449
        // place an empty byte in order to ensure our script is still valid
2450
        // from the PoV of nodes that are enforcing minimal OP_IF/OP_NOTIF.
2451
        witnessStack := wire.TxWitness(make([][]byte, 3))
9✔
2452
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
9✔
2453
        witnessStack[1] = nil
9✔
2454
        witnessStack[2] = signDesc.WitnessScript
9✔
2455

9✔
2456
        return witnessStack, nil
9✔
2457
}
2458

2459
// CommitSpendRevoke constructs a valid witness allowing a node to sweep the
2460
// settled output of a malicious counterparty who broadcasts a revoked
2461
// commitment transaction.
2462
//
2463
// NOTE: The passed SignDescriptor should include the raw (untweaked)
2464
// revocation base public key of the receiver and also the proper double tweak
2465
// value based on the commitment secret of the revoked commitment.
2466
func CommitSpendRevoke(signer Signer, signDesc *SignDescriptor,
2467
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
40✔
2468

40✔
2469
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
40✔
2470
        if err != nil {
40✔
2471
                return nil, err
×
2472
        }
×
2473

2474
        // Place a 1 as the first item in the evaluated witness stack to
2475
        // force script execution to the revocation clause.
2476
        witnessStack := wire.TxWitness(make([][]byte, 3))
40✔
2477
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
40✔
2478
        witnessStack[1] = []byte{1}
40✔
2479
        witnessStack[2] = signDesc.WitnessScript
40✔
2480

40✔
2481
        return witnessStack, nil
40✔
2482
}
2483

2484
// CommitSpendNoDelay constructs a valid witness allowing a node to spend their
2485
// settled no-delay output on the counterparty's commitment transaction. If the
2486
// tweakless field is true, then we'll omit the set where we tweak the pubkey
2487
// with a random set of bytes, and use it directly in the witness stack.
2488
//
2489
// NOTE: The passed SignDescriptor should include the raw (untweaked) public
2490
// key of the receiver and also the proper single tweak value based on the
2491
// current commitment point.
2492
func CommitSpendNoDelay(signer Signer, signDesc *SignDescriptor,
2493
        sweepTx *wire.MsgTx, tweakless bool) (wire.TxWitness, error) {
36✔
2494

36✔
2495
        if signDesc.KeyDesc.PubKey == nil {
36✔
2496
                return nil, fmt.Errorf("cannot generate witness with nil " +
×
2497
                        "KeyDesc pubkey")
×
2498
        }
×
2499

2500
        // This is just a regular p2wkh spend which looks something like:
2501
        //  * witness: <sig> <pubkey>
2502
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
36✔
2503
        if err != nil {
36✔
2504
                return nil, err
×
2505
        }
×
2506

2507
        // Finally, we'll manually craft the witness. The witness here is the
2508
        // exact same as a regular p2wkh witness, depending on the value of the
2509
        // tweakless bool.
2510
        witness := make([][]byte, 2)
36✔
2511
        witness[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
36✔
2512

36✔
2513
        switch tweakless {
36✔
2514
        // If we're tweaking the key, then we use the tweaked public key as the
2515
        // last item in the witness stack which was originally used to created
2516
        // the pkScript we're spending.
2517
        case false:
11✔
2518
                witness[1] = TweakPubKeyWithTweak(
11✔
2519
                        signDesc.KeyDesc.PubKey, signDesc.SingleTweak,
11✔
2520
                ).SerializeCompressed()
11✔
2521

2522
        // Otherwise, we can just use the raw pubkey, since there's no random
2523
        // value to be combined.
2524
        case true:
28✔
2525
                witness[1] = signDesc.KeyDesc.PubKey.SerializeCompressed()
28✔
2526
        }
2527

2528
        return witness, nil
36✔
2529
}
2530

2531
// CommitScriptUnencumbered constructs the public key script on the commitment
2532
// transaction paying to the "other" party. The constructed output is a normal
2533
// p2wkh output spendable immediately, requiring no contestation period.
2534
func CommitScriptUnencumbered(key *btcec.PublicKey) ([]byte, error) {
12,446✔
2535
        // This script goes to the "other" party, and is spendable immediately.
12,446✔
2536
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
12,446✔
2537
                P2WPKHSize,
12,446✔
2538
        ))
12,446✔
2539
        builder.AddOp(txscript.OP_0)
12,446✔
2540
        builder.AddData(btcutil.Hash160(key.SerializeCompressed()))
12,446✔
2541

12,446✔
2542
        return builder.Script()
12,446✔
2543
}
12,446✔
2544

2545
// CommitScriptToRemoteConfirmed constructs the script for the output on the
2546
// commitment transaction paying to the remote party of said commitment
2547
// transaction. The money can only be spend after one confirmation.
2548
//
2549
// Possible Input Scripts:
2550
//
2551
//        SWEEP: <sig>
2552
//
2553
// Output Script:
2554
//
2555
//        <key> OP_CHECKSIGVERIFY
2556
//        1 OP_CHECKSEQUENCEVERIFY
2557
func CommitScriptToRemoteConfirmed(key *btcec.PublicKey) ([]byte, error) {
251✔
2558
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
251✔
2559
                ToRemoteConfirmedScriptSize,
251✔
2560
        ))
251✔
2561

251✔
2562
        // Only the given key can spend the output.
251✔
2563
        builder.AddData(key.SerializeCompressed())
251✔
2564
        builder.AddOp(txscript.OP_CHECKSIGVERIFY)
251✔
2565

251✔
2566
        // Check that the it has one confirmation.
251✔
2567
        builder.AddOp(txscript.OP_1)
251✔
2568
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
251✔
2569

251✔
2570
        return builder.Script()
251✔
2571
}
251✔
2572

2573
// NewRemoteCommitScriptTree constructs a new script tree for the remote party
2574
// to sweep their funds after a hard coded 1 block delay.
2575
func NewRemoteCommitScriptTree(remoteKey *btcec.PublicKey,
2576
) (*CommitScriptTree, error) {
648✔
2577

648✔
2578
        // First, construct the remote party's tapscript they'll use to sweep
648✔
2579
        // their outputs.
648✔
2580
        builder := txscript.NewScriptBuilder()
648✔
2581
        builder.AddData(schnorr.SerializePubKey(remoteKey))
648✔
2582
        builder.AddOp(txscript.OP_CHECKSIG)
648✔
2583
        builder.AddOp(txscript.OP_1)
648✔
2584
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
648✔
2585
        builder.AddOp(txscript.OP_DROP)
648✔
2586

648✔
2587
        remoteScript, err := builder.Script()
648✔
2588
        if err != nil {
648✔
2589
                return nil, err
×
2590
        }
×
2591

2592
        // With this script constructed, we'll map that into a tapLeaf, then
2593
        // make a new tapscript root from that.
2594
        tapLeaf := txscript.NewBaseTapLeaf(remoteScript)
648✔
2595
        tapScriptTree := txscript.AssembleTaprootScriptTree(tapLeaf)
648✔
2596
        tapScriptRoot := tapScriptTree.RootNode.TapHash()
648✔
2597

648✔
2598
        // Now that we have our root, we can arrive at the final output script
648✔
2599
        // by tweaking the internal key with this root.
648✔
2600
        toRemoteOutputKey := txscript.ComputeTaprootOutputKey(
648✔
2601
                &TaprootNUMSKey, tapScriptRoot[:],
648✔
2602
        )
648✔
2603

648✔
2604
        return &CommitScriptTree{
648✔
2605
                ScriptTree: ScriptTree{
648✔
2606
                        TaprootKey:    toRemoteOutputKey,
648✔
2607
                        TapscriptTree: tapScriptTree,
648✔
2608
                        TapscriptRoot: tapScriptRoot[:],
648✔
2609
                        InternalKey:   &TaprootNUMSKey,
648✔
2610
                },
648✔
2611
                SettleLeaf: tapLeaf,
648✔
2612
        }, nil
648✔
2613
}
2614

2615
// TaprootCommitScriptToRemote constructs a taproot witness program for the
2616
// output on the commitment transaction for the remote party. For the top level
2617
// key spend, we'll use a NUMs key to ensure that only the script path can be
2618
// taken. Using a set NUMs key here also means that recovery solutions can scan
2619
// the chain given knowledge of the public key for the remote party. We then
2620
// commit to a single tapscript leaf that holds the normal CSV 1 delay
2621
// script.
2622
//
2623
// Our single tapleaf will use the following script:
2624
//
2625
//        <remotepubkey> OP_CHECKSIG
2626
//        1 OP_CHECKSEQUENCEVERIFY OP_DROP
2627
func TaprootCommitScriptToRemote(remoteKey *btcec.PublicKey,
2628
) (*btcec.PublicKey, error) {
×
2629

×
2630
        commitScriptTree, err := NewRemoteCommitScriptTree(remoteKey)
×
2631
        if err != nil {
×
2632
                return nil, err
×
2633
        }
×
2634

2635
        return commitScriptTree.TaprootKey, nil
×
2636
}
2637

2638
// TaprootCommitRemoteSpend allows the remote party to sweep their output into
2639
// their wallet after an enforced 1 block delay.
2640
func TaprootCommitRemoteSpend(signer Signer, signDesc *SignDescriptor,
2641
        sweepTx *wire.MsgTx,
2642
        scriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error) {
693✔
2643

693✔
2644
        // First, we'll need to construct a valid control block to execute the
693✔
2645
        // leaf script for sweep settlement.
693✔
2646
        var ctrlBlockBytes []byte
693✔
2647
        if signDesc.ControlBlock == nil {
700✔
2648
                settleControlBlock := MakeTaprootCtrlBlock(
7✔
2649
                        signDesc.WitnessScript, &TaprootNUMSKey, scriptTree,
7✔
2650
                )
7✔
2651
                ctrlBytes, err := settleControlBlock.ToBytes()
7✔
2652
                if err != nil {
7✔
2653
                        return nil, err
×
2654
                }
×
2655

2656
                ctrlBlockBytes = ctrlBytes
7✔
2657
        } else {
686✔
2658
                ctrlBlockBytes = signDesc.ControlBlock
686✔
2659
        }
686✔
2660

2661
        // With the control block created, we'll now generate the signature we
2662
        // need to authorize the spend.
2663
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
693✔
2664
        if err != nil {
693✔
2665
                return nil, err
×
2666
        }
×
2667

2668
        // The final witness stack will be:
2669
        //
2670
        //  <sweep sig> <sweep script> <control block>
2671
        witnessStack := make(wire.TxWitness, 3)
693✔
2672
        witnessStack[0] = maybeAppendSighash(sweepSig, signDesc.HashType)
693✔
2673
        witnessStack[1] = signDesc.WitnessScript
693✔
2674
        witnessStack[2] = ctrlBlockBytes
693✔
2675

693✔
2676
        return witnessStack, nil
693✔
2677
}
2678

2679
// LeaseCommitScriptToRemoteConfirmed constructs the script for the output on
2680
// the commitment transaction paying to the remote party of said commitment
2681
// transaction. The money can only be spend after one confirmation.
2682
//
2683
// Possible Input Scripts:
2684
//
2685
//        SWEEP: <sig>
2686
//
2687
// Output Script:
2688
//
2689
//                <key> OP_CHECKSIGVERIFY
2690
//             <lease maturity in blocks> OP_CHECKLOCKTIMEVERIFY OP_DROP
2691
//                1 OP_CHECKSEQUENCEVERIFY
2692
func LeaseCommitScriptToRemoteConfirmed(key *btcec.PublicKey,
2693
        leaseExpiry uint32) ([]byte, error) {
5✔
2694

5✔
2695
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(45))
5✔
2696

5✔
2697
        // Only the given key can spend the output.
5✔
2698
        builder.AddData(key.SerializeCompressed())
5✔
2699
        builder.AddOp(txscript.OP_CHECKSIGVERIFY)
5✔
2700

5✔
2701
        // The channel initiator always has the additional channel lease
5✔
2702
        // expiration constraint for outputs that pay to them which must be
5✔
2703
        // satisfied.
5✔
2704
        builder.AddInt64(int64(leaseExpiry))
5✔
2705
        builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
5✔
2706
        builder.AddOp(txscript.OP_DROP)
5✔
2707

5✔
2708
        // Check that it has one confirmation.
5✔
2709
        builder.AddOp(txscript.OP_1)
5✔
2710
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
5✔
2711

5✔
2712
        return builder.Script()
5✔
2713
}
5✔
2714

2715
// CommitSpendToRemoteConfirmed constructs a valid witness allowing a node to
2716
// spend their settled output on the counterparty's commitment transaction when
2717
// it has one confirmetion. This is used for the anchor channel type. The
2718
// spending key will always be non-tweaked for this output type.
2719
func CommitSpendToRemoteConfirmed(signer Signer, signDesc *SignDescriptor,
2720
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
15✔
2721

15✔
2722
        if signDesc.KeyDesc.PubKey == nil {
15✔
2723
                return nil, fmt.Errorf("cannot generate witness with nil " +
×
2724
                        "KeyDesc pubkey")
×
2725
        }
×
2726

2727
        // Similar to non delayed output, only a signature is needed.
2728
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
15✔
2729
        if err != nil {
15✔
2730
                return nil, err
×
2731
        }
×
2732

2733
        // Finally, we'll manually craft the witness. The witness here is the
2734
        // signature and the redeem script.
2735
        witnessStack := make([][]byte, 2)
15✔
2736
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
15✔
2737
        witnessStack[1] = signDesc.WitnessScript
15✔
2738

15✔
2739
        return witnessStack, nil
15✔
2740
}
2741

2742
// CommitScriptAnchor constructs the script for the anchor output spendable by
2743
// the given key immediately, or by anyone after 16 confirmations.
2744
//
2745
// Possible Input Scripts:
2746
//
2747
//        By owner:                                <sig>
2748
//        By anyone (after 16 conf):        <emptyvector>
2749
//
2750
// Output Script:
2751
//
2752
//        <funding_pubkey> OP_CHECKSIG OP_IFDUP
2753
//        OP_NOTIF
2754
//          OP_16 OP_CSV
2755
//        OP_ENDIF
2756
func CommitScriptAnchor(key *btcec.PublicKey) ([]byte, error) {
453✔
2757
        builder := txscript.NewScriptBuilder(txscript.WithScriptAllocSize(
453✔
2758
                AnchorScriptSize,
453✔
2759
        ))
453✔
2760

453✔
2761
        // Spend immediately with key.
453✔
2762
        builder.AddData(key.SerializeCompressed())
453✔
2763
        builder.AddOp(txscript.OP_CHECKSIG)
453✔
2764

453✔
2765
        // Duplicate the value if true, since it will be consumed by the NOTIF.
453✔
2766
        builder.AddOp(txscript.OP_IFDUP)
453✔
2767

453✔
2768
        // Otherwise spendable by anyone after 16 confirmations.
453✔
2769
        builder.AddOp(txscript.OP_NOTIF)
453✔
2770
        builder.AddOp(txscript.OP_16)
453✔
2771
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
453✔
2772
        builder.AddOp(txscript.OP_ENDIF)
453✔
2773

453✔
2774
        return builder.Script()
453✔
2775
}
453✔
2776

2777
// AnchorScriptTree holds all the contents needed to sweep a taproot anchor
2778
// output on chain.
2779
type AnchorScriptTree struct {
2780
        ScriptTree
2781

2782
        // SweepLeaf is the leaf used to settle the output after the delay.
2783
        SweepLeaf txscript.TapLeaf
2784
}
2785

2786
// NewAnchorScriptTree makes a new script tree for an anchor output with the
2787
// passed anchor key.
2788
func NewAnchorScriptTree(
2789
        anchorKey *btcec.PublicKey) (*AnchorScriptTree, error) {
155✔
2790

155✔
2791
        // The main script used is just a OP_16 CSV (anyone can sweep after 16
155✔
2792
        // blocks).
155✔
2793
        builder := txscript.NewScriptBuilder()
155✔
2794
        builder.AddOp(txscript.OP_16)
155✔
2795
        builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
155✔
2796

155✔
2797
        anchorScript, err := builder.Script()
155✔
2798
        if err != nil {
155✔
2799
                return nil, err
×
2800
        }
×
2801

2802
        // With the script, we can make our sole leaf, then derive the root
2803
        // from that.
2804
        tapLeaf := txscript.NewBaseTapLeaf(anchorScript)
155✔
2805
        tapScriptTree := txscript.AssembleTaprootScriptTree(tapLeaf)
155✔
2806
        tapScriptRoot := tapScriptTree.RootNode.TapHash()
155✔
2807

155✔
2808
        // Now that we have our root, we can arrive at the final output script
155✔
2809
        // by tweaking the internal key with this root.
155✔
2810
        anchorOutputKey := txscript.ComputeTaprootOutputKey(
155✔
2811
                anchorKey, tapScriptRoot[:],
155✔
2812
        )
155✔
2813

155✔
2814
        return &AnchorScriptTree{
155✔
2815
                ScriptTree: ScriptTree{
155✔
2816
                        TaprootKey:    anchorOutputKey,
155✔
2817
                        TapscriptTree: tapScriptTree,
155✔
2818
                        TapscriptRoot: tapScriptRoot[:],
155✔
2819
                        InternalKey:   anchorKey,
155✔
2820
                },
155✔
2821
                SweepLeaf: tapLeaf,
155✔
2822
        }, nil
155✔
2823
}
2824

2825
// WitnessScriptToSign returns the witness script that we'll use when signing
2826
// for the remote party, and also verifying signatures on our transactions. As
2827
// an example, when we create an outgoing HTLC for the remote party, we want to
2828
// sign their success path.
2829
func (a *AnchorScriptTree) WitnessScriptToSign() []byte {
×
2830
        return a.SweepLeaf.Script
×
2831
}
×
2832

2833
// WitnessScriptForPath returns the witness script for the given spending path.
2834
// An error is returned if the path is unknown.
2835
func (a *AnchorScriptTree) WitnessScriptForPath(
2836
        path ScriptPath) ([]byte, error) {
7✔
2837

7✔
2838
        switch path {
7✔
2839
        case ScriptPathDelay:
×
2840
                fallthrough
×
2841
        case ScriptPathSuccess:
7✔
2842
                return a.SweepLeaf.Script, nil
7✔
2843

2844
        default:
×
2845
                return nil, fmt.Errorf("unknown script path: %v", path)
×
2846
        }
2847
}
2848

2849
// CtrlBlockForPath returns the control block for the given spending path. For
2850
// script types that don't have a control block, nil is returned.
2851
func (a *AnchorScriptTree) CtrlBlockForPath(
NEW
2852
        path ScriptPath) (*txscript.ControlBlock, error) {
×
2853

×
2854
        switch path {
×
2855
        case ScriptPathDelay:
×
2856
                fallthrough
×
2857
        case ScriptPathSuccess:
×
2858
                return lnutils.Ptr(MakeTaprootCtrlBlock(
×
2859
                        a.SweepLeaf.Script, a.InternalKey,
×
2860
                        a.TapscriptTree,
×
2861
                )), nil
×
2862

2863
        default:
×
2864
                return nil, fmt.Errorf("unknown script path: %v", path)
×
2865
        }
2866
}
2867

2868
// Tree returns the underlying ScriptTree of the AnchorScriptTree.
NEW
2869
func (a *AnchorScriptTree) Tree() ScriptTree {
×
NEW
2870
        return a.ScriptTree
×
NEW
2871
}
×
2872

2873
// A compile time check to ensure AnchorScriptTree implements the
2874
// TapscriptDescriptor interface.
2875
var _ TapscriptDescriptor = (*AnchorScriptTree)(nil)
2876

2877
// TaprootOutputKeyAnchor returns the segwit v1 (taproot) witness program that
2878
// encodes the anchor output spending conditions: the passed key can be used
2879
// for keyspend, with the OP_CSV 16 clause living within an internal tapscript
2880
// leaf.
2881
//
2882
// Spend paths:
2883
//   - Key spend: <key_signature>
2884
//   - Script spend: OP_16 CSV <control_block>
2885
func TaprootOutputKeyAnchor(key *btcec.PublicKey) (*btcec.PublicKey, error) {
×
2886
        anchorScriptTree, err := NewAnchorScriptTree(key)
×
2887
        if err != nil {
×
2888
                return nil, err
×
2889
        }
×
2890

2891
        return anchorScriptTree.TaprootKey, nil
×
2892
}
2893

2894
// TaprootAnchorSpend constructs a valid witness allowing a node to sweep their
2895
// anchor output.
2896
func TaprootAnchorSpend(signer Signer, signDesc *SignDescriptor,
2897
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
8✔
2898

8✔
2899
        // For this spend type, we only need a single signature which'll be a
8✔
2900
        // keyspend using the anchor private key.
8✔
2901
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
8✔
2902
        if err != nil {
8✔
2903
                return nil, err
×
2904
        }
×
2905

2906
        // The witness stack in this case is pretty simple: we only need to
2907
        // specify the signature generated.
2908
        witnessStack := make(wire.TxWitness, 1)
8✔
2909
        witnessStack[0] = maybeAppendSighash(sweepSig, signDesc.HashType)
8✔
2910

8✔
2911
        return witnessStack, nil
8✔
2912
}
2913

2914
// TaprootAnchorSpendAny constructs a valid witness allowing anyone to sweep
2915
// the anchor output after 16 blocks.
2916
func TaprootAnchorSpendAny(anchorKey *btcec.PublicKey) (wire.TxWitness, error) {
2✔
2917
        anchorScriptTree, err := NewAnchorScriptTree(anchorKey)
2✔
2918
        if err != nil {
2✔
2919
                return nil, err
×
2920
        }
×
2921

2922
        // For this spend, the only thing we need to do is create a valid
2923
        // control block. Other than that, there're no restrictions to how the
2924
        // output can be spent.
2925
        scriptTree := anchorScriptTree.TapscriptTree
2✔
2926
        sweepLeaf := anchorScriptTree.SweepLeaf
2✔
2927
        sweepIdx := scriptTree.LeafProofIndex[sweepLeaf.TapHash()]
2✔
2928
        sweepMerkleProof := scriptTree.LeafMerkleProofs[sweepIdx]
2✔
2929
        sweepControlBlock := sweepMerkleProof.ToControlBlock(anchorKey)
2✔
2930

2✔
2931
        // The final witness stack will be:
2✔
2932
        //
2✔
2933
        //  <sweep script> <control block>
2✔
2934
        witnessStack := make(wire.TxWitness, 2)
2✔
2935
        witnessStack[0] = sweepLeaf.Script
2✔
2936
        witnessStack[1], err = sweepControlBlock.ToBytes()
2✔
2937
        if err != nil {
2✔
2938
                return nil, err
×
2939
        }
×
2940

2941
        return witnessStack, nil
2✔
2942
}
2943

2944
// CommitSpendAnchor constructs a valid witness allowing a node to spend their
2945
// anchor output on the commitment transaction using their funding key. This is
2946
// used for the anchor channel type.
2947
func CommitSpendAnchor(signer Signer, signDesc *SignDescriptor,
2948
        sweepTx *wire.MsgTx) (wire.TxWitness, error) {
5✔
2949

5✔
2950
        if signDesc.KeyDesc.PubKey == nil {
5✔
2951
                return nil, fmt.Errorf("cannot generate witness with nil " +
×
2952
                        "KeyDesc pubkey")
×
2953
        }
×
2954

2955
        // Create a signature.
2956
        sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
5✔
2957
        if err != nil {
5✔
2958
                return nil, err
×
2959
        }
×
2960

2961
        // The witness here is just a signature and the redeem script.
2962
        witnessStack := make([][]byte, 2)
5✔
2963
        witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
5✔
2964
        witnessStack[1] = signDesc.WitnessScript
5✔
2965

5✔
2966
        return witnessStack, nil
5✔
2967
}
2968

2969
// CommitSpendAnchorAnyone constructs a witness allowing anyone to spend the
2970
// anchor output after it has gotten 16 confirmations. Since no signing is
2971
// required, only knowledge of the redeem script is necessary to spend it.
2972
func CommitSpendAnchorAnyone(script []byte) (wire.TxWitness, error) {
3✔
2973
        // The witness here is just the redeem script.
3✔
2974
        witnessStack := make([][]byte, 2)
3✔
2975
        witnessStack[0] = nil
3✔
2976
        witnessStack[1] = script
3✔
2977

3✔
2978
        return witnessStack, nil
3✔
2979
}
3✔
2980

2981
// SingleTweakBytes computes set of bytes we call the single tweak. The purpose
2982
// of the single tweak is to randomize all regular delay and payment base
2983
// points. To do this, we generate a hash that binds the commitment point to
2984
// the pay/delay base point. The end result is that the basePoint is
2985
// tweaked as follows:
2986
//
2987
//   - key = basePoint + sha256(commitPoint || basePoint)*G
2988
func SingleTweakBytes(commitPoint, basePoint *btcec.PublicKey) []byte {
114,021✔
2989
        h := sha256.New()
114,021✔
2990
        h.Write(commitPoint.SerializeCompressed())
114,021✔
2991
        h.Write(basePoint.SerializeCompressed())
114,021✔
2992
        return h.Sum(nil)
114,021✔
2993
}
114,021✔
2994

2995
// TweakPubKey tweaks a public base point given a per commitment point. The per
2996
// commitment point is a unique point on our target curve for each commitment
2997
// transaction. When tweaking a local base point for use in a remote commitment
2998
// transaction, the remote party's current per commitment point is to be used.
2999
// The opposite applies for when tweaking remote keys. Precisely, the following
3000
// operation is used to "tweak" public keys:
3001
//
3002
//        tweakPub := basePoint + sha256(commitPoint || basePoint) * G
3003
//                 := G*k + sha256(commitPoint || basePoint)*G
3004
//                 := G*(k + sha256(commitPoint || basePoint))
3005
//
3006
// Therefore, if a party possess the value k, the private key of the base
3007
// point, then they are able to derive the proper private key for the
3008
// revokeKey by computing:
3009
//
3010
//        revokePriv := k + sha256(commitPoint || basePoint) mod N
3011
//
3012
// Where N is the order of the sub-group.
3013
//
3014
// The rationale for tweaking all public keys used within the commitment
3015
// contracts is to ensure that all keys are properly delinearized to avoid any
3016
// funny business when jointly collaborating to compute public and private
3017
// keys. Additionally, the use of the per commitment point ensures that each
3018
// commitment state houses a unique set of keys which is useful when creating
3019
// blinded channel outsourcing protocols.
3020
//
3021
// TODO(roasbeef): should be using double-scalar mult here
3022
func TweakPubKey(basePoint, commitPoint *btcec.PublicKey) *btcec.PublicKey {
49,755✔
3023
        tweakBytes := SingleTweakBytes(commitPoint, basePoint)
49,755✔
3024
        return TweakPubKeyWithTweak(basePoint, tweakBytes)
49,755✔
3025
}
49,755✔
3026

3027
// TweakPubKeyWithTweak is the exact same as the TweakPubKey function, however
3028
// it accepts the raw tweak bytes directly rather than the commitment point.
3029
func TweakPubKeyWithTweak(pubKey *btcec.PublicKey,
3030
        tweakBytes []byte) *btcec.PublicKey {
287,409✔
3031

287,409✔
3032
        var (
287,409✔
3033
                pubKeyJacobian btcec.JacobianPoint
287,409✔
3034
                tweakJacobian  btcec.JacobianPoint
287,409✔
3035
                resultJacobian btcec.JacobianPoint
287,409✔
3036
        )
287,409✔
3037
        tweakKey, _ := btcec.PrivKeyFromBytes(tweakBytes)
287,409✔
3038
        btcec.ScalarBaseMultNonConst(&tweakKey.Key, &tweakJacobian)
287,409✔
3039

287,409✔
3040
        pubKey.AsJacobian(&pubKeyJacobian)
287,409✔
3041
        btcec.AddNonConst(&pubKeyJacobian, &tweakJacobian, &resultJacobian)
287,409✔
3042

287,409✔
3043
        resultJacobian.ToAffine()
287,409✔
3044
        return btcec.NewPublicKey(&resultJacobian.X, &resultJacobian.Y)
287,409✔
3045
}
287,409✔
3046

3047
// TweakPrivKey tweaks the private key of a public base point given a per
3048
// commitment point. The per commitment secret is the revealed revocation
3049
// secret for the commitment state in question. This private key will only need
3050
// to be generated in the case that a channel counter party broadcasts a
3051
// revoked state. Precisely, the following operation is used to derive a
3052
// tweaked private key:
3053
//
3054
//   - tweakPriv := basePriv + sha256(commitment || basePub) mod N
3055
//
3056
// Where N is the order of the sub-group.
3057
func TweakPrivKey(basePriv *btcec.PrivateKey,
3058
        commitTweak []byte) *btcec.PrivateKey {
240,655✔
3059

240,655✔
3060
        // tweakInt := sha256(commitPoint || basePub)
240,655✔
3061
        tweakScalar := new(btcec.ModNScalar)
240,655✔
3062
        tweakScalar.SetByteSlice(commitTweak)
240,655✔
3063

240,655✔
3064
        tweakScalar.Add(&basePriv.Key)
240,655✔
3065

240,655✔
3066
        return &btcec.PrivateKey{Key: *tweakScalar}
240,655✔
3067
}
240,655✔
3068

3069
// DeriveRevocationPubkey derives the revocation public key given the
3070
// counterparty's commitment key, and revocation preimage derived via a
3071
// pseudo-random-function. In the event that we (for some reason) broadcast a
3072
// revoked commitment transaction, then if the other party knows the revocation
3073
// preimage, then they'll be able to derive the corresponding private key to
3074
// this private key by exploiting the homomorphism in the elliptic curve group:
3075
//   - https://en.wikipedia.org/wiki/Group_homomorphism#Homomorphisms_of_abelian_groups
3076
//
3077
// The derivation is performed as follows:
3078
//
3079
//        revokeKey := revokeBase * sha256(revocationBase || commitPoint) +
3080
//                     commitPoint * sha256(commitPoint || revocationBase)
3081
//
3082
//                  := G*(revokeBasePriv * sha256(revocationBase || commitPoint)) +
3083
//                     G*(commitSecret * sha256(commitPoint || revocationBase))
3084
//
3085
//                  := G*(revokeBasePriv * sha256(revocationBase || commitPoint) +
3086
//                        commitSecret * sha256(commitPoint || revocationBase))
3087
//
3088
// Therefore, once we divulge the revocation secret, the remote peer is able to
3089
// compute the proper private key for the revokeKey by computing:
3090
//
3091
//        revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
3092
//                      (commitSecret * sha256(commitPoint || revocationBase)) mod N
3093
//
3094
// Where N is the order of the sub-group.
3095
func DeriveRevocationPubkey(revokeBase,
3096
        commitPoint *btcec.PublicKey) *btcec.PublicKey {
16,058✔
3097

16,058✔
3098
        // R = revokeBase * sha256(revocationBase || commitPoint)
16,058✔
3099
        revokeTweakBytes := SingleTweakBytes(revokeBase, commitPoint)
16,058✔
3100
        revokeTweakScalar := new(btcec.ModNScalar)
16,058✔
3101
        revokeTweakScalar.SetByteSlice(revokeTweakBytes)
16,058✔
3102

16,058✔
3103
        var (
16,058✔
3104
                revokeBaseJacobian btcec.JacobianPoint
16,058✔
3105
                rJacobian          btcec.JacobianPoint
16,058✔
3106
        )
16,058✔
3107
        revokeBase.AsJacobian(&revokeBaseJacobian)
16,058✔
3108
        btcec.ScalarMultNonConst(
16,058✔
3109
                revokeTweakScalar, &revokeBaseJacobian, &rJacobian,
16,058✔
3110
        )
16,058✔
3111

16,058✔
3112
        // C = commitPoint * sha256(commitPoint || revocationBase)
16,058✔
3113
        commitTweakBytes := SingleTweakBytes(commitPoint, revokeBase)
16,058✔
3114
        commitTweakScalar := new(btcec.ModNScalar)
16,058✔
3115
        commitTweakScalar.SetByteSlice(commitTweakBytes)
16,058✔
3116

16,058✔
3117
        var (
16,058✔
3118
                commitPointJacobian btcec.JacobianPoint
16,058✔
3119
                cJacobian           btcec.JacobianPoint
16,058✔
3120
        )
16,058✔
3121
        commitPoint.AsJacobian(&commitPointJacobian)
16,058✔
3122
        btcec.ScalarMultNonConst(
16,058✔
3123
                commitTweakScalar, &commitPointJacobian, &cJacobian,
16,058✔
3124
        )
16,058✔
3125

16,058✔
3126
        // Now that we have the revocation point, we add this to their commitment
16,058✔
3127
        // public key in order to obtain the revocation public key.
16,058✔
3128
        //
16,058✔
3129
        // P = R + C
16,058✔
3130
        var resultJacobian btcec.JacobianPoint
16,058✔
3131
        btcec.AddNonConst(&rJacobian, &cJacobian, &resultJacobian)
16,058✔
3132

16,058✔
3133
        resultJacobian.ToAffine()
16,058✔
3134
        return btcec.NewPublicKey(&resultJacobian.X, &resultJacobian.Y)
16,058✔
3135
}
16,058✔
3136

3137
// DeriveRevocationPrivKey derives the revocation private key given a node's
3138
// commitment private key, and the preimage to a previously seen revocation
3139
// hash. Using this derived private key, a node is able to claim the output
3140
// within the commitment transaction of a node in the case that they broadcast
3141
// a previously revoked commitment transaction.
3142
//
3143
// The private key is derived as follows:
3144
//
3145
//        revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
3146
//                      (commitSecret * sha256(commitPoint || revocationBase)) mod N
3147
//
3148
// Where N is the order of the sub-group.
3149
func DeriveRevocationPrivKey(revokeBasePriv *btcec.PrivateKey,
3150
        commitSecret *btcec.PrivateKey) *btcec.PrivateKey {
60✔
3151

60✔
3152
        // r = sha256(revokeBasePub || commitPoint)
60✔
3153
        revokeTweakBytes := SingleTweakBytes(
60✔
3154
                revokeBasePriv.PubKey(), commitSecret.PubKey(),
60✔
3155
        )
60✔
3156
        revokeTweakScalar := new(btcec.ModNScalar)
60✔
3157
        revokeTweakScalar.SetByteSlice(revokeTweakBytes)
60✔
3158

60✔
3159
        // c = sha256(commitPoint || revokeBasePub)
60✔
3160
        commitTweakBytes := SingleTweakBytes(
60✔
3161
                commitSecret.PubKey(), revokeBasePriv.PubKey(),
60✔
3162
        )
60✔
3163
        commitTweakScalar := new(btcec.ModNScalar)
60✔
3164
        commitTweakScalar.SetByteSlice(commitTweakBytes)
60✔
3165

60✔
3166
        // Finally to derive the revocation secret key we'll perform the
60✔
3167
        // following operation:
60✔
3168
        //
60✔
3169
        //  k = (revocationPriv * r) + (commitSecret * c) mod N
60✔
3170
        //
60✔
3171
        // This works since:
60✔
3172
        //  P = (G*a)*b + (G*c)*d
60✔
3173
        //  P = G*(a*b) + G*(c*d)
60✔
3174
        //  P = G*(a*b + c*d)
60✔
3175
        revokeHalfPriv := revokeTweakScalar.Mul(&revokeBasePriv.Key)
60✔
3176
        commitHalfPriv := commitTweakScalar.Mul(&commitSecret.Key)
60✔
3177

60✔
3178
        revocationPriv := revokeHalfPriv.Add(commitHalfPriv)
60✔
3179

60✔
3180
        return &btcec.PrivateKey{Key: *revocationPriv}
60✔
3181
}
60✔
3182

3183
// ComputeCommitmentPoint generates a commitment point given a commitment
3184
// secret. The commitment point for each state is used to randomize each key in
3185
// the key-ring and also to used as a tweak to derive new public+private keys
3186
// for the state.
3187
func ComputeCommitmentPoint(commitSecret []byte) *btcec.PublicKey {
11,709✔
3188
        _, pubKey := btcec.PrivKeyFromBytes(commitSecret)
11,709✔
3189
        return pubKey
11,709✔
3190
}
11,709✔
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

© 2026 Coveralls, Inc