forked from arkade-os/emulator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils_test.go
More file actions
771 lines (637 loc) · 21.2 KB
/
Copy pathutils_test.go
File metadata and controls
771 lines (637 loc) · 21.2 KB
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
package test
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
"slices"
"strings"
"testing"
"time"
"github.com/ArkLabsHQ/introspector/pkg/arkade"
introspectorclient "github.com/ArkLabsHQ/introspector/pkg/client"
arklib "github.com/arkade-os/arkd/pkg/ark-lib"
"github.com/arkade-os/arkd/pkg/ark-lib/asset"
"github.com/arkade-os/arkd/pkg/ark-lib/extension"
"github.com/arkade-os/arkd/pkg/ark-lib/offchain"
"github.com/arkade-os/arkd/pkg/ark-lib/script"
"github.com/arkade-os/arkd/pkg/ark-lib/tree"
"github.com/arkade-os/arkd/pkg/ark-lib/txutils"
arksdk "github.com/arkade-os/go-sdk"
"github.com/arkade-os/go-sdk/client"
"github.com/arkade-os/go-sdk/explorer"
inmemorystoreconfig "github.com/arkade-os/go-sdk/store/inmemory"
"github.com/arkade-os/go-sdk/wallet"
singlekeywallet "github.com/arkade-os/go-sdk/wallet/singlekey"
inmemorystore "github.com/arkade-os/go-sdk/wallet/singlekey/store/inmemory"
"github.com/btcsuite/btcd/btcec/v2"
"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/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type delegateBatchEventsHandler struct {
intentId string
intent introspectorclient.Intent
vtxosToForfeit []client.TapscriptsVtxo
signerSession tree.SignerSession
introspectorClient introspectorclient.TransportClient
wallet wallet.WalletService
client client.TransportClient
explorer explorer.Explorer
forfeitAddress string
batchExpiry arklib.RelativeLocktime
cacheBatchId string
}
func (h *delegateBatchEventsHandler) OnBatchStarted(
ctx context.Context, event client.BatchStartedEvent,
) (bool, error) {
buf := sha256.Sum256([]byte(h.intentId))
hashedIntentId := hex.EncodeToString(buf[:])
for _, hash := range event.HashedIntentIds {
if hash == hashedIntentId {
if err := h.client.ConfirmRegistration(ctx, h.intentId); err != nil {
return false, err
}
h.cacheBatchId = event.Id
h.batchExpiry = getBatchExpiryLocktime(uint32(event.BatchExpiry))
return false, nil
}
}
return true, nil
}
func (h *delegateBatchEventsHandler) OnBatchFinalized(
_ context.Context, event client.BatchFinalizedEvent,
) error {
return nil
}
func (h *delegateBatchEventsHandler) OnBatchFailed(
_ context.Context, event client.BatchFailedEvent,
) error {
if event.Id == h.cacheBatchId {
return fmt.Errorf("batch failed: %s", event.Reason)
}
return nil
}
func (h *delegateBatchEventsHandler) OnTreeTxEvent(context.Context, client.TreeTxEvent) error {
return nil
}
func (h *delegateBatchEventsHandler) OnTreeSignatureEvent(context.Context, client.TreeSignatureEvent) error {
return nil
}
func (h *delegateBatchEventsHandler) OnTreeSigningStarted(
ctx context.Context, event client.TreeSigningStartedEvent, vtxoTree *tree.TxTree,
) (bool, error) {
myPubkey := h.signerSession.GetPublicKey()
if !slices.Contains(event.CosignersPubkeys, myPubkey) {
return true, nil
}
arkInfos, err := h.client.GetInfo(ctx)
if err != nil {
return false, err
}
h.forfeitAddress = arkInfos.ForfeitAddress
forfeitPubKeyBytes, err := hex.DecodeString(arkInfos.ForfeitPubKey)
if err != nil {
return false, err
}
forfeitPubKey, err := btcec.ParsePubKey(forfeitPubKeyBytes)
if err != nil {
return false, err
}
sweepClosure := script.CSVMultisigClosure{
MultisigClosure: script.MultisigClosure{PubKeys: []*btcec.PublicKey{forfeitPubKey}},
Locktime: h.batchExpiry,
}
script, err := sweepClosure.Script()
if err != nil {
return false, err
}
commitmentTx, err := psbt.NewFromRawBytes(strings.NewReader(event.UnsignedCommitmentTx), true)
if err != nil {
return false, err
}
batchOutput := commitmentTx.UnsignedTx.TxOut[0]
batchOutputAmount := batchOutput.Value
sweepTapLeaf := txscript.NewBaseTapLeaf(script)
sweepTapTree := txscript.AssembleTaprootScriptTree(sweepTapLeaf)
root := sweepTapTree.RootNode.TapHash()
generateAndSendNonces := func(session tree.SignerSession) error {
if err := session.Init(root.CloneBytes(), batchOutputAmount, vtxoTree); err != nil {
return err
}
nonces, err := session.GetNonces()
if err != nil {
return err
}
return h.client.SubmitTreeNonces(ctx, event.Id, session.GetPublicKey(), nonces)
}
if err := generateAndSendNonces(h.signerSession); err != nil {
return false, err
}
return false, nil
}
func (h *delegateBatchEventsHandler) OnTreeNonces(context.Context, client.TreeNoncesEvent) (
bool, error,
) {
return false, nil
}
func (h *delegateBatchEventsHandler) OnTreeNoncesAggregated(
ctx context.Context, event client.TreeNoncesAggregatedEvent,
) (bool, error) {
h.signerSession.SetAggregatedNonces(event.Nonces)
sigs, err := h.signerSession.Sign()
if err != nil {
return false, err
}
err = h.client.SubmitTreeSignatures(
ctx,
event.Id,
h.signerSession.GetPublicKey(),
sigs,
)
return err == nil, err
}
func (h *delegateBatchEventsHandler) OnBatchFinalization(
ctx context.Context, event client.BatchFinalizationEvent,
vtxoTree, connectorTree *tree.TxTree,
) error {
if len(h.vtxosToForfeit) <= 0 {
return nil
}
if connectorTree == nil {
return fmt.Errorf("connector tree is nil")
}
forfeits, err := h.createAndSignForfeits(ctx, h.vtxosToForfeit, connectorTree.Leaves())
if err != nil {
return err
}
flatConnectorTree, err := connectorTree.Serialize()
if err != nil {
return err
}
signedForfeits, signedCommitmentTx, err := h.introspectorClient.SubmitFinalization(
ctx, h.intent, forfeits, flatConnectorTree, event.Tx,
)
if err != nil {
return err
}
return h.client.SubmitSignedForfeitTxs(ctx, signedForfeits, signedCommitmentTx)
}
func (h *delegateBatchEventsHandler) OnStreamStarted(_ context.Context, _ client.StreamStartedEvent) error {
return nil
}
func (h *delegateBatchEventsHandler) createAndSignForfeits(
ctx context.Context, vtxosToSign []client.TapscriptsVtxo, connectorsLeaves []*psbt.Packet,
) ([]string, error) {
parsedForfeitAddr, err := btcutil.DecodeAddress(h.forfeitAddress, nil)
if err != nil {
return nil, err
}
forfeitPkScript, err := txscript.PayToAddrScript(parsedForfeitAddr)
if err != nil {
return nil, err
}
signedForfeitTxs := make([]string, 0, len(vtxosToSign))
for i, vtxo := range vtxosToSign {
connectorTx := connectorsLeaves[i]
var connector *wire.TxOut
var connectorOutpoint *wire.OutPoint
for outIndex, output := range connectorTx.UnsignedTx.TxOut {
if bytes.Equal(txutils.ANCHOR_PKSCRIPT, output.PkScript) {
continue
}
connector = output
connectorOutpoint = &wire.OutPoint{
Hash: connectorTx.UnsignedTx.TxHash(),
Index: uint32(outIndex),
}
break
}
if connector == nil {
return nil, fmt.Errorf("connector not found for vtxo %s", vtxo.Outpoint.String())
}
vtxoScript, err := script.ParseVtxoScript(vtxo.Tapscripts)
if err != nil {
return nil, err
}
vtxoTapKey, vtxoTapTree, err := vtxoScript.TapTree()
if err != nil {
return nil, err
}
vtxoOutputScript, err := script.P2TRScript(vtxoTapKey)
if err != nil {
return nil, err
}
vtxoTxHash, err := chainhash.NewHashFromStr(vtxo.Txid)
if err != nil {
return nil, err
}
vtxoInput := &wire.OutPoint{
Hash: *vtxoTxHash,
Index: vtxo.VOut,
}
forfeitClosures := vtxoScript.ForfeitClosures()
if len(forfeitClosures) <= 0 {
return nil, fmt.Errorf("no forfeit closures found")
}
forfeitClosure := forfeitClosures[0]
forfeitScript, err := forfeitClosure.Script()
if err != nil {
return nil, err
}
forfeitLeaf := txscript.NewBaseTapLeaf(forfeitScript)
leafProof, err := vtxoTapTree.GetTaprootMerkleProof(forfeitLeaf.TapHash())
if err != nil {
return nil, err
}
tapscript := psbt.TaprootTapLeafScript{
ControlBlock: leafProof.ControlBlock,
Script: leafProof.Script,
LeafVersion: txscript.BaseLeafVersion,
}
vtxoLocktime := arklib.AbsoluteLocktime(0)
if cltv, ok := forfeitClosure.(*script.CLTVMultisigClosure); ok {
vtxoLocktime = cltv.Locktime
}
vtxoPrevout := &wire.TxOut{
Value: int64(vtxo.Amount),
PkScript: vtxoOutputScript,
}
vtxoSequence := wire.MaxTxInSequenceNum
if vtxoLocktime != 0 {
vtxoSequence = wire.MaxTxInSequenceNum - 1
}
forfeitTx, err := tree.BuildForfeitTx(
[]*wire.OutPoint{vtxoInput, connectorOutpoint},
[]uint32{vtxoSequence, wire.MaxTxInSequenceNum},
[]*wire.TxOut{vtxoPrevout, connector},
forfeitPkScript,
uint32(vtxoLocktime),
)
if err != nil {
return nil, err
}
forfeitTx.Inputs[0].TaprootLeafScript = []*psbt.TaprootTapLeafScript{&tapscript}
b64, err := forfeitTx.B64Encode()
if err != nil {
return nil, err
}
signedForfeitTx, err := h.wallet.SignTransaction(ctx, h.explorer, b64)
if err != nil {
return nil, err
}
signedForfeitTxs = append(signedForfeitTxs, signedForfeitTx)
}
return signedForfeitTxs, nil
}
type boardingBatchEventsHandler struct {
*delegateBatchEventsHandler
boardingVtxo client.TapscriptsVtxo
}
func (h *boardingBatchEventsHandler) OnBatchFinalization(
ctx context.Context, event client.BatchFinalizationEvent,
vtxoTree, connectorTree *tree.TxTree,
) error {
commitmentPtx, err := psbt.NewFromRawBytes(strings.NewReader(event.Tx), true)
if err != nil {
return err
}
boardingVtxoScript, err := script.ParseVtxoScript(h.boardingVtxo.Tapscripts)
if err != nil {
return err
}
forfeitClosures := boardingVtxoScript.ForfeitClosures()
if len(forfeitClosures) <= 0 {
return fmt.Errorf("no forfeit closures found")
}
forfeitClosure := forfeitClosures[0]
forfeitScript, err := forfeitClosure.Script()
if err != nil {
return err
}
_, taprootTree, err := boardingVtxoScript.TapTree()
if err != nil {
return err
}
forfeitLeaf := txscript.NewBaseTapLeaf(forfeitScript)
forfeitProof, err := taprootTree.GetTaprootMerkleProof(forfeitLeaf.TapHash())
if err != nil {
return fmt.Errorf(
"failed to get taproot merkle proof for boarding utxo: %s", err,
)
}
tapscript := &psbt.TaprootTapLeafScript{
ControlBlock: forfeitProof.ControlBlock,
Script: forfeitProof.Script,
LeafVersion: txscript.BaseLeafVersion,
}
for i := range commitmentPtx.Inputs {
prevout := commitmentPtx.UnsignedTx.TxIn[i].PreviousOutPoint
if h.boardingVtxo.Txid == prevout.Hash.String() &&
h.boardingVtxo.VOut == prevout.Index {
commitmentPtx.Inputs[i].TaprootLeafScript = []*psbt.TaprootTapLeafScript{
tapscript,
}
break
}
}
b64, err := commitmentPtx.B64Encode()
if err != nil {
return err
}
signedCommitmentTx, err := h.wallet.SignTransaction(ctx, h.explorer, b64)
if err != nil {
return err
}
_, signedCommitmentTx, err = h.introspectorClient.SubmitFinalization(
ctx, h.intent, []string{}, nil, signedCommitmentTx,
)
if err != nil {
return err
}
return h.client.SubmitSignedForfeitTxs(ctx, []string{}, signedCommitmentTx)
}
func getBatchExpiryLocktime(expiry uint32) arklib.RelativeLocktime {
if expiry >= 512 {
return arklib.RelativeLocktime{Type: arklib.LocktimeTypeSecond, Value: expiry}
}
return arklib.RelativeLocktime{Type: arklib.LocktimeTypeBlock, Value: expiry}
}
// setupBobWallet creates and unlocks a new wallet for Bob
func setupBobWallet(t *testing.T, ctx context.Context) (wallet.WalletService, *btcec.PrivateKey, *btcec.PublicKey) {
bobPrivKey, err := btcec.NewPrivateKey()
require.NoError(t, err)
configStore, err := inmemorystoreconfig.NewConfigStore()
require.NoError(t, err)
walletStore, err := inmemorystore.NewWalletStore()
require.NoError(t, err)
bobWallet, err := singlekeywallet.NewBitcoinWallet(configStore, walletStore)
require.NoError(t, err)
_, err = bobWallet.Create(ctx, password, hex.EncodeToString(bobPrivKey.Serialize()))
require.NoError(t, err)
_, err = bobWallet.Unlock(ctx, password)
require.NoError(t, err)
return bobWallet, bobPrivKey, bobPrivKey.PubKey()
}
// fundAndSettleAlice funds alice's account via boarding and settles
// sends 1$
func fundAndSettleAlice(t *testing.T, ctx context.Context, alice arksdk.ArkClient, amount int64) *arklib.Address {
_, offchainAddr, boardingAddress, err := alice.Receive(ctx)
require.NoError(t, err)
aliceAddr, err := arklib.DecodeAddressV0(offchainAddr)
require.NoError(t, err)
amountBtc := strings.TrimSuffix(btcutil.Amount(amount).Format(btcutil.AmountBTC), " BTC")
_, err = runCommand("nigiri", "faucet", boardingAddress, amountBtc)
require.NoError(t, err)
time.Sleep(5 * time.Second)
_, err = alice.Settle(ctx)
require.NoError(t, err)
time.Sleep(5 * time.Second)
return aliceAddr
}
// createIssuanceAssetPacket creates a simple asset issuance packet with one output
func createIssuanceAssetPacket(t *testing.T, vout uint16, amount uint64) asset.Packet {
assetOutput, err := asset.NewAssetOutput(vout, amount)
require.NoError(t, err)
assetGroup, err := asset.NewAssetGroup(
nil, // nil AssetId means issuance (will use current tx hash)
nil, // no control asset
[]asset.AssetInput{}, // no inputs (issuance)
[]asset.AssetOutput{*assetOutput},
[]asset.Metadata{}, // no metadata
)
require.NoError(t, err)
assetPacket, err := asset.NewPacket([]asset.AssetGroup{*assetGroup})
require.NoError(t, err)
return assetPacket
}
// createTransferAssetPacket creates an asset transfer packet for an existing asset
func createTransferAssetPacket(t *testing.T, mintTxHash chainhash.Hash, groupIndex uint16, vin uint16, vout uint16, amount uint64) asset.Packet {
assetId := &asset.AssetId{Txid: [asset.TX_HASH_SIZE]byte(mintTxHash), Index: groupIndex}
assetInput, err := asset.NewAssetInput(vin, amount)
require.NoError(t, err)
assetOutput, err := asset.NewAssetOutput(vout, amount)
require.NoError(t, err)
assetGroup, err := asset.NewAssetGroup(
assetId,
nil, // no control asset
[]asset.AssetInput{*assetInput},
[]asset.AssetOutput{*assetOutput},
[]asset.Metadata{},
)
require.NoError(t, err)
assetPacket, err := asset.NewPacket([]asset.AssetGroup{*assetGroup})
require.NoError(t, err)
return assetPacket
}
// createArkadeScriptWithAssetIntrospection creates an arkade script that verifies:
// - Output goes to specified address
// - Exactly 1 asset group
// - Asset output sum equals expected amount
func createArkadeScriptWithAssetIntrospection(t *testing.T, alicePkScript []byte, assetAmount int64) []byte {
arkadeScript, err := txscript.NewScriptBuilder().
// Check output 0 goes to alice's address
AddInt64(0).
AddOp(arkade.OP_INSPECTOUTPUTSCRIPTPUBKEY).
AddOp(arkade.OP_1).
AddOp(arkade.OP_EQUALVERIFY).
AddData(alicePkScript[2:]). // only witness program
AddOp(arkade.OP_EQUALVERIFY).
// Check: 1 asset group
AddOp(arkade.OP_INSPECTNUMASSETGROUPS).
AddInt64(1).
AddOp(arkade.OP_EQUALVERIFY).
// Check: sum of outputs for group 0 equals assetAmount
AddInt64(0). // group index
AddInt64(1). // source = outputs
AddOp(arkade.OP_INSPECTASSETGROUPSUM).
AddInt64(assetAmount).
AddOp(arkade.OP_EQUAL).
Script()
require.NoError(t, err)
return arkadeScript
}
// setupIntrospectorClient creates and returns an introspector client and its signer public key
func setupIntrospectorClient(t *testing.T, ctx context.Context) (introspectorclient.TransportClient, *btcec.PublicKey, *grpc.ClientConn) {
conn, err := grpc.NewClient("localhost:7073", grpc.WithTransportCredentials(insecure.NewCredentials()))
require.NoError(t, err)
introspectorClient := introspectorclient.NewGRPCClient(conn)
introspectorInfo, err := introspectorClient.GetInfo(ctx)
require.NoError(t, err)
require.NotNil(t, introspectorInfo)
publicKeyBytes, err := hex.DecodeString(introspectorInfo.SignerPublicKey)
require.NoError(t, err)
publicKey, err := btcec.ParsePubKey(publicKeyBytes)
require.NoError(t, err)
return introspectorClient, publicKey, conn
}
// createVtxoScriptWithArkadeScript creates a vtxo script with a multisig closure containing the arkade script pubkey
func createVtxoScriptWithArkadeScript(bobPubKey, aliceSigner, introspectorPubKey *btcec.PublicKey, arkadeScriptHash []byte) script.TapscriptsVtxoScript {
return script.TapscriptsVtxoScript{
Closures: []script.Closure{
&script.MultisigClosure{
PubKeys: []*btcec.PublicKey{
bobPubKey,
aliceSigner,
arkade.ComputeArkadeScriptPublicKey(introspectorPubKey, arkadeScriptHash),
},
},
},
}
}
// addIntrospectorPacket builds an IntrospectorPacket with the given entries and
// embeds it into the transaction's OP_RETURN output. If an existing ARK OP_RETURN
// (e.g. from an asset packet) is present, the introspector data is merged into it.
// Otherwise a new OP_RETURN is inserted before the last output (P2A anchor).
func addIntrospectorPacket(t *testing.T, ptx *psbt.Packet, entries []arkade.IntrospectorEntry) {
packet, err := arkade.NewPacket(entries...)
require.NoError(t, err)
// Look for an existing OP_RETURN with ARK extension (e.g. asset packet).
for i, out := range ptx.UnsignedTx.TxOut {
if !extension.IsExtension(out.PkScript) {
continue
}
// Parse existing extension and append the introspector packet.
ext, err := extension.NewExtensionFromBytes(out.PkScript)
if err != nil {
continue
}
ext = append(ext, packet)
combined, err := ext.Serialize()
require.NoError(t, err)
ptx.UnsignedTx.TxOut[i].PkScript = combined
return
}
// No existing ARK extension — insert a new one.
ext := extension.Extension{packet}
txOut, err := ext.TxOut()
require.NoError(t, err)
lastIdx := len(ptx.UnsignedTx.TxOut) - 1
lastOut := ptx.UnsignedTx.TxOut[lastIdx]
if bytes.Equal(lastOut.PkScript, txutils.ANCHOR_PKSCRIPT) {
// Insert before the P2A anchor so the server rebuild matches.
ptx.UnsignedTx.TxOut[lastIdx] = txOut
ptx.UnsignedTx.AddTxOut(lastOut)
} else {
// No anchor (e.g. intent proofs) — append at the end so payment
// output indices are not shifted.
ptx.UnsignedTx.AddTxOut(txOut)
}
ptx.Outputs = append(ptx.Outputs, psbt.POutput{})
}
// createVtxoScriptWithArkadeAndCSV creates a vtxo script with arkade closure + CSV closure
func createVtxoScriptWithArkadeAndCSV(bobPubKey, aliceSigner, introspectorPubKey *btcec.PublicKey, arkadeScriptHash []byte) script.TapscriptsVtxoScript {
return script.TapscriptsVtxoScript{
Closures: []script.Closure{
&script.MultisigClosure{
PubKeys: []*btcec.PublicKey{
bobPubKey,
aliceSigner,
arkade.ComputeArkadeScriptPublicKey(introspectorPubKey, arkadeScriptHash),
},
},
&script.CSVMultisigClosure{
MultisigClosure: script.MultisigClosure{
PubKeys: []*btcec.PublicKey{
bobPubKey,
aliceSigner,
},
},
Locktime: arklib.RelativeLocktime{Type: arklib.LocktimeTypeSecond, Value: 512 * 10},
},
},
}
}
// uint64LE returns an 8-byte little-endian encoding of v.
func uint64LE(v uint64) []byte {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, v)
return b
}
func checkpointInputPkScript(vtxoInput offchain.VtxoInput, checkpointScriptBytes []byte) ([]byte, error) {
signerUnrollScriptClosure := &script.CSVMultisigClosure{}
valid, err := signerUnrollScriptClosure.Decode(checkpointScriptBytes)
if err != nil {
return nil, err
}
if !valid {
return nil, fmt.Errorf("invalid signer unroll script")
}
collaborativeClosure, err := script.DecodeClosure(vtxoInput.Tapscript.RevealedScript)
if err != nil {
return nil, err
}
checkpointVtxoScript := script.TapscriptsVtxoScript{
Closures: []script.Closure{signerUnrollScriptClosure, collaborativeClosure},
}
tapKey, _, err := checkpointVtxoScript.TapTree()
if err != nil {
return nil, err
}
return script.P2TRScript(tapKey)
}
func debugExecuteArkadeScripts(t *testing.T, ptx *psbt.Packet, signerPublicKey *btcec.PublicKey) error {
t.Helper()
if len(ptx.Inputs) != len(ptx.UnsignedTx.TxIn) {
return fmt.Errorf("malformed psbt")
}
prevouts := make(map[wire.OutPoint]*wire.TxOut)
for index, input := range ptx.Inputs {
if input.WitnessUtxo == nil {
return fmt.Errorf("witness utxo is nil at input %d", index)
}
prevouts[ptx.UnsignedTx.TxIn[index].PreviousOutPoint] = input.WitnessUtxo
}
prevoutFetcher := txscript.NewMultiPrevOutFetcher(prevouts)
packet, err := arkade.FindIntrospectorPacket(ptx.UnsignedTx)
if err != nil {
return fmt.Errorf("failed to parse introspector packet: %w", err)
}
if len(packet) == 0 {
return fmt.Errorf("no introspector packet found in transaction")
}
for _, entry := range packet {
inputIndex := int(entry.Vin)
script, err := arkade.ReadArkadeScript(ptx, signerPublicKey, entry)
if err != nil {
return fmt.Errorf("failed to read arkade script at input %d: %w", inputIndex, err)
}
err = script.Execute(ptx.UnsignedTx, prevoutFetcher, inputIndex, arkade.WithDebugCallback(
func(step *arkade.StepInfo, engine *arkade.Engine) error {
disasm, err := engine.DisasmPC()
if err != nil {
disasm = "<done>"
}
t.Logf(
"vin=%d op=%s stack=%s altstack=%s",
inputIndex,
disasm,
formatHexStack(step.Stack),
formatHexStack(step.AltStack),
)
return nil
},
))
if err != nil {
return fmt.Errorf("failed to execute arkade script at input %d: %w", inputIndex, err)
}
}
return nil
}
func formatHexStack(items [][]byte) string {
if len(items) == 0 {
return "[]"
}
hexItems := make([]string, len(items))
for i := range items {
hexItems[i] = hex.EncodeToString(items[i])
}
return "[" + strings.Join(hexItems, " ") + "]"
}