-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathlnd_taproot_test.go
1985 lines (1704 loc) · 62 KB
/
lnd_taproot_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package itest
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"testing"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/psbt"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/chainrpc"
"github.com/lightningnetwork/lnd/lnrpc/signrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lntest"
"github.com/lightningnetwork/lnd/lntest/node"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/stretchr/testify/require"
)
const (
testTaprootKeyFamily = 77
testAmount = 800_000
signMethodBip86 = signrpc.SignMethod_SIGN_METHOD_TAPROOT_KEY_SPEND_BIP0086
signMethodRootHash = signrpc.SignMethod_SIGN_METHOD_TAPROOT_KEY_SPEND
signMethodTapscript = signrpc.SignMethod_SIGN_METHOD_TAPROOT_SCRIPT_SPEND
)
var (
hexDecode = func(keyStr string) []byte {
keyBytes, _ := hex.DecodeString(keyStr)
return keyBytes
}
dummyInternalKey, _ = btcec.ParsePubKey(hexDecode(
"03464805f5468e294d88cf15a3f06aef6c89d63ef1bd7b42db2e0c74c1ac" +
"eb90fe",
))
)
// testTaprootSpend ensures that the daemon can send to and spend from taproot
// (p2tr) outputs.
func testTaprootSpend(ht *lntest.HarnessTest) {
alice := ht.NewNode("Alice", nil)
testTaprootSendCoinsKeySpendBip86(ht, alice)
testTaprootComputeInputScriptKeySpendBip86(ht, alice)
testTaprootSignOutputRawScriptSpend(ht, alice)
testTaprootSignOutputRawScriptSpend(
ht, alice, txscript.SigHashSingle,
)
testTaprootSignOutputRawKeySpendBip86(ht, alice)
testTaprootSignOutputRawKeySpendBip86(
ht, alice, txscript.SigHashSingle,
)
testTaprootSignOutputRawKeySpendRootHash(ht, alice)
}
// testTaprootMuSig2 ensures that the daemon can send to and spend from taproot
// (p2tr) outputs using musig2.
func testTaprootMuSig2(ht *lntest.HarnessTest) {
alice := ht.NewNodeWithCoins("Alice", nil)
muSig2Versions := []signrpc.MuSig2Version{
signrpc.MuSig2Version_MUSIG2_VERSION_V040,
signrpc.MuSig2Version_MUSIG2_VERSION_V100RC2,
}
for _, version := range muSig2Versions {
testTaprootMuSig2KeySpendBip86(ht, alice, version)
testTaprootMuSig2KeySpendRootHash(ht, alice, version)
testTaprootMuSig2ScriptSpend(ht, alice, version)
testTaprootMuSig2CombinedLeafKeySpend(ht, alice, version)
testMuSig2CombineKey(ht, alice, version)
}
}
// testTaprootImportScripts ensures that the daemon can import taproot scripts.
func testTaprootImportScripts(ht *lntest.HarnessTest) {
alice := ht.NewNodeWithCoins("Alice", nil)
testTaprootImportTapscriptFullTree(ht, alice)
testTaprootImportTapscriptPartialReveal(ht, alice)
testTaprootImportTapscriptRootHashOnly(ht, alice)
testTaprootImportTapscriptFullKey(ht, alice)
}
// testTaprootSendCoinsKeySpendBip86 tests sending to and spending from
// p2tr key spend only (BIP-0086) addresses through the SendCoins RPC which
// internally uses the ComputeInputScript method for signing.
func testTaprootSendCoinsKeySpendBip86(ht *lntest.HarnessTest,
alice *node.HarnessNode) {
// We'll start the test by sending Alice some coins, which she'll use to
// send to herself on a p2tr output.
ht.FundCoins(btcutil.SatoshiPerBitcoin, alice)
// Let's create a p2tr address now.
p2trResp := alice.RPC.NewAddress(&lnrpc.NewAddressRequest{
Type: AddrTypeTaprootPubkey,
})
// Assert this is a segwit v1 address that starts with bcrt1p.
require.Contains(
ht, p2trResp.Address, ht.Miner().ActiveNet.Bech32HRPSegwit+"1p",
)
// Send the coins from Alice's wallet to her own, but to the new p2tr
// address.
alice.RPC.SendCoins(&lnrpc.SendCoinsRequest{
Addr: p2trResp.Address,
Amount: 0.5 * btcutil.SatoshiPerBitcoin,
TargetConf: 6,
})
txid := ht.AssertNumTxsInMempool(1)[0]
// Wait until bob has seen the tx and considers it as owned.
p2trOutputIndex := ht.GetOutputIndex(txid, p2trResp.Address)
op := &lnrpc.OutPoint{
TxidBytes: txid[:],
OutputIndex: uint32(p2trOutputIndex),
}
ht.AssertUTXOInWallet(alice, op, "")
// Mine a block to clean up the mempool.
ht.MineBlocksAndAssertNumTxes(1, 1)
// Let's sweep the whole wallet to a new p2tr address, making sure we
// can sign transactions with v0 and v1 inputs.
p2trResp = alice.RPC.NewAddress(&lnrpc.NewAddressRequest{
Type: lnrpc.AddressType_TAPROOT_PUBKEY,
})
alice.RPC.SendCoins(&lnrpc.SendCoinsRequest{
Addr: p2trResp.Address,
SendAll: true,
TargetConf: 6,
})
// Make sure the coins sent to the address are confirmed correctly,
// including the confirmation notification.
confirmAddress(ht, alice, p2trResp.Address)
}
// testTaprootComputeInputScriptKeySpendBip86 tests sending to and spending from
// p2tr key spend only (BIP-0086) addresses through the SendCoins RPC which
// internally uses the ComputeInputScript method for signing.
func testTaprootComputeInputScriptKeySpendBip86(ht *lntest.HarnessTest,
alice *node.HarnessNode) {
// We'll start the test by sending Alice some coins, which she'll use
// to send to herself on a p2tr output.
ht.FundCoins(btcutil.SatoshiPerBitcoin, alice)
// Let's create a p2tr address now.
p2trAddr, p2trPkScript := newAddrWithScript(
ht, alice, lnrpc.AddressType_TAPROOT_PUBKEY,
)
// Send the coins from Alice's wallet to her own, but to the new p2tr
// address.
req := &lnrpc.SendCoinsRequest{
Addr: p2trAddr.String(),
Amount: testAmount,
TargetConf: 6,
}
alice.RPC.SendCoins(req)
// Wait until bob has seen the tx and considers it as owned.
txid := ht.AssertNumTxsInMempool(1)[0]
p2trOutputIndex := ht.GetOutputIndex(txid, p2trAddr.String())
op := &lnrpc.OutPoint{
TxidBytes: txid[:],
OutputIndex: uint32(p2trOutputIndex),
}
ht.AssertUTXOInWallet(alice, op, "")
p2trOutpoint := wire.OutPoint{
Hash: txid,
Index: uint32(p2trOutputIndex),
}
// Mine a block to clean up the mempool.
ht.MineBlocksAndAssertNumTxes(1, 1)
// We'll send the coins back to a p2wkh address.
p2wkhAddr, p2wkhPkScript := newAddrWithScript(
ht, alice, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
)
// Create fee estimation for a p2tr input and p2wkh output.
feeRate := chainfee.SatPerKWeight(12500)
estimator := input.TxWeightEstimator{}
estimator.AddTaprootKeySpendInput(txscript.SigHashDefault)
estimator.AddP2WKHOutput()
estimatedWeight := estimator.Weight()
requiredFee := feeRate.FeeForWeight(estimatedWeight)
tx := wire.NewMsgTx(2)
tx.TxIn = []*wire.TxIn{{
PreviousOutPoint: p2trOutpoint,
}}
value := int64(testAmount - requiredFee)
tx.TxOut = []*wire.TxOut{{
PkScript: p2wkhPkScript,
Value: value,
}}
var buf bytes.Buffer
require.NoError(ht, tx.Serialize(&buf))
utxoInfo := []*signrpc.TxOut{{
PkScript: p2trPkScript,
Value: testAmount,
}}
signReq := &signrpc.SignReq{
RawTxBytes: buf.Bytes(),
SignDescs: []*signrpc.SignDescriptor{{
Output: utxoInfo[0],
InputIndex: 0,
Sighash: uint32(txscript.SigHashDefault),
}},
PrevOutputs: utxoInfo,
}
signResp := alice.RPC.ComputeInputScript(signReq)
tx.TxIn[0].Witness = signResp.InputScripts[0].Witness
// Serialize, weigh and publish the TX now, then make sure the
// coins are sent and confirmed to the final sweep destination address.
publishTxAndConfirmSweep(
ht, alice, tx, estimatedWeight,
&chainrpc.SpendRequest{
Outpoint: &chainrpc.Outpoint{
Hash: p2trOutpoint.Hash[:],
Index: p2trOutpoint.Index,
},
Script: p2trPkScript,
},
p2wkhAddr.String(),
)
}
// testTaprootSignOutputRawScriptSpend tests sending to and spending from p2tr
// script addresses using the script path with the SignOutputRaw RPC.
func testTaprootSignOutputRawScriptSpend(ht *lntest.HarnessTest,
alice *node.HarnessNode, sigHashType ...txscript.SigHashType) {
// For the next step, we need a public key. Let's use a special family
// for this.
req := &walletrpc.KeyReq{KeyFamily: testTaprootKeyFamily}
keyDesc := alice.RPC.DeriveNextKey(req)
leafSigningKey, err := btcec.ParsePubKey(keyDesc.RawKeyBytes)
require.NoError(ht, err)
// Let's create a taproot script output now. This is a hash lock with a
// simple preimage of "foobar".
leaf1 := testScriptHashLock(ht.T, []byte("foobar"))
// Let's add a second script output as well to test the partial reveal.
leaf2 := testScriptSchnorrSig(ht.T, leafSigningKey)
inclusionProof := leaf1.TapHash()
tapscript := input.TapscriptPartialReveal(
dummyInternalKey, leaf2, inclusionProof[:],
)
taprootKey, err := tapscript.TaprootKey()
require.NoError(ht, err)
// Send some coins to the generated tapscript address.
p2trOutpoint, p2trPkScript := sendToTaprootOutput(ht, alice, taprootKey)
// Spend the output again, this time back to a p2wkh address.
p2wkhAddr, p2wkhPkScript := newAddrWithScript(
ht, alice, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
)
// Create fee estimation for a p2tr input and p2wkh output.
feeRate := chainfee.SatPerKWeight(12500)
estimator := input.TxWeightEstimator{}
estimator.AddTapscriptInput(
input.TaprootSignatureWitnessSize, tapscript,
)
estimator.AddP2WKHOutput()
estimatedWeight := estimator.Weight()
sigHash := txscript.SigHashDefault
if len(sigHashType) != 0 {
sigHash = sigHashType[0]
// If a non-default sighash is used, then we'll need to add an
// extra byte to account for the sighash that doesn't exist in
// the default case.
estimatedWeight++
}
requiredFee := feeRate.FeeForWeight(estimatedWeight)
tx := wire.NewMsgTx(2)
tx.TxIn = []*wire.TxIn{{
PreviousOutPoint: p2trOutpoint,
}}
value := int64(testAmount - requiredFee)
tx.TxOut = []*wire.TxOut{{
PkScript: p2wkhPkScript,
Value: value,
}}
var buf bytes.Buffer
require.NoError(ht, tx.Serialize(&buf))
utxoInfo := []*signrpc.TxOut{{
PkScript: p2trPkScript,
Value: testAmount,
}}
// Before we actually sign, we want to make sure that we get an error
// when we try to sign for a Taproot output without specifying all UTXO
// information.
signReq := &signrpc.SignReq{
RawTxBytes: buf.Bytes(),
SignDescs: []*signrpc.SignDescriptor{{
Output: utxoInfo[0],
InputIndex: 0,
KeyDesc: keyDesc,
Sighash: uint32(sigHash),
WitnessScript: leaf2.Script,
SignMethod: signMethodTapscript,
}},
}
err = alice.RPC.SignOutputRawErr(signReq)
require.Contains(
ht, err.Error(), "error signing taproot output, transaction "+
"input 0 is missing its previous outpoint information",
)
// We also want to make sure we get an error when we don't specify the
// correct signing method.
signReq = &signrpc.SignReq{
RawTxBytes: buf.Bytes(),
SignDescs: []*signrpc.SignDescriptor{{
Output: utxoInfo[0],
InputIndex: 0,
KeyDesc: keyDesc,
Sighash: uint32(sigHash),
WitnessScript: leaf2.Script,
}},
PrevOutputs: utxoInfo,
}
err = alice.RPC.SignOutputRawErr(signReq)
require.Contains(
ht, err.Error(), "selected sign method witness_v0 is not "+
"compatible with given pk script 5120",
)
// Do the actual signing now.
signReq = &signrpc.SignReq{
RawTxBytes: buf.Bytes(),
SignDescs: []*signrpc.SignDescriptor{{
Output: utxoInfo[0],
InputIndex: 0,
KeyDesc: keyDesc,
Sighash: uint32(sigHash),
WitnessScript: leaf2.Script,
SignMethod: signMethodTapscript,
}},
PrevOutputs: utxoInfo,
}
signResp := alice.RPC.SignOutputRaw(signReq)
// We can now assemble the witness stack.
controlBlockBytes, err := tapscript.ControlBlock.ToBytes()
require.NoError(ht, err)
sig := signResp.RawSigs[0]
if len(sigHashType) != 0 {
sig = append(sig, byte(sigHashType[0]))
}
tx.TxIn[0].Witness = wire.TxWitness{
sig, leaf2.Script, controlBlockBytes,
}
// Serialize, weigh and publish the TX now, then make sure the
// coins are sent and confirmed to the final sweep destination address.
publishTxAndConfirmSweep(
ht, alice, tx, estimatedWeight,
&chainrpc.SpendRequest{
Outpoint: &chainrpc.Outpoint{
Hash: p2trOutpoint.Hash[:],
Index: p2trOutpoint.Index,
},
Script: p2trPkScript,
},
p2wkhAddr.String(),
)
}
// testTaprootSignOutputRawKeySpendBip86 tests that a tapscript address can
// also be spent using the key spend path through the SignOutputRaw RPC using a
// BIP0086 key spend only commitment.
func testTaprootSignOutputRawKeySpendBip86(ht *lntest.HarnessTest,
alice *node.HarnessNode, sigHashType ...txscript.SigHashType) {
// For the next step, we need a public key. Let's use a special family
// for this.
req := &walletrpc.KeyReq{KeyFamily: testTaprootKeyFamily}
keyDesc := alice.RPC.DeriveNextKey(req)
internalKey, err := btcec.ParsePubKey(keyDesc.RawKeyBytes)
require.NoError(ht, err)
// We want to make sure we can still use a tweaked key, even if it ends
// up being essentially double tweaked because of the taproot root hash.
dummyKeyTweak := sha256.Sum256([]byte("this is a key tweak"))
internalKey = input.TweakPubKeyWithTweak(internalKey, dummyKeyTweak[:])
// Our taproot key is a BIP0086 key spend only construction that just
// commits to the internal key and no root hash.
taprootKey := txscript.ComputeTaprootKeyNoScript(internalKey)
// Send some coins to the generated tapscript address.
p2trOutpoint, p2trPkScript := sendToTaprootOutput(ht, alice, taprootKey)
// Spend the output again, this time back to a p2wkh address.
p2wkhAddr, p2wkhPkScript := newAddrWithScript(
ht, alice, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
)
sigHash := txscript.SigHashDefault
if len(sigHashType) != 0 {
sigHash = sigHashType[0]
}
// Create fee estimation for a p2tr input and p2wkh output.
feeRate := chainfee.SatPerKWeight(12500)
estimator := input.TxWeightEstimator{}
estimator.AddTaprootKeySpendInput(sigHash)
estimator.AddP2WKHOutput()
estimatedWeight := estimator.Weight()
requiredFee := feeRate.FeeForWeight(estimatedWeight)
tx := wire.NewMsgTx(2)
tx.TxIn = []*wire.TxIn{{
PreviousOutPoint: p2trOutpoint,
}}
value := int64(testAmount - requiredFee)
tx.TxOut = []*wire.TxOut{{
PkScript: p2wkhPkScript,
Value: value,
}}
var buf bytes.Buffer
require.NoError(ht, tx.Serialize(&buf))
utxoInfo := []*signrpc.TxOut{{
PkScript: p2trPkScript,
Value: testAmount,
}}
signReq := &signrpc.SignReq{
RawTxBytes: buf.Bytes(),
SignDescs: []*signrpc.SignDescriptor{{
Output: utxoInfo[0],
InputIndex: 0,
KeyDesc: keyDesc,
SingleTweak: dummyKeyTweak[:],
Sighash: uint32(sigHash),
SignMethod: signMethodBip86,
}},
PrevOutputs: utxoInfo,
}
signResp := alice.RPC.SignOutputRaw(signReq)
sig := signResp.RawSigs[0]
if len(sigHashType) != 0 {
sig = append(sig, byte(sigHash))
}
tx.TxIn[0].Witness = wire.TxWitness{sig}
// Serialize, weigh and publish the TX now, then make sure the
// coins are sent and confirmed to the final sweep destination address.
publishTxAndConfirmSweep(
ht, alice, tx, estimatedWeight,
&chainrpc.SpendRequest{
Outpoint: &chainrpc.Outpoint{
Hash: p2trOutpoint.Hash[:],
Index: p2trOutpoint.Index,
},
Script: p2trPkScript,
},
p2wkhAddr.String(),
)
}
// testTaprootSignOutputRawKeySpendRootHash tests that a tapscript address can
// also be spent using the key spend path through the SignOutputRaw RPC using a
// tapscript root hash.
func testTaprootSignOutputRawKeySpendRootHash(ht *lntest.HarnessTest,
alice *node.HarnessNode) {
// For the next step, we need a public key. Let's use a special family
// for this.
req := &walletrpc.KeyReq{KeyFamily: testTaprootKeyFamily}
keyDesc := alice.RPC.DeriveNextKey(req)
internalKey, err := btcec.ParsePubKey(keyDesc.RawKeyBytes)
require.NoError(ht, err)
// We want to make sure we can still use a tweaked key, even if it ends
// up being essentially double tweaked because of the taproot root hash.
dummyKeyTweak := sha256.Sum256([]byte("this is a key tweak"))
internalKey = input.TweakPubKeyWithTweak(internalKey, dummyKeyTweak[:])
// Let's create a taproot script output now. This is a hash lock with a
// simple preimage of "foobar".
leaf1 := testScriptHashLock(ht.T, []byte("foobar"))
rootHash := leaf1.TapHash()
taprootKey := txscript.ComputeTaprootOutputKey(internalKey, rootHash[:])
// Send some coins to the generated tapscript address.
p2trOutpoint, p2trPkScript := sendToTaprootOutput(ht, alice, taprootKey)
// Spend the output again, this time back to a p2wkh address.
p2wkhAddr, p2wkhPkScript := newAddrWithScript(
ht, alice, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
)
// Create fee estimation for a p2tr input and p2wkh output.
feeRate := chainfee.SatPerKWeight(12500)
estimator := input.TxWeightEstimator{}
estimator.AddTaprootKeySpendInput(txscript.SigHashDefault)
estimator.AddP2WKHOutput()
estimatedWeight := estimator.Weight()
requiredFee := feeRate.FeeForWeight(estimatedWeight)
tx := wire.NewMsgTx(2)
tx.TxIn = []*wire.TxIn{{
PreviousOutPoint: p2trOutpoint,
}}
value := int64(testAmount - requiredFee)
tx.TxOut = []*wire.TxOut{{
PkScript: p2wkhPkScript,
Value: value,
}}
var buf bytes.Buffer
require.NoError(ht, tx.Serialize(&buf))
utxoInfo := []*signrpc.TxOut{{
PkScript: p2trPkScript,
Value: testAmount,
}}
signReq := &signrpc.SignReq{
RawTxBytes: buf.Bytes(),
SignDescs: []*signrpc.SignDescriptor{{
Output: utxoInfo[0],
InputIndex: 0,
KeyDesc: keyDesc,
SingleTweak: dummyKeyTweak[:],
Sighash: uint32(txscript.SigHashDefault),
TapTweak: rootHash[:],
SignMethod: signMethodRootHash,
}},
PrevOutputs: utxoInfo,
}
signResp := alice.RPC.SignOutputRaw(signReq)
tx.TxIn[0].Witness = wire.TxWitness{
signResp.RawSigs[0],
}
// Serialize, weigh and publish the TX now, then make sure the
// coins are sent and confirmed to the final sweep destination address.
publishTxAndConfirmSweep(
ht, alice, tx, estimatedWeight,
&chainrpc.SpendRequest{
Outpoint: &chainrpc.Outpoint{
Hash: p2trOutpoint.Hash[:],
Index: p2trOutpoint.Index,
},
Script: p2trPkScript,
},
p2wkhAddr.String(),
)
}
// testTaprootMuSig2KeySpendBip86 tests that a combined MuSig2 key can also be
// used as a BIP-0086 key spend only key.
func testTaprootMuSig2KeySpendBip86(ht *lntest.HarnessTest,
alice *node.HarnessNode, version signrpc.MuSig2Version) {
// We're not going to commit to a script. So our taproot tweak will be
// empty and just specify the necessary flag.
taprootTweak := &signrpc.TaprootTweakDesc{
KeySpendOnly: true,
}
keyDesc1, keyDesc2, keyDesc3, allPubKeys := deriveSigningKeys(
ht, alice, version,
)
_, taprootKey, sessResp1, sessResp2, sessResp3 := createMuSigSessions(
ht, alice, taprootTweak, keyDesc1, keyDesc2, keyDesc3,
allPubKeys, version,
)
// Send some coins to the generated tapscript address.
p2trOutpoint, p2trPkScript := sendToTaprootOutput(ht, alice, taprootKey)
// Spend the output again, this time back to a p2wkh address.
p2wkhAddr, p2wkhPkScript := newAddrWithScript(
ht, alice, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
)
// Create fee estimation for a p2tr input and p2wkh output.
feeRate := chainfee.SatPerKWeight(12500)
estimator := input.TxWeightEstimator{}
estimator.AddTaprootKeySpendInput(txscript.SigHashDefault)
estimator.AddP2WKHOutput()
estimatedWeight := estimator.Weight()
requiredFee := feeRate.FeeForWeight(estimatedWeight)
tx := wire.NewMsgTx(2)
tx.TxIn = []*wire.TxIn{{
PreviousOutPoint: p2trOutpoint,
}}
value := int64(testAmount - requiredFee)
tx.TxOut = []*wire.TxOut{{
PkScript: p2wkhPkScript,
Value: value,
}}
var buf bytes.Buffer
require.NoError(ht, tx.Serialize(&buf))
utxoInfo := []*signrpc.TxOut{{
PkScript: p2trPkScript,
Value: testAmount,
}}
// We now need to create the raw sighash of the transaction, as that
// will be the message we're signing collaboratively.
prevOutputFetcher := txscript.NewCannedPrevOutputFetcher(
utxoInfo[0].PkScript, utxoInfo[0].Value,
)
sighashes := txscript.NewTxSigHashes(tx, prevOutputFetcher)
sigHash, err := txscript.CalcTaprootSignatureHash(
sighashes, txscript.SigHashDefault, tx, 0, prevOutputFetcher,
)
require.NoError(ht, err)
// Now that we have the transaction prepared, we need to start with the
// signing. We simulate all three parties here, so we need to do
// everything three times. But because we're going to use session 1 to
// combine everything, we don't need its response, as it will store its
// own signature.
signReq := &signrpc.MuSig2SignRequest{
SessionId: sessResp1.SessionId,
MessageDigest: sigHash,
}
alice.RPC.MuSig2Sign(signReq)
signReq = &signrpc.MuSig2SignRequest{
SessionId: sessResp2.SessionId,
MessageDigest: sigHash,
Cleanup: true,
}
signResp2 := alice.RPC.MuSig2Sign(signReq)
signReq = &signrpc.MuSig2SignRequest{
SessionId: sessResp3.SessionId,
MessageDigest: sigHash,
Cleanup: true,
}
signResp3 := alice.RPC.MuSig2Sign(signReq)
// Luckily only one of the signers needs to combine the signature, so
// let's do that now.
combineReq := &signrpc.MuSig2CombineSigRequest{
SessionId: sessResp1.SessionId,
OtherPartialSignatures: [][]byte{
signResp2.LocalPartialSignature,
signResp3.LocalPartialSignature,
},
}
combineResp := alice.RPC.MuSig2CombineSig(combineReq)
require.Equal(ht, true, combineResp.HaveAllSignatures)
require.NotEmpty(ht, combineResp.FinalSignature)
sig, err := schnorr.ParseSignature(combineResp.FinalSignature)
require.NoError(ht, err)
require.True(ht, sig.Verify(sigHash, taprootKey))
tx.TxIn[0].Witness = wire.TxWitness{
combineResp.FinalSignature,
}
// Serialize, weigh and publish the TX now, then make sure the
// coins are sent and confirmed to the final sweep destination address.
publishTxAndConfirmSweep(
ht, alice, tx, estimatedWeight,
&chainrpc.SpendRequest{
Outpoint: &chainrpc.Outpoint{
Hash: p2trOutpoint.Hash[:],
Index: p2trOutpoint.Index,
},
Script: p2trPkScript,
},
p2wkhAddr.String(),
)
}
// testTaprootMuSig2KeySpendRootHash tests that a tapscript address can also be
// spent using a MuSig2 combined key.
func testTaprootMuSig2KeySpendRootHash(ht *lntest.HarnessTest,
alice *node.HarnessNode, version signrpc.MuSig2Version) {
// We're going to commit to a script as well. This is a hash lock with a
// simple preimage of "foobar". We need to know this upfront so, we can
// specify the taproot tweak with the root hash when creating the Musig2
// signing session.
leaf1 := testScriptHashLock(ht.T, []byte("foobar"))
rootHash := leaf1.TapHash()
taprootTweak := &signrpc.TaprootTweakDesc{
ScriptRoot: rootHash[:],
}
keyDesc1, keyDesc2, keyDesc3, allPubKeys := deriveSigningKeys(
ht, alice, version,
)
_, taprootKey, sessResp1, sessResp2, sessResp3 := createMuSigSessions(
ht, alice, taprootTweak, keyDesc1, keyDesc2, keyDesc3,
allPubKeys, version,
)
// Send some coins to the generated tapscript address.
p2trOutpoint, p2trPkScript := sendToTaprootOutput(ht, alice, taprootKey)
// Spend the output again, this time back to a p2wkh address.
p2wkhAddr, p2wkhPkScript := newAddrWithScript(
ht, alice, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
)
// Create fee estimation for a p2tr input and p2wkh output.
feeRate := chainfee.SatPerKWeight(12500)
estimator := input.TxWeightEstimator{}
estimator.AddTaprootKeySpendInput(txscript.SigHashDefault)
estimator.AddP2WKHOutput()
estimatedWeight := estimator.Weight()
requiredFee := feeRate.FeeForWeight(estimatedWeight)
tx := wire.NewMsgTx(2)
tx.TxIn = []*wire.TxIn{{
PreviousOutPoint: p2trOutpoint,
}}
value := int64(testAmount - requiredFee)
tx.TxOut = []*wire.TxOut{{
PkScript: p2wkhPkScript,
Value: value,
}}
var buf bytes.Buffer
require.NoError(ht, tx.Serialize(&buf))
utxoInfo := []*signrpc.TxOut{{
PkScript: p2trPkScript,
Value: testAmount,
}}
// We now need to create the raw sighash of the transaction, as that
// will be the message we're signing collaboratively.
prevOutputFetcher := txscript.NewCannedPrevOutputFetcher(
utxoInfo[0].PkScript, utxoInfo[0].Value,
)
sighashes := txscript.NewTxSigHashes(tx, prevOutputFetcher)
sigHash, err := txscript.CalcTaprootSignatureHash(
sighashes, txscript.SigHashDefault, tx, 0, prevOutputFetcher,
)
require.NoError(ht, err)
// Now that we have the transaction prepared, we need to start with the
// signing. We simulate all three parties here, so we need to do
// everything three times. But because we're going to use session 1 to
// combine everything, we don't need its response, as it will store its
// own signature.
req := &signrpc.MuSig2SignRequest{
SessionId: sessResp1.SessionId,
MessageDigest: sigHash,
}
alice.RPC.MuSig2Sign(req)
req = &signrpc.MuSig2SignRequest{
SessionId: sessResp2.SessionId,
MessageDigest: sigHash,
Cleanup: true,
}
signResp2 := alice.RPC.MuSig2Sign(req)
req = &signrpc.MuSig2SignRequest{
SessionId: sessResp3.SessionId,
MessageDigest: sigHash,
Cleanup: true,
}
signResp3 := alice.RPC.MuSig2Sign(req)
// Luckily only one of the signers needs to combine the signature, so
// let's do that now.
combineReq := &signrpc.MuSig2CombineSigRequest{
SessionId: sessResp1.SessionId,
OtherPartialSignatures: [][]byte{
signResp2.LocalPartialSignature,
signResp3.LocalPartialSignature,
},
}
combineResp := alice.RPC.MuSig2CombineSig(combineReq)
require.Equal(ht, true, combineResp.HaveAllSignatures)
require.NotEmpty(ht, combineResp.FinalSignature)
sig, err := schnorr.ParseSignature(combineResp.FinalSignature)
require.NoError(ht, err)
require.True(ht, sig.Verify(sigHash, taprootKey))
tx.TxIn[0].Witness = wire.TxWitness{
combineResp.FinalSignature,
}
// Serialize, weigh and publish the TX now, then make sure the
// coins are sent and confirmed to the final sweep destination address.
publishTxAndConfirmSweep(
ht, alice, tx, estimatedWeight,
&chainrpc.SpendRequest{
Outpoint: &chainrpc.Outpoint{
Hash: p2trOutpoint.Hash[:],
Index: p2trOutpoint.Index,
},
Script: p2trPkScript,
},
p2wkhAddr.String(),
)
}
// testTaprootMuSig2ScriptSpend tests that a tapscript address with an internal
// key that is a MuSig2 combined key can also be spent using the script path.
func testTaprootMuSig2ScriptSpend(ht *lntest.HarnessTest,
alice *node.HarnessNode, version signrpc.MuSig2Version) {
// We're going to commit to a script and spend the output using the
// script. This is a hash lock with a simple preimage of "foobar". We
// need to know this upfront so, we can specify the taproot tweak with
// the root hash when creating the Musig2 signing session.
leaf1 := testScriptHashLock(ht.T, []byte("foobar"))
rootHash := leaf1.TapHash()
taprootTweak := &signrpc.TaprootTweakDesc{
ScriptRoot: rootHash[:],
}
keyDesc1, keyDesc2, keyDesc3, allPubKeys := deriveSigningKeys(
ht, alice, version,
)
internalKey, taprootKey, _, _, _ := createMuSigSessions(
ht, alice, taprootTweak, keyDesc1, keyDesc2, keyDesc3,
allPubKeys, version,
)
// Because we know the internal key and the script we want to spend, we
// can now create the tapscript struct that's used for assembling the
// control block and fee estimation.
tapscript := input.TapscriptFullTree(internalKey, leaf1)
// Send some coins to the generated tapscript address.
p2trOutpoint, p2trPkScript := sendToTaprootOutput(ht, alice, taprootKey)
// Spend the output again, this time back to a p2wkh address.
p2wkhAddr, p2wkhPkScript := newAddrWithScript(
ht, alice, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
)
// Create fee estimation for a p2tr input and p2wkh output.
feeRate := chainfee.SatPerKWeight(12500)
estimator := input.TxWeightEstimator{}
estimator.AddTapscriptInput(
lntypes.WeightUnit(len([]byte("foobar"))+len(leaf1.Script)+1),
tapscript,
)
estimator.AddP2WKHOutput()
estimatedWeight := estimator.Weight()
requiredFee := feeRate.FeeForWeight(estimatedWeight)
tx := wire.NewMsgTx(2)
tx.TxIn = []*wire.TxIn{{
PreviousOutPoint: p2trOutpoint,
}}
value := int64(testAmount - requiredFee)
tx.TxOut = []*wire.TxOut{{
PkScript: p2wkhPkScript,
Value: value,
}}
// We can now assemble the witness stack.
controlBlockBytes, err := tapscript.ControlBlock.ToBytes()
require.NoError(ht, err)
tx.TxIn[0].Witness = wire.TxWitness{
[]byte("foobar"),
leaf1.Script,
controlBlockBytes,
}
// Serialize, weigh and publish the TX now, then make sure the
// coins are sent and confirmed to the final sweep destination address.
publishTxAndConfirmSweep(
ht, alice, tx, estimatedWeight,
&chainrpc.SpendRequest{
Outpoint: &chainrpc.Outpoint{
Hash: p2trOutpoint.Hash[:],
Index: p2trOutpoint.Index,
},
Script: p2trPkScript,
},
p2wkhAddr.String(),
)
}
// testTaprootMuSig2CombinedLeafKeySpend tests that a MuSig2 combined key can be
// used for an OP_CHECKSIG inside a tap script leaf spend.
func testTaprootMuSig2CombinedLeafKeySpend(ht *lntest.HarnessTest,
alice *node.HarnessNode, version signrpc.MuSig2Version) {
// We're using the combined MuSig2 key in a script leaf. So we need to
// derive the combined key first, before we can build the script.
keyDesc1, keyDesc2, keyDesc3, allPubKeys := deriveSigningKeys(
ht, alice, version,
)
req := &signrpc.MuSig2CombineKeysRequest{
AllSignerPubkeys: allPubKeys,
Version: version,
}
combineResp := alice.RPC.MuSig2CombineKeys(req)
combinedPubKey, err := schnorr.ParsePubKey(combineResp.CombinedKey)
require.NoError(ht, err)
// We're going to commit to a script and spend the output using the
// script. This is just an OP_CHECKSIG with the combined MuSig2 public
// key.
leaf := testScriptSchnorrSig(ht.T, combinedPubKey)
tapscript := input.TapscriptPartialReveal(dummyInternalKey, leaf, nil)
taprootKey, err := tapscript.TaprootKey()
require.NoError(ht, err)
// Send some coins to the generated tapscript address.
p2trOutpoint, p2trPkScript := sendToTaprootOutput(ht, alice, taprootKey)
// Spend the output again, this time back to a p2wkh address.
p2wkhAddr, p2wkhPkScript := newAddrWithScript(
ht, alice, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
)
// Create fee estimation for a p2tr input and p2wkh output.
feeRate := chainfee.SatPerKWeight(12500)
estimator := input.TxWeightEstimator{}
estimator.AddTapscriptInput(
input.TaprootSignatureWitnessSize, tapscript,
)
estimator.AddP2WKHOutput()
estimatedWeight := estimator.Weight()
requiredFee := feeRate.FeeForWeight(estimatedWeight)
tx := wire.NewMsgTx(2)
tx.TxIn = []*wire.TxIn{{
PreviousOutPoint: p2trOutpoint,
}}
value := int64(testAmount - requiredFee)
tx.TxOut = []*wire.TxOut{{
PkScript: p2wkhPkScript,
Value: value,
}}
var buf bytes.Buffer
require.NoError(ht, tx.Serialize(&buf))
utxoInfo := []*signrpc.TxOut{{
PkScript: p2trPkScript,
Value: testAmount,
}}
// Do the actual signing now.
_, _, sessResp1, sessResp2, sessResp3 := createMuSigSessions(
ht, alice, nil, keyDesc1, keyDesc2, keyDesc3, allPubKeys,
version,
)
require.NoError(ht, err)