-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathassets_test.go
More file actions
1138 lines (1006 loc) · 32.5 KB
/
Copy pathassets_test.go
File metadata and controls
1138 lines (1006 loc) · 32.5 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
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"
"context"
"crypto/tls"
"net/http"
"slices"
"strings"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/lightninglabs/taproot-assets/asset"
"github.com/lightninglabs/taproot-assets/commitment"
"github.com/lightninglabs/taproot-assets/fn"
"github.com/lightninglabs/taproot-assets/internal/test"
"github.com/lightninglabs/taproot-assets/proof"
"github.com/lightninglabs/taproot-assets/taprpc"
wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc"
"github.com/lightninglabs/taproot-assets/taprpc/mintrpc"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/stretchr/testify/require"
"golang.org/x/exp/maps"
"golang.org/x/net/http2"
"google.golang.org/protobuf/proto"
)
var (
simpleAssets = []*mintrpc.MintAssetRequest{
{
Asset: &mintrpc.MintAsset{
AssetType: taprpc.AssetType_NORMAL,
Name: "itestbuxx",
AssetMeta: &taprpc.AssetMeta{
Data: []byte("some metadata"),
},
Amount: 5000,
AssetVersion: taprpc.AssetVersion_ASSET_VERSION_V0,
},
},
{
Asset: &mintrpc.MintAsset{
AssetType: taprpc.AssetType_COLLECTIBLE,
Name: "itestbuxx-collectible",
AssetMeta: &taprpc.AssetMeta{
Data: []byte("some metadata"),
},
Amount: 1,
AssetVersion: taprpc.AssetVersion_ASSET_VERSION_V1,
},
},
}
issuableAssets = []*mintrpc.MintAssetRequest{
{
Asset: &mintrpc.MintAsset{
AssetType: taprpc.AssetType_NORMAL,
Name: "itestbuxx-money-printer-brrr",
AssetMeta: &taprpc.AssetMeta{
Data: []byte("some metadata"),
},
Amount: 5000,
AssetVersion: taprpc.AssetVersion_ASSET_VERSION_V1,
NewGroupedAsset: true,
},
},
{
Asset: &mintrpc.MintAsset{
AssetType: taprpc.AssetType_COLLECTIBLE,
Name: "itestbuxx-collectible-brrr",
AssetMeta: &taprpc.AssetMeta{
Data: []byte("some metadata"),
},
Amount: 1,
AssetVersion: taprpc.AssetVersion_ASSET_VERSION_V0,
NewGroupedAsset: true,
},
},
}
transport = &http2.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
client = http.Client{
Transport: transport,
Timeout: 1 * time.Second,
}
)
// testMintAssets tests that we're able to mint assets, retrieve their proofs
// and that we're able to import the proofs into a new node.
func testMintAssets(t *harnessTest) {
ctx := context.Background()
rpcSimpleAssets := MintAssetsConfirmBatch(
t.t, t.lndHarness.Miner(), t.tapd, simpleAssets,
)
rpcIssuableAssets := MintAssetsConfirmBatch(
t.t, t.lndHarness.Miner(), t.tapd, issuableAssets,
)
// Now that all our assets have been issued, we'll use the balance
// calls to ensure that we're able to retrieve the proper balance for
// them all.
AssertMintedAssetBalances(
t.t, t.tapd, rpcSimpleAssets, rpcIssuableAssets, false,
)
AssertBalances(
t.t, t.tapd, 10002, WithNumUtxos(4), WithNumAnchorUtxos(2),
WithGroupedAssetBalance(5001),
WithScriptKeyType(asset.ScriptKeyBip86),
)
// Check that we can retrieve the group keys for the issuable assets.
assertGroups(t.t, t.tapd, issuableAssets)
// Make sure that the minting proofs reflect the correct state.
AssertMintingProofs(t.t, t.tapd, simpleAssets, rpcSimpleAssets)
AssertMintingProofs(t.t, t.tapd, issuableAssets, rpcIssuableAssets)
// Make sure we can't mint assets with too much meta data.
invalidRequest := CopyRequest(simpleAssets[0])
invalidRequest.Asset.AssetMeta.Data = make(
[]byte, proof.MetaDataMaxSizeBytes+1,
)
_, err := t.tapd.MintAsset(ctx, invalidRequest)
require.ErrorContains(t.t, err, proof.ErrMetaDataTooLarge.Error())
// Make sure the proof files for the freshly minted assets can be
// retrieved and are fully valid.
var allAssets []*taprpc.Asset
allAssets = append(allAssets, rpcSimpleAssets...)
allAssets = append(allAssets, rpcIssuableAssets...)
chainClient := t.tapd.cfg.LndNode.RPC.ChainKit
for _, mintedAsset := range allAssets {
AssertAssetProofs(t.t, t.tapd, chainClient, mintedAsset)
}
// Let's now create a new node and import all assets into that new node.
charlie := t.lndHarness.NewNode("charlie", lndDefaultArgs)
secondTapd := setupTapdHarness(
t.t, t, charlie, t.universeServer,
)
defer shutdownAndAssert(t, charlie, secondTapd)
// We import the assets into a node that doesn't have the keys to spend
// them, so we don't expect them to show up with script_key_is_local set
// to true in the list of assets.
transferAssetProofs(t, t.tapd, secondTapd, allAssets, false)
// Check that all the imported genesis proofs have no altLeaves.
emptyLeafMap := make(map[string][]*asset.Asset)
for _, asset := range rpcIssuableAssets {
AssertProofAltLeaves(t.t, secondTapd, asset, emptyLeafMap)
}
for _, asset := range rpcSimpleAssets {
AssertProofAltLeaves(t.t, secondTapd, asset, emptyLeafMap)
}
}
// testMintBatchResume tests that we're able to create a pending batch, restart
// the node, and finalize the pending batch on restart.
func testMintBatchResume(t *harnessTest) {
ctx := context.Background()
// Build one batch, but leave it as pending.
BuildMintingBatch(t.t, t.tapd, simpleAssets)
// The batch is pending and unfunded, so the verbose batch listing
// should return an empty list. An anchor transaction (BTC funding) is
// required for verbose listing to include group key requests.
batchResp, err := t.tapd.ListBatches(ctx, &mintrpc.ListBatchRequest{
Verbose: true,
})
require.NoError(t.t, err)
require.Empty(t.t, batchResp.Batches)
batchResp, err = t.tapd.ListBatches(ctx, &mintrpc.ListBatchRequest{})
require.NoError(t.t, err)
require.Len(t.t, batchResp.Batches, 1)
t.Logf("batches: %v", toJSON(t.t, batchResp))
batchKey := batchResp.Batches[0].Batch.BatchKey
// Restart the node. The non-final batch should be detected on restart
// and finalized.
t.Logf("Restarting minting node")
require.NoError(t.t, t.tapd.stop(false))
require.NoError(t.t, t.tapd.start(false))
hashes, err := WaitForNTxsInMempool(
t.lndHarness.Miner(), 1, defaultWaitTimeout,
)
require.NoError(t.t, err)
mintTXID := *hashes[0]
// Mine a block to confirm the assets.
block := MineBlocks(t.t, t.lndHarness.Miner(), 1, 1)[0]
blockHash := block.BlockHash()
WaitForBatchState(
t.t, ctx, t.tapd, defaultWaitTimeout, batchKey,
mintrpc.BatchState_BATCH_STATE_FINALIZED,
)
// We should be able to fetch the batch, and also find that the txid of
// the batch tx is populated.
batchResp, err = t.tapd.ListBatches(ctx, &mintrpc.ListBatchRequest{
Filter: &mintrpc.ListBatchRequest_BatchKey{
BatchKey: batchKey,
},
})
require.NoError(t.t, err)
require.Len(t.t, batchResp.Batches, 1)
batch := batchResp.Batches[0]
require.NotEmpty(t.t, batch.Batch.BatchTxid)
AssertAssetsMinted(
t.t, t.tapd, simpleAssets, mintTXID, blockHash,
)
}
// transferAssetProofs locates and exports the proof files for all given assets
// from the source node and imports them into the destination node.
func transferAssetProofs(t *harnessTest, src, dst *tapdHarness,
assets []*taprpc.Asset, shouldShowUpAsLocal bool) {
ctx := context.Background()
// TODO(roasbeef): modify import call, can't work as is
// * proof file only contains the tweaked script key
// * from that we don't know the internal key
// * we can import the proof but it's useless as is, but lets this
// itest work
chainClient := src.cfg.LndNode.RPC.ChainKit
for _, existingAsset := range assets {
gen := existingAsset.AssetGenesis
proofFile := AssertAssetProofs(
t.t, src, chainClient, existingAsset,
)
ImportProofFileDeprecated(t, dst, proofFile, gen.GenesisPoint)
}
listResp, err := dst.ListAssets(
ctx, &taprpc.ListAssetRequest{
ScriptKeyType: allScriptKeysQuery,
},
)
require.NoError(t.t, err)
importedAssets := GroupAssetsByName(listResp.Assets)
for _, existingAsset := range assets {
gen := existingAsset.AssetGenesis
out, err := wire.NewOutPointFromString(
existingAsset.ChainAnchor.AnchorOutpoint,
)
require.NoError(t.t, err)
anchorTxHash := out.Hash
anchorBlockHash, err := chainhash.NewHashFromStr(
existingAsset.ChainAnchor.AnchorBlockHash,
)
require.NoError(t.t, err)
AssertAssetState(
t.t, importedAssets, gen.Name, gen.MetaHash,
AssetAmountCheck(existingAsset.Amount),
AssetTypeCheck(existingAsset.AssetGenesis.AssetType),
AssetAnchorCheck(anchorTxHash, *anchorBlockHash),
AssetScriptKeyIsLocalCheck(shouldShowUpAsLocal),
)
}
}
// testMintAssetNameCollisionError tests that no error is produced when
// attempting to mint an asset whose name collides with an existing minted asset
// or an asset from a cancelled minting batch. An error should be produced
// when asset names collide within the same minting batch.
func testMintAssetNameCollisionError(t *harnessTest) {
// Asset name which will be common between minted asset and colliding
// asset.
commonAssetName := "test-asset-name"
// Define and mint a single asset.
assetMint := mintrpc.MintAssetRequest{
Asset: &mintrpc.MintAsset{
AssetType: taprpc.AssetType_NORMAL,
Name: commonAssetName,
AssetMeta: &taprpc.AssetMeta{
Data: []byte("metadata-1"),
},
Amount: 5000,
},
}
rpcSimpleAssets := MintAssetsConfirmBatch(
t.t, t.lndHarness.Miner(), t.tapd,
[]*mintrpc.MintAssetRequest{&assetMint},
)
// Ensure minted asset with requested name was successfully minted.
mintedAssetName := rpcSimpleAssets[0].AssetGenesis.Name
require.Equal(t.t, commonAssetName, mintedAssetName)
// Attempt to mint another asset whose name should collide with the
// existing minted asset. No other fields should collide.
assetCollide := mintrpc.MintAssetRequest{
Asset: &mintrpc.MintAsset{
AssetType: taprpc.AssetType_COLLECTIBLE,
Name: commonAssetName,
AssetMeta: &taprpc.AssetMeta{
Data: []byte("metadata-2"),
},
Amount: 1,
},
}
ctx := context.Background()
equalityCheck := func(a *mintrpc.MintAsset, b *mintrpc.PendingAsset) {
require.Equal(t.t, a.AssetType, b.AssetType)
require.Equal(t.t, a.Name, b.Name)
require.Equal(t.t, a.AssetMeta.Data, b.AssetMeta.Data)
require.Equal(t.t, a.Amount, b.Amount)
require.Equal(t.t, a.GroupKey, b.GroupKey)
require.Equal(t.t, a.GroupAnchor, b.GroupAnchor)
}
equalityCheckSeedlings := func(a, b *mintrpc.PendingAsset) {
require.Equal(t.t, a.AssetType, b.AssetType)
require.Equal(t.t, a.Name, b.Name)
require.Equal(t.t, a.AssetMeta.Data, b.AssetMeta.Data)
require.Equal(t.t, a.Amount, b.Amount)
require.Equal(t.t, a.NewGroupedAsset, b.NewGroupedAsset)
require.Equal(t.t, a.GroupKey, b.GroupKey)
require.Equal(t.t, a.GroupAnchor, b.GroupAnchor)
}
// If we attempt to add both assets to the same batch, the second mint
// call should fail.
collideResp, err := t.tapd.MintAsset(ctx, &assetCollide)
require.NoError(t.t, err)
require.NotNil(t.t, collideResp.PendingBatch)
require.NotNil(t.t, collideResp.PendingBatch.BatchKey)
require.Len(t.t, collideResp.PendingBatch.Assets, 1)
_, batchNameErr := t.tapd.MintAsset(ctx, &assetMint)
require.ErrorContains(t.t, batchNameErr, "already in batch")
// If we cancel the batch, we should still be able to fetch it from the
// daemon, and be able to refer to it by the batch key.
rpcBatches, err := t.tapd.ListBatches(
ctx, &mintrpc.ListBatchRequest{},
)
require.NoError(t.t, err)
allBatches := rpcBatches.Batches
require.Len(t.t, allBatches, 2)
isCollidingBatch := func(batch *mintrpc.VerboseBatch) bool {
if len(batch.Batch.Assets) == 0 {
return false
}
assetType := batch.Batch.Assets[0].AssetType
return assetType == taprpc.AssetType_COLLECTIBLE
}
batchCollide, err := fn.First(allBatches, isCollidingBatch)
require.NoError(t.t, err)
require.Len(t.t, batchCollide.Batch.Assets, 1)
equalityCheck(assetCollide.Asset, batchCollide.Batch.Assets[0])
cancelBatchKey, err := t.tapd.CancelBatch(
ctx, &mintrpc.CancelBatchRequest{},
)
require.NoError(t.t, err)
require.Equal(
t.t, cancelBatchKey.BatchKey, collideResp.PendingBatch.BatchKey,
)
// The only change in the returned batch after cancellation should be
// the batch state.
cancelBatch, err := t.tapd.ListBatches(ctx, &mintrpc.ListBatchRequest{
Filter: &mintrpc.ListBatchRequest_BatchKey{
BatchKey: collideResp.PendingBatch.BatchKey,
},
})
require.NoError(t.t, err)
require.Len(t.t, cancelBatch.Batches, 1)
cancelBatchCollide := cancelBatch.Batches[0]
require.Len(t.t, cancelBatchCollide.Batch.Assets, 1)
equalityCheckSeedlings(
batchCollide.Batch.Assets[0],
cancelBatchCollide.Batch.Assets[0],
)
cancelBatchState := cancelBatchCollide.Batch.State
require.Equal(
t.t, cancelBatchState,
mintrpc.BatchState_BATCH_STATE_SEEDLING_CANCELLED,
)
// Minting the asset with the name collision should work, even though
// it is also part of a cancelled batch.
rpcCollideAsset := MintAssetsConfirmBatch(
t.t, t.lndHarness.Miner(), t.tapd,
[]*mintrpc.MintAssetRequest{&assetCollide},
)
collideAssetName := rpcCollideAsset[0].AssetGenesis.Name
require.Equal(t.t, commonAssetName, collideAssetName)
}
// testMintAssetsWithTapscriptSibling tests that a batch of assets can be minted
// with a tapscript sibling, and that the genesis output from that mint can be
// spend via the script path.
func testMintAssetsWithTapscriptSibling(t *harnessTest) {
ctx := context.Background()
// Build the tapscript tree.
sigLockPrivKey := test.RandPrivKey()
hashLockPreimage := []byte("foobar")
hashLockLeaf := test.ScriptHashLock(t.t, hashLockPreimage)
sigLeaf := test.ScriptSchnorrSig(t.t, sigLockPrivKey.PubKey())
siblingTree := txscript.AssembleTaprootScriptTree(hashLockLeaf, sigLeaf)
siblingBranch := txscript.NewTapBranch(
siblingTree.RootNode.Left(), siblingTree.RootNode.Right(),
)
siblingPreimage := commitment.NewPreimageFromBranch(siblingBranch)
typedBranch := asset.TapTreeNodesFromBranch(siblingBranch)
rawBranch := fn.MapOptionZ(asset.GetBranch(typedBranch), asset.ToBranch)
require.Len(t.t, rawBranch, 2)
siblingReq := mintrpc.FinalizeBatchRequest_Branch{
Branch: &taprpc.TapBranch{
LeftTaphash: rawBranch[0],
RightTaphash: rawBranch[1],
},
}
rpcSimpleAssets := MintAssetsConfirmBatch(
t.t, t.lndHarness.Miner(), t.tapd, simpleAssets,
WithSiblingBranch(siblingReq),
)
rpcIssuableAssets := MintAssetsConfirmBatch(
t.t, t.lndHarness.Miner(), t.tapd, issuableAssets,
)
AssertMintedAssetBalances(
t.t, t.tapd, rpcSimpleAssets, rpcIssuableAssets, false,
)
// Filter the managed UTXOs to select the genesis UTXO with the
// tapscript sibling.
utxos, err := t.tapd.ListUtxos(ctx, &taprpc.ListUtxosRequest{})
require.NoError(t.t, err)
utxoWithTapSibling := func(utxo *taprpc.ManagedUtxo) bool {
return !bytes.Equal(utxo.TaprootAssetRoot, utxo.MerkleRoot)
}
mintingOutputWithSibling := fn.Filter(
maps.Values(utxos.ManagedUtxos), utxoWithTapSibling,
)
require.Len(t.t, mintingOutputWithSibling, 1)
genesisWithSibling := mintingOutputWithSibling[0]
// Verify that all assets anchored in the output with the tapscript
// sibling have the correct sibling preimage. Also verify that the final
// tweak used for the genesis output is derived from the tapscript
// sibling created above and the batch Taproot Asset commitment.
AssertGenesisOutput(t.t, genesisWithSibling, siblingPreimage)
// Extract the fields needed to construct a script path spend, which
// includes the Taproot Asset commitment root, the final tap tweak, and
// the internal key.
mintTapTweak := genesisWithSibling.MerkleRoot
mintTapTreeRoot := genesisWithSibling.TaprootAssetRoot
mintInternalKey, err := btcec.ParsePubKey(
genesisWithSibling.InternalKey,
)
require.NoError(t.t, err)
mintOutputKey := txscript.ComputeTaprootOutputKey(
mintInternalKey, mintTapTweak,
)
mintOutputKeyIsOdd := mintOutputKey.SerializeCompressed()[0] == 0x03
siblingScriptHash := sigLeaf.TapHash()
// Build the control block and witness.
inclusionProof := bytes.Join(
[][]byte{siblingScriptHash[:], mintTapTreeRoot}, nil,
)
hashLockControlBlock := txscript.ControlBlock{
InternalKey: mintInternalKey,
OutputKeyYIsOdd: mintOutputKeyIsOdd,
LeafVersion: txscript.BaseLeafVersion,
InclusionProof: inclusionProof,
}
hashLockControlBlockBytes, err := hashLockControlBlock.ToBytes()
require.NoError(t.t, err)
hashLockWitness := wire.TxWitness{
hashLockPreimage, hashLockLeaf.Script, hashLockControlBlockBytes,
}
// Make a non-tap output from Bob to use in a TX spending Alice's
// genesis UTXO.
bobLnd := t.lndHarness.NewNodeWithCoins("Bob", nil)
burnOutput := MakeOutput(
t, bobLnd, lnrpc.AddressType_TAPROOT_PUBKEY, 500,
)
// Construct and publish the TX.
genesisOutpoint, err := wire.NewOutPointFromString(
genesisWithSibling.OutPoint,
)
require.NoError(t.t, err)
burnTx := wire.MsgTx{
Version: 2,
TxIn: []*wire.TxIn{{
PreviousOutPoint: *genesisOutpoint,
Witness: hashLockWitness,
}},
TxOut: []*wire.TxOut{burnOutput},
}
burnTxBytes, err := fn.Serialize(&burnTx)
require.NoError(t.t, err)
bobLnd.RPC.PublishTransaction(&walletrpc.Transaction{
TxHex: burnTxBytes,
})
// Bob should detect the TX, and the resulting confirmed UTXO once
// a new block is mined.
t.lndHarness.Miner().AssertNumTxsInMempool(1)
t.lndHarness.AssertNumUTXOsUnconfirmed(bobLnd, 1)
t.lndHarness.MineBlocksAndAssertNumTxes(1, 1)
t.lndHarness.AssertNumUTXOsWithConf(bobLnd, 1, 1, 1)
}
// testMintBatchAndTransfer tests that we can mint a batch of assets, observe
// the finalized batch state, and observe the same batch state after a transfer
// of an asset from the batch.
func testMintBatchAndTransfer(t *harnessTest) {
ctx := context.Background()
rpcSimpleAssets := MintAssetsConfirmBatch(
t.t, t.lndHarness.Miner(), t.tapd, simpleAssets,
)
// List the batch right after minting.
originalBatches, err := t.tapd.ListBatches(
ctx, &mintrpc.ListBatchRequest{},
)
require.NoError(t.t, err)
// We'll make a second node now that'll be the receiver of all the
// assets made above.
bobLnd := t.lndHarness.NewNodeWithCoins("Bob", nil)
secondTapd := setupTapdHarness(t.t, t, bobLnd, t.universeServer)
defer func() {
require.NoError(t.t, secondTapd.stop(!*noDelete))
}()
// In order to force a split, we don't try to send the full first asset.
a := rpcSimpleAssets[0]
addr, events := NewAddrWithEventStream(
t.t, secondTapd, &taprpc.NewAddrRequest{
AssetId: a.AssetGenesis.AssetId,
Amt: a.Amount - 1,
AssetVersion: a.Version,
},
)
AssertAddrCreated(t.t, secondTapd, a, addr)
sendResp, sendEvents := sendAssetsToAddr(t, t.tapd, addr)
sendRespJSON, err := formatProtoJSON(sendResp)
require.NoError(t.t, err)
t.Logf("Got response from sending assets: %v", sendRespJSON)
// Make sure that eventually we see a single event for the
// address.
AssertAddrEvent(t.t, secondTapd, addr, 1, statusDetected)
// Mine a block to make sure the events are marked as confirmed.
MineBlocks(t.t, t.lndHarness.Miner(), 1, 1)
// Eventually the event should be marked as confirmed.
AssertAddrEvent(t.t, secondTapd, addr, 1, statusConfirmed)
// Make sure we have imported and finalized all proofs.
AssertNonInteractiveRecvComplete(t.t, secondTapd, 1)
AssertSendEventsComplete(t.t, addr.ScriptKey, sendEvents)
// Make sure the receiver has received all events in order for
// the address.
AssertReceiveEvents(t.t, addr, events)
afterBatches, err := t.tapd.ListBatches(
ctx, &mintrpc.ListBatchRequest{},
)
require.NoError(t.t, err)
// The batch listed after the transfer should be identical to the batch
// listed before the transfer.
require.Equal(
t.t, len(originalBatches.Batches), len(afterBatches.Batches),
)
originalBatch := originalBatches.Batches[0].Batch
afterBatch := afterBatches.Batches[0].Batch
// Sort the assets from the listed batch before comparison.
slices.SortFunc(originalBatch.Assets,
func(a, b *mintrpc.PendingAsset) int {
return strings.Compare(a.Name, b.Name)
})
slices.SortFunc(afterBatch.Assets,
func(a, b *mintrpc.PendingAsset) int {
return strings.Compare(a.Name, b.Name)
})
require.True(t.t, proto.Equal(originalBatch, afterBatch))
}
// testAssetBalances validates the balance retrieval and virtual PSBT funding
// functionality for issued assets. The test performs the following steps:
// 1. Mints two batches of assets and verifies that the tapcli
// `assets balance` returns the correct balances.
// 2. Tests funding a vPSBT, putting a lease on one of the two batches, with
// the `FundVirtualPsbt` RPC for various scenarios:
// - Fails if the Inputs field contains a nil Outpoint.
// - Fails if the Inputs field contains an invalid Outpoint.
// - Fails if the Inputs field contains an invalid short AssetId.
// - Fails if the Inputs field contains an invalid short ScriptKey.
// - Succeeds if a valid Outpoint is provided in the Inputs field.
// - Succeeds if the Inputs field is not provided at all, using asset
// coin selection instead.
// 3. Ensures that leased assets are reflected correctly in the balance
// retrieval, with and without the `include_leased` flag.
func testAssetBalances(t *harnessTest) {
ctx := context.Background()
// Mint assets for testing.
rpcSimpleAssets := MintAssetsConfirmBatch(
t.t, t.lndHarness.Miner(), t.tapd, simpleAssets,
)
targetAsset := rpcSimpleAssets[0]
// Now that all our assets have been issued, we'll use the balance
// calls to ensure that we're able to retrieve the proper balance for
// them all.
AssertMintedAssetBalances(t.t, t.tapd, rpcSimpleAssets, nil, false)
// Verify that the include_pending and include_channel flags work
// correctly when there are no pending transfers or channels.
balResp, err := t.tapd.ListBalances(
ctx, &taprpc.ListBalancesRequest{
GroupBy: groupBalancesByAssetID,
IncludePending: true,
IncludeChannel: true,
},
)
require.NoError(t.t, err)
require.NotNil(t.t, balResp)
require.Empty(t.t, balResp.PendingAssetBalances)
require.Empty(t.t, balResp.ChannelAssetBalances)
// Check chain anchor for the target asset.
out, err := wire.NewOutPointFromString(
targetAsset.ChainAnchor.AnchorOutpoint,
)
require.NoError(t.t, err)
var (
targetAssetGenesis = targetAsset.AssetGenesis
assetId = targetAssetGenesis.AssetId
scriptKey = targetAsset.ScriptKey
anchorTxid = out.Hash.CloneBytes()
anchorVout = out.Index
aliceTapd = t.tapd
bobLnd = t.lndHarness.NewNodeWithCoins("Bob", nil)
)
// We create a second tapd node that will be used to simulate a second
// party in the test. This tapd node is connected to lnd "Bob".
bobTapd := setupTapdHarness(t.t, t, bobLnd, t.universeServer)
defer func() {
require.NoError(t.t, bobTapd.stop(!*noDelete))
}()
const assetsToSend = 1000
bobAddr, err := bobTapd.NewAddr(ctx, &taprpc.NewAddrRequest{
AssetId: targetAssetGenesis.AssetId,
Amt: assetsToSend,
})
require.NoError(t.t, err)
recipients := map[string]uint64{
bobAddr.Encoded: bobAddr.Amount,
}
subTests := []struct {
name string
inputs []*wrpc.PrevId
expectError bool
expectedErrMsg string
}{
{
name: "Fail if Inputs are provided but Outpoint is nil",
inputs: []*wrpc.PrevId{
{
Outpoint: nil,
Id: assetId,
ScriptKey: scriptKey,
},
},
expectError: true,
expectedErrMsg: "index 0 has a nil Outpoint",
},
{
name: "Fail if Inputs contain an invalid Outpoint",
inputs: []*wrpc.PrevId{
{
Outpoint: &taprpc.OutPoint{
Txid: []byte(
"invalid_txid",
),
OutputIndex: anchorVout,
},
Id: assetId,
ScriptKey: scriptKey,
},
},
expectError: true,
expectedErrMsg: "invalid outpoint txid",
},
{
name: "Fail if AssetId is too short",
inputs: []*wrpc.PrevId{
{
Outpoint: &taprpc.OutPoint{
Txid: anchorTxid,
OutputIndex: anchorVout,
},
Id: []byte{1, 2},
ScriptKey: scriptKey,
},
},
expectError: true,
expectedErrMsg: "invalid asset ID",
},
{
name: "Fail if ScriptKey is too short",
inputs: []*wrpc.PrevId{
{
Outpoint: &taprpc.OutPoint{
Txid: anchorTxid,
OutputIndex: anchorVout,
},
Id: assetId,
ScriptKey: []byte{1, 2},
},
},
expectError: true,
expectedErrMsg: "invalid script key",
},
{
name: "Fail if valid, unfindable Outpoint is provided",
inputs: []*wrpc.PrevId{
{
Outpoint: &taprpc.OutPoint{
Txid: anchorTxid,
OutputIndex: anchorVout + 1,
},
Id: assetId,
ScriptKey: scriptKey,
},
},
expectError: true,
expectedErrMsg: "failed to find coin(s)",
},
{
name: "Succeed if a valid Outpoint is provided",
inputs: []*wrpc.PrevId{
{
Outpoint: &taprpc.OutPoint{
Txid: anchorTxid,
OutputIndex: anchorVout,
},
Id: assetId,
ScriptKey: scriptKey,
},
},
expectError: false,
},
{
name: "Succeed if no Inputs are provided",
inputs: nil,
expectError: false,
},
}
for _, tt := range subTests {
// Now we can create our virtual transaction and ask Alice's
// tapd to fund it.
_, err := aliceTapd.FundVirtualPsbt(
ctx, &wrpc.FundVirtualPsbtRequest{
Template: &wrpc.FundVirtualPsbtRequest_Raw{
Raw: &wrpc.TxTemplate{
Recipients: recipients,
Inputs: tt.inputs,
},
},
},
)
if tt.expectError {
require.ErrorContains(t.t, err, tt.expectedErrMsg)
continue
}
require.NoError(t.t, err)
// With a transaction funding should have led to a lease on the
// simple assets, we'll use the balance calls to ensure that
// we're able to retrieve the proper balances.
AssertBalances(
t.t, t.tapd, 0, WithAssetID(targetAssetGenesis.AssetId),
WithNumAnchorUtxos(0),
)
AssertBalances(
t.t, t.tapd, 5000, WithIncludeLeased(), WithNumUtxos(1),
WithAssetID(targetAssetGenesis.AssetId),
WithNumAnchorUtxos(1),
)
// Unlock the input if provided so it can be reused.
for _, input := range tt.inputs {
_, err = aliceTapd.RemoveUTXOLease(
ctx, &wrpc.RemoveUTXOLeaseRequest{
Outpoint: input.Outpoint,
},
)
require.NoError(t.t, err)
}
}
}
// testListAssets tests the pagination support of the ListAssets RPC.
func testListAssets(t *harnessTest) {
ctx := context.Background()
// Mint three separate batches with 2 assets each, giving us 6 total
// assets to paginate through. Multiple batches ensure the assets have
// distinct primary keys in the database.
const numBatches = 3
const assetsPerBatch = 2
const totalAssets = numBatches * assetsPerBatch
for i := range numBatches {
MintAssetsConfirmBatch(
t.t, t.lndHarness.Miner(), t.tapd,
[]*mintrpc.MintAssetRequest{
{
Asset: &mintrpc.MintAsset{
AssetType: taprpc.
AssetType_NORMAL,
Name: assetName(
"pagination",
i, 0,
),
AssetMeta: &taprpc.AssetMeta{
Data: []byte("m"),
},
Amount: 1000,
},
},
{
Asset: &mintrpc.MintAsset{
AssetType: taprpc.
AssetType_COLLECTIBLE,
Name: assetName(
"pagination",
i, 1,
),
AssetMeta: &taprpc.AssetMeta{
Data: []byte("m"),
},
Amount: 1,
},
},
},
)
}
// Verify we have all expected assets with no pagination (backward
// compat: limit=0 uses a default).
allResp, err := t.tapd.ListAssets(
ctx, &taprpc.ListAssetRequest{},
)
require.NoError(t.t, err)
require.Len(t.t, allResp.Assets, totalAssets)
// Test limit: fetch only the first 3 assets.
resp, err := t.tapd.ListAssets(
ctx, &taprpc.ListAssetRequest{
Limit: 3,
},
)
require.NoError(t.t, err)
require.Len(t.t, resp.Assets, 3)
// Test offset + limit: skip the first 2, fetch 3.
resp, err = t.tapd.ListAssets(
ctx, &taprpc.ListAssetRequest{
Offset: 2,
Limit: 3,
},
)
require.NoError(t.t, err)
require.Len(t.t, resp.Assets, 3)
// Test ascending direction: asset IDs should be in ascending
// order of creation.
resp, err = t.tapd.ListAssets(
ctx, &taprpc.ListAssetRequest{
Limit: int32(totalAssets),
Direction: taprpc.
SortDirection_SORT_DIRECTION_ASC,
},
)
require.NoError(t.t, err)
require.Len(t.t, resp.Assets, totalAssets)
ascAssets := resp.Assets
// Test descending direction.
resp, err = t.tapd.ListAssets(
ctx, &taprpc.ListAssetRequest{
Limit: int32(totalAssets),
Direction: taprpc.
SortDirection_SORT_DIRECTION_DESC,
},
)
require.NoError(t.t, err)
require.Len(t.t, resp.Assets, totalAssets)
// Verify the descending results are the reverse of ascending.
for i := range totalAssets {
require.Equal(
t.t,
ascAssets[i].AssetGenesis.AssetId,
resp.Assets[totalAssets-1-i].
AssetGenesis.AssetId,
)
}
// Test offset beyond total: should return empty.
resp, err = t.tapd.ListAssets(
ctx, &taprpc.ListAssetRequest{
Offset: int32(totalAssets + 10),
Limit: 10,
},
)
require.NoError(t.t, err)
require.Len(t.t, resp.Assets, 0)
// Test pagination through all results in pages of 2.
var allPaginated []*taprpc.Asset
offset := int32(0)
limit := int32(2)
for {
page, err := t.tapd.ListAssets(
ctx, &taprpc.ListAssetRequest{
Offset: offset,
Limit: limit,
Direction: taprpc.
SortDirection_SORT_DIRECTION_ASC,
},
)
require.NoError(t.t, err)
if len(page.Assets) == 0 {
break
}
allPaginated = append(