-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
717 lines (606 loc) · 20.7 KB
/
main.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
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"sync"
"github.com/btcsuite/btcd/btcec/v2"
// "github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/oxf71/musig2-demo/lib/go-ord-tx/pkg/btcapi/mempool"
"github.com/oxf71/musig2-demo/lib/go-ord-tx/pkg/ord"
musig2demo "github.com/oxf71/musig2-demo/musig2"
)
type bip340Test struct {
secretKey string
publicKey string
auxRand string
message string
signature string
verifyResult bool
validPubKey bool
expectErr error
rfc6979 bool
}
var bip340TestVectors = []bip340Test{
{
secretKey: "440bb3ec56d213e90d006d344d74f6478db4f7fa4cdd388095d8f4edef0c5156",
publicKey: "03d7ce6683d188fe474d0099fc1035017761be40f7a6c50f3b2f459e1c128eac6a",
},
{
secretKey: "e0087817fd1d1154a781c11b394a0dcec82f076bbf026df9d61667ead16fa778",
publicKey: "03f07fc321723c0516f524315470c32aa54a0150bffb8bee113334e5b1e356563d", // mycjLUFZ1Lo4GwaXoB9RAVFnG81AJGQy2a
},
}
func decodeHex(hexStr string) []byte {
b, err := hex.DecodeString(hexStr)
if err != nil {
panic("invalid hex string in test source: err " + err.Error() +
", hex: " + hexStr)
}
return b
}
func sign() {
test := bip340TestVectors[0]
d := decodeHex(test.secretKey)
privKey, _ := btcec.PrivKeyFromBytes(d)
var auxBytes [32]byte
aux := decodeHex(test.auxRand)
copy(auxBytes[:], aux)
msg := decodeHex(test.message)
fmt.Println("publicKey:", string(privKey.PubKey().SerializeCompressed()))
sig, err := schnorr.Sign(privKey, msg)
if err != nil {
log.Fatal(err)
}
sigStr := strings.ToUpper(hex.EncodeToString(sig.Serialize()))
fmt.Println(sigStr)
}
func verify() {
// privKey, err := btcec.NewPrivateKey()
// if err != nil {
// log.Fatalf("unable to gen priv key: %v", err)
// }
// pubKey := privKey.PubKey()
// pk := hex.EncodeToString(privKey.Serialize())
// pubK := hex.EncodeToString(pubKey.SerializeCompressed())
// address, err := btcutil.NewAddressPubKey(pubKey.SerializeCompressed(), &chaincfg.TestNet3Params)
// if err != nil {
// log.Fatalf("unable to gen pub key: %v", err)
// }
// fmt.Println(pk)
// fmt.Println(pubK)
// fmt.Println(address.EncodeAddress())
var combinedKey *btcec.PublicKey
signerKeys := make([]*btcec.PrivateKey, len(bip340TestVectors))
signSet := make([]*btcec.PublicKey, len(bip340TestVectors))
for i, v := range bip340TestVectors {
d := decodeHex(v.secretKey)
privKey, _ := btcec.PrivKeyFromBytes(d)
pubKey := privKey.PubKey()
signerKeys[i] = privKey
signSet[i] = pubKey
}
var ctxOpts []musig2.ContextOption
// taprootTweak := [32]byte{
// 0xE8, 0xF7, 0x91, 0xFF, 0x92, 0x25, 0xA2, 0xAF,
// 0x01, 0x02, 0xAF, 0xFF, 0x4A, 0x9A, 0x72, 0x3D,
// 0x96, 0x12, 0xA6, 0x82, 0xA2, 0x5E, 0xBE, 0x79,
// 0x80, 0x2B, 0x26, 0x3C, 0xDF, 0xCD, 0x83, 0xBB,
// }
// // // taprootTweak := musig2.KeyTweakDesc{
// // // Tweak: testTweak,
// // // IsXOnly: true,
// // // }
// // taprootTweak := []byte{}
// switch {
// case len(taprootTweak) == 0:
// ctxOpts = append(ctxOpts, musig2.WithBip86TweakCtx())
// case taprootTweak[:] != nil:
// ctxOpts = append(ctxOpts, musig2.WithTaprootTweakCtx(taprootTweak[:]))
// // case len(tweaks) != 0:
// // ctxOpts = append(ctxOpts, musig2.WithTweakedContext(tweaks...))
// }
ctxOpts = append(ctxOpts, musig2.WithKnownSigners(signSet))
signers := make([]*musig2.Session, 2)
for i, signerKey := range signerKeys {
signCtx, err := musig2.NewContext(
signerKey, false, ctxOpts...,
)
if err != nil {
log.Fatalf("unable to generate context: %v", err)
}
if combinedKey == nil {
combinedKey, err = signCtx.CombinedKey()
if err != nil {
log.Fatalf("combined key not available: %v", err)
}
}
session, err := signCtx.NewSession()
if err != nil {
log.Fatalf("unable to generate new session: %v", err)
}
signers[i] = session
}
combined := hex.EncodeToString(combinedKey.SerializeCompressed())
combinedAddress, err := btcutil.NewAddressPubKey(combinedKey.SerializeCompressed(), &chaincfg.TestNet3Params)
if err != nil {
log.Fatalf("unable to gen pub key: %v", err)
}
fmt.Println("combined: ", combined)
fmt.Println("combined address: ", combinedAddress.EncodeAddress())
utxoTaprootAddress, err := btcutil.NewAddressTaproot(schnorr.SerializePubKey(txscript.ComputeTaprootKeyNoScript(combinedKey)), &chaincfg.TestNet3Params)
if err != nil {
log.Fatal(err)
}
fmt.Println("utxo taproot address: ", utxoTaprootAddress.EncodeAddress())
}
func musig2_demo() {
// 聚合签名 pub key
var combinedKey *btcec.PublicKey
// 私钥1
privKey1, _ := btcec.PrivKeyFromBytes(decodeHex(bip340TestVectors[0].secretKey))
pubKey1 := privKey1.PubKey()
// 私钥2
privKey2, _ := btcec.PrivKeyFromBytes(decodeHex(bip340TestVectors[1].secretKey))
pubKey2 := privKey2.PubKey()
signSet := make([]*btcec.PublicKey, len(bip340TestVectors))
signSet = append(signSet, pubKey1, pubKey2)
//
var ctxOpts []musig2.ContextOption
ctxOpts = append(ctxOpts, musig2.WithKnownSigners(signSet))
ctxOpts = append(ctxOpts, musig2.WithBip86TweakCtx())
fmt.Println(ctxOpts)
signCtx1, err := musig2.NewContext(
privKey1, false, ctxOpts...,
)
if err != nil {
log.Fatalf("unable to generate context: %v", err)
}
if combinedKey == nil {
combinedKey, err = signCtx1.CombinedKey()
if err != nil {
log.Fatalf("combined key not available: %v", err)
}
}
session1, err := signCtx1.NewSession()
if err != nil {
log.Fatalf("unable to generate new session: %v", err)
}
session2, err := session(privKey2, combinedKey, ctxOpts...)
if err != nil {
log.Fatalf("unable to generate new session: %v", err)
}
combined := hex.EncodeToString(combinedKey.SerializeCompressed())
combinedAddress, err := btcutil.NewAddressPubKey(combinedKey.SerializeCompressed(), &chaincfg.TestNet3Params)
if err != nil {
log.Fatalf("unable to gen pub key: %v", err)
}
fmt.Println("combined: ", combined)
fmt.Println("combined address: ", combinedAddress.EncodeAddress())
utxoTaprootAddress, err := btcutil.NewAddressTaproot(schnorr.SerializePubKey(txscript.ComputeTaprootKeyNoScript(combinedKey)), &chaincfg.TestNet3Params)
if err != nil {
log.Fatal(err)
}
fmt.Println("utxo taproot address: ", utxoTaprootAddress.EncodeAddress())
signers := make([]*musig2.Session, 2)
signers = append(signers, session1, session2)
// Next, in the pre-signing phase, we'll send all the nonces to each
// signer.
var wg sync.WaitGroup
for i, signCtx := range signers {
signCtx := signCtx
wg.Add(1)
go func(idx int, signer *musig2.Session) {
defer wg.Done()
for j, otherCtx := range signers {
if idx == j {
continue
}
nonce := otherCtx.PublicNonce()
haveAll, err := signer.RegisterPubNonce(nonce)
if err != nil {
log.Fatalf("unable to add public nonce")
}
if j == len(signers)-1 && !haveAll {
log.Fatalf("all public nonces should have been detected")
}
}
}(i, signCtx)
}
wg.Wait()
msg := sha256.Sum256([]byte("let's get taprooty"))
_, err = session1.Sign(msg)
if err != nil {
log.Fatalf("unable to generate partial sig: %v", err)
}
partialSig2, err := session2.Sign(msg)
if err != nil {
log.Fatalf("unable to generate partial sig: %v", err)
}
haveAll, err := session1.CombineSig(partialSig2)
if err != nil {
log.Fatalf("unable to combine sigs: %v", err)
}
if !haveAll {
log.Fatalf("final sig wasn't reconstructed")
}
}
func musig2_early_demo() {
// btcec.PrivKeyFromBytes(decodeHex(bip340TestVectors[0].secretKey))
privKey1, _ := btcec.PrivKeyFromBytes(decodeHex(bip340TestVectors[0].secretKey))
privKey2, _ := btcec.PrivKeyFromBytes(decodeHex(bip340TestVectors[0].secretKey))
// privKey1, err := btcec.NewPrivateKey()
// if err != nil {
// log.Fatalf("unable to gen priv key: %v", err)
// }
// privKey2, err := btcec.NewPrivateKey()
// if err != nil {
// log.Fatalf("unable to gen priv key: %v", err)
// }
// If we try to make a context, with just the private key and sorting
// value, we should get an error.
_, err := musig2.NewContext(privKey1, true)
if !errors.Is(err, musig2.ErrSignersNotSpecified) {
log.Fatalf("unexpected ctx error: %v", err)
}
signers := []*btcec.PublicKey{privKey1.PubKey(), privKey2.PubKey()}
numSigners := len(signers)
ctx1, err := musig2.NewContext(
privKey1, true, musig2.WithNumSigners(numSigners), musig2.WithEarlyNonceGen(),
)
if err != nil {
log.Fatalf("unable to make ctx: %v", err)
}
pubKey1 := ctx1.PubKey()
ctx2, err := musig2.NewContext(
privKey2, true, musig2.WithKnownSigners(signers), musig2.WithEarlyNonceGen(),
)
if err != nil {
log.Fatalf("unable to make ctx: %v", err)
}
pubKey2 := ctx2.PubKey()
// At this point, the combined key shouldn't be available for signer 1,
// but should be for signer 2, as they know about all signers.
if _, err := ctx1.CombinedKey(); !errors.Is(err, musig2.ErrNotEnoughSigners) {
log.Fatalf("unepxected error: %v", err)
}
_, err = ctx2.CombinedKey()
if err != nil {
log.Fatalf("unable to get combined key: %v", err)
}
// The early nonces _should_ be available at this point.
nonce1, err := ctx1.EarlySessionNonce()
if err != nil {
log.Fatalf("session nonce not available: %v", err)
}
nonce2, err := ctx2.EarlySessionNonce()
if err != nil {
log.Fatalf("session nonce not available: %v", err)
}
// The number of registered signers should still be 1 for both parties.
if ctx1.NumRegisteredSigners() != 1 {
log.Fatalf("expected 1 signer, instead have: %v",
ctx1.NumRegisteredSigners())
}
if ctx2.NumRegisteredSigners() != 2 {
log.Fatalf("expected 2 signers, instead have: %v",
ctx2.NumRegisteredSigners())
}
// If we try to make a session, we should get an error since we dn't
// have all the signers yet.
if _, err := ctx1.NewSession(); !errors.Is(err, musig2.ErrNotEnoughSigners) {
log.Fatalf("unexpected session key error: %v", err)
}
// The combined key should also be unavailable as well.
if _, err := ctx1.CombinedKey(); !errors.Is(err, musig2.ErrNotEnoughSigners) {
log.Fatalf("unexpected combined key error: %v", err)
}
// We'll now register the other signer for party 1.
done, err := ctx1.RegisterSigner(&pubKey2)
if err != nil {
log.Fatalf("unable to register signer: %v", err)
}
if !done {
log.Fatalf("signer 1 doesn't have all keys")
}
// If we try to register the signer again, we should get an error.
_, err = ctx2.RegisterSigner(&pubKey1)
if !errors.Is(err, musig2.ErrAlreadyHaveAllSigners) {
log.Fatalf("should not be able to register too many signers")
}
// We should be able to create the session at this point.
session1, err := ctx1.NewSession()
if err != nil {
log.Fatalf("unable to create new session: %v", err)
}
session2, err := ctx2.NewSession()
if err != nil {
log.Fatalf("unable to create new session: %v", err)
}
msg := sha256.Sum256([]byte("let's get taprooty, LN style"))
// If we try to sign before we have the combined nonce, we shoudl get
// an error.
_, err = session1.Sign(msg)
if !errors.Is(err, musig2.ErrCombinedNonceUnavailable) {
log.Fatalf("unable to gen sig: %v", err)
}
// Now we can exchange nonces to continue with the rest of the signing
// process as normal.
done, err = session1.RegisterPubNonce(nonce2.PubNonce)
if err != nil {
log.Fatalf("unable to register nonce: %v", err)
}
if !done {
log.Fatalf("signer 1 doesn't have all nonces")
}
done, err = session2.RegisterPubNonce(nonce1.PubNonce)
if err != nil {
log.Fatalf("unable to register nonce: %v", err)
}
if !done {
log.Fatalf("signer 2 doesn't have all nonces")
}
// Registering the nonce again should error out.
_, err = session2.RegisterPubNonce(nonce1.PubNonce)
if !errors.Is(err, musig2.ErrAlredyHaveAllNonces) {
log.Fatalf("shouldn't be able to register nonces twice")
}
// Sign the message and combine the two partial sigs into one.
_, err = session1.Sign(msg)
if err != nil {
log.Fatalf("unable to gen sig: %v", err)
}
sig2, err := session2.Sign(msg)
if err != nil {
log.Fatalf("unable to gen sig: %v", err)
}
done, err = session1.CombineSig(sig2)
if err != nil {
log.Fatalf("unable to combine sig: %v", err)
}
if !done {
log.Fatalf("all sigs should be known now: %v", err)
}
// If we try to combine another sig, then we should get an error.
_, err = session1.CombineSig(sig2)
if !errors.Is(err, musig2.ErrAlredyHaveAllSigs) {
log.Fatalf("shouldn't be able to combine again")
}
// Finally, verify that the final signature is valid.
combinedKey, err := ctx1.CombinedKey()
if err != nil {
log.Fatalf("unexpected combined key error: %v", err)
}
finalSig := session1.FinalSig()
if !finalSig.Verify(msg[:], combinedKey) {
log.Fatalf("final sig is invalid!")
}
combined := hex.EncodeToString(combinedKey.SerializeCompressed())
combinedAddress, err := btcutil.NewAddressPubKey(combinedKey.SerializeCompressed(), &chaincfg.TestNet3Params)
if err != nil {
log.Fatalf("unable to gen pub key: %v", err)
}
fmt.Println("combined: ", combined)
fmt.Println("combined address: ", combinedAddress.EncodeAddress())
utxoTaprootAddress, err := btcutil.NewAddressTaproot(schnorr.SerializePubKey(txscript.ComputeTaprootKeyNoScript(combinedKey)), &chaincfg.TestNet3Params)
if err != nil {
log.Fatal(err)
}
fmt.Println("utxo taproot address: ", utxoTaprootAddress.EncodeAddress())
fmt.Println("finalSig: ", hex.EncodeToString(finalSig.Serialize()))
}
func session(privKey *btcec.PrivateKey, combinedKey *btcec.PublicKey, ctxOpts ...musig2.ContextOption) (*musig2.Session, error) {
signCtx2, err := musig2.NewContext(
privKey, false, ctxOpts...,
)
if err != nil {
log.Fatalf("unable to generate context: %v", err)
}
if combinedKey == nil {
combinedKey, err = signCtx2.CombinedKey()
if err != nil {
log.Fatalf("combined key not available: %v", err)
}
}
return signCtx2.NewSession()
}
func RawTxInSignature(tx *wire.MsgTx, idx int, subScript []byte,
hashType txscript.SigHashType, key1 *btcec.PrivateKey, key2 *btcec.PrivateKey) ([]byte, error) {
hash, err := txscript.CalcSignatureHash(subScript, hashType, tx, idx)
if err != nil {
return nil, err
}
// signature := ecdsa.Sign(key1, hash)
msg := sha256.Sum256(hash)
signature, hash, err := musig2demo.TwoPrivSign2(key1, key2, msg)
if err != nil {
log.Fatal(err)
}
return append(signature.Serialize(), byte(hashType)), nil
}
func SignatureScript(tx *wire.MsgTx, idx int, subscript []byte, hashType txscript.SigHashType, privKey1 *btcec.PrivateKey, privKey2 *btcec.PrivateKey, compress bool) ([]byte, error) {
sig, err := RawTxInSignature(tx, idx, subscript, hashType, privKey1, privKey2)
if err != nil {
return nil, err
}
pk, err := musig2demo.TwoCombinedKey(privKey1, privKey2)
if err != nil {
log.Fatal(err)
}
// pk := privKey.PubKey()
var pkData []byte
if compress {
pkData = pk.SerializeCompressed()
} else {
pkData = pk.SerializeUncompressed()
}
return txscript.NewScriptBuilder().AddData(sig).AddData(pkData).Script()
}
func sendTransaction() {
netParams := &chaincfg.SigNetParams
btcApiClient := mempool.NewClient(netParams)
// privateKeyHex02 := "4ef5cb1fd5afd08ca9acbe5d077d89f1e095f67616a326d368851e57a92d1bab"
// privateKeyByte02, _ := hex.DecodeString(privateKeyHex02)
// privateKeyBytes02 := privateKeyByte02 // 用你自己的私钥替换这里的字节
// privateKey02, publicKey02 := btcec.PrivKeyFromBytes(privateKeyBytes02)
// // 根据公钥生成比特币地址
// addressPubKeyHash01 := btcutil.Hash160(publicKey02.SerializeCompressed())
// address02, err := btcutil.NewAddressPubKeyHash(addressPubKeyHash01, &chaincfg.TestNet3Params)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println("address: ", address02)
// 找零地址
changeAddress, err := btcutil.DecodeAddress("tb1prggx0jcdqgag2kj9agxa7n6p888ffpzs4flps8ztwctrluz040hq6x9sz8", netParams)
if err != nil {
fmt.Println("DecodeAddress err:", err)
return
}
privKey1, _ := btcec.PrivKeyFromBytes(decodeHex("440bb3ec56d213e90d006d344d74f6478db4f7fa4cdd388095d8f4edef0c5156"))
privKey2, _ := btcec.PrivKeyFromBytes(decodeHex(bip340TestVectors[1].secretKey))
musig2BtcTaprootAddress := musig2demo.TwoBtcTaprootAddress(privKey1, privKey2)
// fmt.Println("taprootAddress: ", taprootAddress)
// addressPubKeyHash01 := btcutil.Hash160(musig2BtcAddress.SerializeCompressed())
// address02, err := btcutil.NewAddressPubKeyHash(addressPubKeyHash01, &chaincfg.TestNet3Params)
// if err != nil {
// log.Fatal(err)
// }
// mulsigAddr, err := btcutil.DecodeAddress(musig2BtcAddress, &chaincfg.TestNet3Params)
// if err != nil {
// fmt.Println("DecodeAddress err:", err)
// return
// }
// fmt.Println("taprootAddress: ", taprootAddress)
addressPubKey1 := btcutil.Hash160(privKey1.PubKey().SerializeCompressed())
address01, err := btcutil.NewAddressPubKeyHash(addressPubKey1, netParams)
if err != nil {
log.Fatal(err)
}
// mulsigAddr := musig2BtcTaprootAddress
fmt.Println("mulsigAddr:", musig2BtcTaprootAddress)
fmt.Println("address 1", address01)
musig2Address, err := btcutil.DecodeAddress("tb1prggx0jcdqgag2kj9agxa7n6p888ffpzs4flps8ztwctrluz040hq6x9sz8", netParams)
if err != nil {
fmt.Println("DecodeAddress err:", err)
return
}
unspentList, err := btcApiClient.ListUnspent(musig2Address)
if err != nil {
fmt.Println("ListUnspent err:", err)
return
}
if len(unspentList) == 0 {
return
}
fmt.Println("000000:", len(unspentList))
// 创建比特币交易输入和输出
totalSenderAmount := btcutil.Amount(0)
tx := wire.NewMsgTx(wire.TxVersion)
for i := range unspentList {
in := wire.NewTxIn(unspentList[i].Outpoint, nil, nil)
tx.AddTxIn(in)
totalSenderAmount += btcutil.Amount(unspentList[i].Output.Value)
}
// 获取目标地址的比特币脚本
destAddress, err := btcutil.DecodeAddress("tb1prggx0jcdqgag2kj9agxa7n6p888ffpzs4flps8ztwctrluz040hq6x9sz8", netParams)
if err != nil {
fmt.Println("DecodeAddress err:", err)
return
}
destinationScript, err := txscript.PayToAddrScript(destAddress)
if err != nil {
fmt.Println("PayToAddrScript err:", err)
return
}
// 计算总金额和交易费用
var fee int64 = 1000
changeAmount := int64(totalSenderAmount) - 2000 - fee // 减去交易费用,转账2000
fmt.Println("0000: ", int64(totalSenderAmount))
// 添加目标地址作为交易输出
tx.AddTxOut(wire.NewTxOut(2000, destinationScript))
var changeScript []byte
if changeAmount > 0 {
// 添加找零地址作为交易输出
changeScript, err = txscript.PayToAddrScript(changeAddress)
if err != nil {
fmt.Println("PayToAddrScript err:", err)
return
}
tx.AddTxOut(wire.NewTxOut(changeAmount, changeScript))
}
// 构建多签赎回脚本
for i, v := range tx.TxIn {
// sigScriptB, err := SignatureScript(tx, i, changeScript, txscript.SigHashDefault, privKey1, privKey2, true)
// if err != nil {
// fmt.Println("SignatureScript:", err)
// return
// }
// fmt.Println("sigScriptB:", sigScriptB)
txOut := txscript.NewMultiPrevOutFetcher(nil).FetchPrevOutput(v.PreviousOutPoint)
witness, err := ord.TaprootWitnessSignature(
tx,
txscript.NewTxSigHashes(tx, txscript.NewMultiPrevOutFetcher(nil)),
i,
txOut.Value,
txOut.PkScript,
txscript.SigHashDefault,
privKey1,
nil,
// tool.txCtxDataList[0].controlBlockWitness,
)
if err != nil {
log.Fatal(err)
}
v.Witness = witness
// witnessList[i] = witness
// v.Witness = wire.TxWitness{sigScriptB.Serialize(), hash}
// v.SignatureScript = sigScriptB
}
txjsondata, err := json.Marshal(tx)
if err != nil {
fmt.Println("json.Marshal err:", err)
return
}
fmt.Println("txjsondata:", string(txjsondata))
// 发送交易
txHash, err := btcApiClient.BroadcastTx(tx)
if err != nil {
fmt.Println("BroadcastTx err:", err)
return
}
fmt.Printf("转账成功!交易哈希:%s\n", txHash.String())
}
func main() {
// sendTransaction()
privKey1, _ := btcec.PrivKeyFromBytes(decodeHex(bip340TestVectors[0].secretKey))
privKey2, _ := btcec.PrivKeyFromBytes(decodeHex(bip340TestVectors[1].secretKey))
musig2_early_demo()
msg := sha256.Sum256([]byte("msg hello"))
sign, hash, err := musig2demo.TwoPrivSign2(privKey1, privKey2, msg)
if err != nil {
log.Fatal(err)
}
fmt.Println("sign: ", hex.EncodeToString(sign.Serialize()))
fmt.Println("sign hash", hex.EncodeToString(hash))
btcAddress := musig2demo.TwoBtcAddress(privKey1, privKey2)
fmt.Println("btcAddress: ", btcAddress)
taprootAddress := musig2demo.TwoBtcTaprootAddress(privKey1, privKey2)
fmt.Println("taprootAddress: ", taprootAddress)
// verify sign
combinedKey, err := musig2demo.TwoCombinedKey(privKey1, privKey2)
if err != nil {
log.Fatal(err)
}
fmt.Println("combinedKey", combinedKey.SerializeCompressed())
fmt.Println("sign verify: ", sign.Verify(hash, combinedKey))
}