-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathassets_store_test.go
More file actions
3858 lines (3365 loc) · 103 KB
/
Copy pathassets_store_test.go
File metadata and controls
3858 lines (3365 loc) · 103 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 tapdb
import (
"bytes"
"context"
"crypto/sha256"
"database/sql"
"math/rand"
"sort"
"testing"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew"
"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/mssmt"
"github.com/lightninglabs/taproot-assets/proof"
"github.com/lightninglabs/taproot-assets/tapdb/sqlc"
"github.com/lightninglabs/taproot-assets/tapfreighter"
"github.com/lightninglabs/taproot-assets/tappsbt"
"github.com/lightninglabs/taproot-assets/tapscript"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/keychain"
"github.com/stretchr/testify/require"
)
type assetGenOptions struct {
version asset.Version
assetGen asset.Genesis
customGroup bool
groupAnchorGen *asset.Genesis
groupAnchorGenPoint *wire.OutPoint
noGroupKey bool
genesisAsset bool
groupKeyPriv *btcec.PrivateKey
amt uint64
genesisPoint wire.OutPoint
scriptKey asset.ScriptKey
}
func defaultAssetGenOpts(t *testing.T) *assetGenOptions {
gen := asset.RandGenesis(t, asset.Normal)
return &assetGenOptions{
version: asset.Version(rand.Int31n(2)),
assetGen: gen,
groupKeyPriv: test.RandPrivKey(),
amt: uint64(test.RandInt[uint32]()),
genesisPoint: test.RandOp(t),
scriptKey: asset.NewScriptKeyBip86(keychain.KeyDescriptor{
PubKey: test.RandPubKey(t),
KeyLocator: keychain.KeyLocator{
Family: test.RandInt[keychain.KeyFamily](),
Index: uint32(test.RandInt[int32]()),
},
}),
}
}
type assetGenOpt func(*assetGenOptions)
func withAssetGenAmt(amt uint64) assetGenOpt {
return func(opt *assetGenOptions) {
opt.amt = amt
}
}
func withAssetGenKeyGroup(key *btcec.PrivateKey) assetGenOpt {
return func(opt *assetGenOptions) {
opt.customGroup = true
opt.groupKeyPriv = key
}
}
func withGroupAnchorGen(g *asset.Genesis) assetGenOpt {
return func(opt *assetGenOptions) {
opt.groupAnchorGen = g
}
}
func withGroupAnchorGenPoint(op wire.OutPoint) assetGenOpt {
return func(opt *assetGenOptions) {
opt.groupAnchorGenPoint = &op
}
}
func withAssetGenPoint(op wire.OutPoint) assetGenOpt {
return func(opt *assetGenOptions) {
opt.genesisPoint = op
}
}
func withAssetGen(g asset.Genesis) assetGenOpt {
return func(opt *assetGenOptions) {
opt.assetGen = g
}
}
func withAssetVersionGen(v *asset.Version) assetGenOpt {
return func(opt *assetGenOptions) {
opt.version = *v
}
}
func withScriptKey(k asset.ScriptKey) assetGenOpt {
return func(opt *assetGenOptions) {
opt.scriptKey = k
}
}
func withNoGroupKey() assetGenOpt {
return func(opt *assetGenOptions) {
opt.noGroupKey = true
}
}
func withGenesisAsset() assetGenOpt {
return func(opt *assetGenOptions) {
opt.genesisAsset = true
opt.noGroupKey = true
}
}
func randAsset(t *testing.T, genOpts ...assetGenOpt) *asset.Asset {
opts := defaultAssetGenOpts(t)
for _, optFunc := range genOpts {
optFunc(opts)
}
genesis := opts.assetGen
genesis.FirstPrevOut = opts.genesisPoint
groupPriv := *opts.groupKeyPriv
genSigner := asset.NewMockGenesisSigner(&groupPriv)
genTxBuilder := tapscript.GroupTxBuilder{}
var (
groupKeyDesc = keychain.KeyDescriptor{
PubKey: groupPriv.PubKey(),
}
assetGroupKey *asset.GroupKey
err error
initialGen = genesis
protoAsset *asset.Asset
lockTime = uint64(test.RandInt[int32]())
relativeLockTime = uint64(test.RandInt[int32]())
)
protoAsset = asset.NewAssetNoErr(
t, genesis, opts.amt, lockTime, relativeLockTime,
opts.scriptKey, nil, asset.WithAssetVersion(opts.version),
)
if opts.groupAnchorGen != nil {
initialGen = *opts.groupAnchorGen
}
if opts.groupAnchorGenPoint != nil {
initialGen.FirstPrevOut = *opts.groupAnchorGenPoint
}
groupReq := asset.NewGroupKeyRequestNoErr(
t, groupKeyDesc, fn.None[asset.ExternalKey](), initialGen,
protoAsset, nil, fn.None[chainhash.Hash](),
)
genTx, err := groupReq.BuildGroupVirtualTx(&genTxBuilder)
require.NoError(t, err)
assetGroupKey, err = asset.DeriveGroupKey(
genSigner, *genTx, *groupReq, nil,
)
require.NoError(t, err)
newAsset := &asset.Asset{
Version: opts.version,
Genesis: genesis,
Amount: opts.amt,
LockTime: lockTime,
RelativeLockTime: relativeLockTime,
ScriptKey: opts.scriptKey,
}
// Go with an even amount to make the splits always work nicely.
if newAsset.Amount%2 != 0 {
newAsset.Amount++
}
// 50/50 chance that we'll actually have a group key. Or we'll always
// use it if a custom group key was specified.
switch {
case opts.noGroupKey:
break
case opts.customGroup || test.RandInt[int]()%2 == 0:
// If we're using a group key, we want to leave the asset with
// the group witness and not a random witness.
assetWithGroup := asset.NewAssetNoErr(
t, genesis, newAsset.Amount, newAsset.LockTime,
newAsset.RelativeLockTime, newAsset.ScriptKey,
assetGroupKey, asset.WithAssetVersion(opts.version),
)
return assetWithGroup
}
// For the witnesses, we'll flip a coin: we'll either make a genesis
// witness, or a set of actual witnesses.
var witnesses []asset.Witness
if opts.genesisAsset || test.RandInt[int]()%2 == 0 {
witnesses = append(witnesses, asset.Witness{
PrevID: &asset.PrevID{},
TxWitness: nil,
SplitCommitment: nil,
})
} else {
numWitness := test.RandInt[int]() % 10
if numWitness == 0 {
numWitness++
}
witnesses = make([]asset.Witness, numWitness)
for i := 0; i < numWitness; i++ {
scriptKey := asset.NewScriptKeyBip86(
keychain.KeyDescriptor{
PubKey: test.RandPubKey(t),
},
)
witnesses[i] = asset.Witness{
PrevID: &asset.PrevID{
OutPoint: test.RandOp(t),
ID: asset.RandID(t),
ScriptKey: asset.ToSerialized(
scriptKey.PubKey,
),
},
TxWitness: test.RandTxWitnesses(t),
// For simplicity, we just use the base asset
// itself as the "anchor" asset in the split
// commitment.
SplitCommitment: commitment.RandSplitCommit(
t, *newAsset,
),
}
}
}
newAsset.PrevWitnesses = witnesses
return newAsset
}
func assertAssetEqual(t *testing.T, a, b *asset.Asset) {
t.Helper()
if equal := a.DeepEqual(b); !equal {
// Print a nice diff if the native equality check fails.
require.Equal(t, b, a)
// Make sure we fail in any case, even if the above equality
// check succeeds (which shouldn't be the case).
t.Fatalf("asset equality failed!")
}
}
// TestImportAssetProof tests that given a valid asset proof (mainly the final
// snapshot information), we're able to properly import all the components on
// disk, then retrieve the asset as if it were ours.
func TestImportAssetProof(t *testing.T) {
t.Parallel()
var (
ctxb = context.Background()
dbHandle = NewDbHandle(t)
assetStore = dbHandle.AssetStore
)
// Add a random asset and corresponding proof into the database.
testAsset, testProof := dbHandle.AddRandomAssetProof(t)
initialBlob := testProof.Blob
// We should now be able to retrieve the set of all assets inserted on
// disk.
assets, err := assetStore.FetchAllAssets(ctxb, false, false, nil)
require.NoError(t, err)
require.Len(t, assets, 1)
// The DB asset should match the asset we inserted exactly.
dbAsset := assets[0]
assertAssetEqual(t, testAsset, dbAsset.Asset)
// Finally, we'll verify all the anchor information that was inserted
// on disk.
require.Equal(t, testProof.AnchorBlockHash, dbAsset.AnchorBlockHash)
require.Equal(
t, testProof.AssetSnapshot.OutPoint, dbAsset.AnchorOutpoint,
)
require.Equal(t, testProof.AnchorTx.TxHash(), dbAsset.AnchorTx.TxHash())
require.NotZero(t, dbAsset.AnchorBlockHeight)
// We should also be able to fetch the proof we just inserted using the
// script key of the new asset.
currentBlob, err := assetStore.FetchProof(ctxb, proof.Locator{
ScriptKey: *testAsset.ScriptKey.PubKey,
})
require.NoError(t, err)
require.Equal(t, initialBlob, currentBlob)
// We should also be able to fetch the created asset above based on
// either the asset ID, or key group via the main coin selection
// routine.
assetConstraints := tapfreighter.CommitmentConstraints{
AssetSpecifier: testAsset.Specifier(),
}
selectedAssets, err := assetStore.ListEligibleCoins(
ctxb, assetConstraints,
)
require.NoError(t, err)
require.Len(t, selectedAssets, 1)
assertAssetEqual(t, testAsset, selectedAssets[0].Asset)
// We'll now attempt to overwrite the proof with one that has different
// block information (simulating a re-org).
updatedBlob := bytes.Repeat([]byte{0x77}, 100)
testProof.AnchorBlockHash = chainhash.Hash{12, 34, 56}
testProof.AnchorBlockHeight = 1234
testProof.AnchorTxIndex = 5678
testProof.Blob = updatedBlob
require.NoError(t, assetStore.ImportProofs(
ctxb, proof.MockVerifierCtx, true, testProof,
))
currentBlob, err = assetStore.FetchProof(ctxb, proof.Locator{
ScriptKey: *testAsset.ScriptKey.PubKey,
})
require.NoError(t, err)
require.Equal(t, updatedBlob, []byte(currentBlob))
// Make sure we get the same result if we also query by proof outpoint.
currentBlob, err = assetStore.FetchProof(ctxb, proof.Locator{
ScriptKey: *testAsset.ScriptKey.PubKey,
OutPoint: &testProof.AssetSnapshot.OutPoint,
})
require.NoError(t, err)
require.Equal(t, updatedBlob, []byte(currentBlob))
// Make sure the chain TX was updated as well.
assets, err = assetStore.FetchAllAssets(ctxb, false, false, nil)
require.NoError(t, err)
require.Len(t, assets, 1)
// The DB asset should match the asset we inserted exactly.
dbAsset = assets[0]
assertAssetEqual(t, testAsset, dbAsset.Asset)
// Finally, we'll verify all the anchor information that was inserted
// on disk.
require.Equal(t, testProof.AnchorBlockHash, dbAsset.AnchorBlockHash)
require.Equal(
t, testProof.AssetSnapshot.OutPoint, dbAsset.AnchorOutpoint,
)
require.Equal(t, testProof.AnchorTx.TxHash(), dbAsset.AnchorTx.TxHash())
// We now add a second proof for the same script key but a different
// outpoint and expect that to be stored and retrieved correctly.
oldOutpoint := testProof.AssetSnapshot.OutPoint
newChainTx := wire.NewMsgTx(2)
newChainTx.TxIn = []*wire.TxIn{{
PreviousOutPoint: test.RandOp(t),
}}
newChainTx.TxOut = []*wire.TxOut{{
PkScript: bytes.Repeat([]byte{0x01}, 34),
}}
newOutpoint := wire.OutPoint{
Hash: newChainTx.TxHash(),
Index: 0,
}
testProof.AssetSnapshot.AnchorTx = newChainTx
testProof.AssetSnapshot.OutPoint = newOutpoint
testProof.Blob = []byte("new proof")
require.NoError(t, assetStore.ImportProofs(
ctxb, proof.MockVerifierCtx, false, testProof,
))
// We should still be able to fetch the old proof.
dbBlob, err := assetStore.FetchProof(ctxb, proof.Locator{
ScriptKey: *testAsset.ScriptKey.PubKey,
OutPoint: &oldOutpoint,
})
require.NoError(t, err)
require.Equal(t, updatedBlob, []byte(dbBlob))
// But also the new one.
dbBlob, err = assetStore.FetchProof(ctxb, proof.Locator{
ScriptKey: *testAsset.ScriptKey.PubKey,
OutPoint: &newOutpoint,
})
require.NoError(t, err)
require.EqualValues(t, testProof.Blob, []byte(dbBlob))
}
// TestInternalKeyUpsert tests that if we insert an internal key that's a
// duplicate, it works and we get the primary key of the key that was already
// inserted.
func TestInternalKeyUpsert(t *testing.T) {
t.Parallel()
// First, we'll create a new instance of the database.
_, _, db := newAssetStore(t)
testKey := test.RandPubKey(t)
// Now we'll insert two internal keys that are the same. We should get
// the same response back (the primary key) for both of them.
ctx := context.Background()
k1, err := db.UpsertInternalKey(ctx, InternalKey{
RawKey: testKey.SerializeCompressed(),
KeyFamily: 1,
KeyIndex: 2,
})
require.NoError(t, err)
k2, err := db.UpsertInternalKey(ctx, InternalKey{
RawKey: testKey.SerializeCompressed(),
KeyFamily: 1,
KeyIndex: 2,
})
require.NoError(t, err)
require.Equal(t, k1, k2)
}
type assetDesc struct {
assetGen asset.Genesis
groupAnchorGen *asset.Genesis
groupAnchorGenPoint *wire.OutPoint
anchorPoint wire.OutPoint
keyGroup *btcec.PrivateKey
noGroupKey bool
scriptKey *asset.ScriptKey
amt uint64
spent bool
leasedUntil time.Time
assetVersion *asset.Version
}
type assetGenerator struct {
assetGens []asset.Genesis
anchorTxs []*wire.MsgTx
anchorPoints []wire.OutPoint
anchorPointsToTx map[wire.OutPoint]*wire.MsgTx
anchorPointsToHeights map[wire.OutPoint]uint32
groupKeys []*btcec.PrivateKey
}
func newAssetGenerator(t *testing.T,
numAssetIDs, numGroupKeys int) *assetGenerator {
anchorTxs := make([]*wire.MsgTx, numAssetIDs)
for i := 0; i < numAssetIDs; i++ {
pkScript := bytes.Repeat([]byte{byte(i)}, 34)
anchorTxs[i] = &wire.MsgTx{
TxIn: []*wire.TxIn{
{},
},
TxOut: []*wire.TxOut{
{
PkScript: pkScript,
Value: 10 * 8,
},
},
}
}
anchorPoints := make([]wire.OutPoint, numAssetIDs)
anchorPointsToTx := make(map[wire.OutPoint]*wire.MsgTx, numAssetIDs)
anchorPointsToHeights := make(map[wire.OutPoint]uint32, numAssetIDs)
for i, tx := range anchorTxs {
tx := tx
anchorPoint := wire.OutPoint{
Hash: tx.TxHash(),
Index: 0,
}
anchorPoints[i] = anchorPoint
anchorPointsToTx[anchorPoint] = tx
anchorPointsToHeights[anchorPoint] = uint32(i + 500)
}
assetGens := make([]asset.Genesis, numAssetIDs)
for i := 0; i < numAssetIDs; i++ {
assetGens[i] = asset.RandGenesis(t, asset.Normal)
}
groupKeys := make([]*btcec.PrivateKey, numGroupKeys)
for i := 0; i < numGroupKeys; i++ {
groupKeys[i] = test.RandPrivKey()
}
return &assetGenerator{
groupKeys: groupKeys,
assetGens: assetGens,
anchorPoints: anchorPoints,
anchorPointsToTx: anchorPointsToTx,
anchorPointsToHeights: anchorPointsToHeights,
anchorTxs: anchorTxs,
}
}
func (a *assetGenerator) genAssets(t *testing.T, assetStore *AssetStore,
assetDescs []assetDesc) ([]*asset.Asset, []proof.Proof) {
ctx := context.Background()
anchorPointsToAssetCommitments := make(
map[wire.OutPoint][]*commitment.AssetCommitment,
)
newAssets := make([]*asset.Asset, len(assetDescs))
for idx, desc := range assetDescs {
desc := desc
opts := []assetGenOpt{
withAssetGenAmt(desc.amt),
withAssetGenPoint(desc.anchorPoint),
withAssetGen(desc.assetGen),
}
if desc.keyGroup != nil {
opts = append(opts, withAssetGenKeyGroup(desc.keyGroup))
}
if desc.noGroupKey {
opts = append(opts, withNoGroupKey())
}
if desc.scriptKey != nil {
opts = append(opts, withScriptKey(*desc.scriptKey))
}
if desc.amt == 0 {
opts = append(opts, withScriptKey(asset.NUMSScriptKey))
}
if desc.groupAnchorGen != nil {
opts = append(opts, withGroupAnchorGen(
desc.groupAnchorGen,
))
}
if desc.groupAnchorGenPoint != nil {
opts = append(opts, withGroupAnchorGenPoint(
*desc.groupAnchorGenPoint,
))
}
if desc.assetVersion != nil {
opts = append(opts, withAssetVersionGen(
desc.assetVersion,
))
}
newAssets[idx] = randAsset(t, opts...)
// Group assets by anchor point before building tap commitments.
assetCommitment, err := commitment.NewAssetCommitment(
newAssets[idx],
)
require.NoError(t, err)
_, ok := anchorPointsToAssetCommitments[desc.anchorPoint]
if !ok {
anchorPointsToAssetCommitments[desc.anchorPoint] =
[]*commitment.AssetCommitment{}
}
anchorPointsToAssetCommitments[desc.anchorPoint] = append(
anchorPointsToAssetCommitments[desc.anchorPoint],
assetCommitment,
)
}
anchorPointsToTapCommitments := make(
map[wire.OutPoint]*commitment.TapCommitment,
)
for anchorPoint, commitments := range anchorPointsToAssetCommitments {
tapCommitment, err := commitment.NewTapCommitment(
nil, commitments...,
)
require.NoError(t, err)
anchorPointsToTapCommitments[anchorPoint] = tapCommitment
}
assetProofs := make([]proof.Proof, len(newAssets))
for i, newAsset := range newAssets {
desc := assetDescs[i]
anchorPoint := a.anchorPointsToTx[desc.anchorPoint]
height := a.anchorPointsToHeights[desc.anchorPoint]
tapCommitment := anchorPointsToTapCommitments[desc.anchorPoint]
// Encode a minimal proof so we have a valid proof blob to
// store.
assetProof := proof.Proof{}
assetProof.AnchorTx = *anchorPoint
assetProof.BlockHeight = height
txMerkleProof, err := proof.NewTxMerkleProof(
[]*wire.MsgTx{anchorPoint}, 0,
)
require.NoError(t, err)
assetProof.TxMerkleProof = *txMerkleProof
assetProof.Asset = *newAsset
assetProof.InclusionProof = proof.TaprootProof{
OutputIndex: 0,
InternalKey: test.RandPubKey(t),
}
assetProofs[i] = assetProof
proofBlob, err := proof.EncodeAsProofFile(&assetProof)
require.NoError(t, err)
err = assetStore.importAssetFromProof(
ctx, assetStore.db, &proof.AnnotatedProof{
AssetSnapshot: &proof.AssetSnapshot{
AnchorTx: anchorPoint,
InternalKey: test.RandPubKey(t),
Asset: newAsset,
ScriptRoot: tapCommitment,
AnchorBlockHeight: height,
},
Blob: proofBlob,
},
)
require.NoError(t, err)
if desc.spent {
opBytes, err := encodeOutpoint(desc.anchorPoint)
require.NoError(t, err)
var (
scriptKey = newAsset.ScriptKey.PubKey
id = newAsset.ID()
)
params := SetAssetSpentParams{
ScriptKey: scriptKey.SerializeCompressed(),
GenAssetID: id[:],
AnchorPoint: opBytes,
}
_, err = assetStore.db.SetAssetSpent(ctx, params)
require.NoError(t, err)
}
if !desc.leasedUntil.IsZero() {
owner := newAsset.ID()
err = assetStore.LeaseCoins(
ctx, owner, desc.leasedUntil, desc.anchorPoint,
)
require.NoError(t, err)
}
}
return newAssets, assetProofs
}
func (a *assetGenerator) assetSpecifierAssetID(i int,
op wire.OutPoint) asset.Specifier {
gen := a.assetGens[i]
gen.FirstPrevOut = op
id := gen.ID()
return asset.NewSpecifierFromId(id)
}
func (a *assetGenerator) assetSpecifierGroupKey(i int,
op wire.OutPoint) asset.Specifier {
gen := a.assetGens[i]
gen.FirstPrevOut = op
genTweak := gen.ID()
groupPriv := *a.groupKeys[i]
internalPriv := input.TweakPrivKey(&groupPriv, genTweak[:])
tweakedPriv := txscript.TweakTaprootPrivKey(*internalPriv, nil)
groupPubKey := tweakedPriv.PubKey()
return asset.NewSpecifierFromGroupKey(*groupPubKey)
}
type filterOpt func(f *AssetQueryFilters)
func filterSpecifier(s asset.Specifier) filterOpt {
return func(f *AssetQueryFilters) {
f.AssetSpecifier = s
}
}
func filterMinAmt(amt uint64) filterOpt {
return func(f *AssetQueryFilters) {
f.MinAmt = amt
}
}
func filterMaxAmt(amt uint64) filterOpt {
return func(f *AssetQueryFilters) {
f.MaxAmt = amt
}
}
func filterDistinctSpecifier() filterOpt {
return func(f *AssetQueryFilters) {
f.DistinctSpecifier = true
}
}
func filterAnchorHeight(height int32) filterOpt {
return func(f *AssetQueryFilters) {
f.MinAnchorHeight = height
}
}
func filterAnchorPoint(point *wire.OutPoint) filterOpt {
return func(f *AssetQueryFilters) {
f.AnchorPoint = point
}
}
func filterScriptKey(key *asset.ScriptKey) filterOpt {
return func(f *AssetQueryFilters) {
f.ScriptKey = key
}
}
func filterScriptKeyType(keyType asset.ScriptKeyType) filterOpt {
return func(f *AssetQueryFilters) {
f.ScriptKeyType = fn.Some(keyType)
}
}
// TestFetchAllAssets tests that the different AssetQueryFilters work as
// expected.
func TestFetchAllAssets(t *testing.T) {
t.Parallel()
const (
numAssetIDs = 12
numGroupKeys = 2
)
internalKey := test.RandPubKey(t)
tweak := test.RandBytes(32)
scriptPubKey := txscript.ComputeTaprootOutputKey(internalKey, tweak)
scriptKeyWithScript := &asset.ScriptKey{
PubKey: scriptPubKey,
TweakedScriptKey: &asset.TweakedScriptKey{
RawKey: keychain.KeyDescriptor{
PubKey: internalKey,
},
Tweak: tweak,
},
}
ctx := context.Background()
assetGen := newAssetGenerator(t, numAssetIDs, numGroupKeys)
availableAssets := []assetDesc{{
assetGen: assetGen.assetGens[0],
anchorPoint: assetGen.anchorPoints[0],
amt: 5,
}, {
assetGen: assetGen.assetGens[1],
anchorPoint: assetGen.anchorPoints[0],
amt: 1,
}, {
assetGen: assetGen.assetGens[2],
anchorPoint: assetGen.anchorPoints[0],
amt: 34,
scriptKey: scriptKeyWithScript,
}, {
assetGen: assetGen.assetGens[3],
anchorPoint: assetGen.anchorPoints[1],
amt: 99,
spent: true,
}, {
assetGen: assetGen.assetGens[4],
anchorPoint: assetGen.anchorPoints[1],
amt: 12,
}, {
assetGen: assetGen.assetGens[5],
anchorPoint: assetGen.anchorPoints[2],
amt: 666,
spent: true,
}, {
assetGen: assetGen.assetGens[6],
anchorPoint: assetGen.anchorPoints[3],
amt: 22,
leasedUntil: time.Now().Add(time.Hour),
}, {
assetGen: assetGen.assetGens[7],
anchorPoint: assetGen.anchorPoints[3],
amt: 666,
spent: true,
}, {
assetGen: assetGen.assetGens[8],
anchorPoint: assetGen.anchorPoints[4],
amt: 34,
leasedUntil: time.Now().Add(time.Hour),
}, {
assetGen: assetGen.assetGens[9],
anchorPoint: assetGen.anchorPoints[4],
amt: 777,
scriptKey: scriptKeyWithScript,
}, {
assetGen: assetGen.assetGens[10],
anchorPoint: assetGen.anchorPoints[10],
amt: 10,
keyGroup: assetGen.groupKeys[0],
}, {
assetGen: assetGen.assetGens[11],
anchorPoint: assetGen.anchorPoints[11],
amt: 8,
groupAnchorGen: &assetGen.assetGens[10],
groupAnchorGenPoint: &assetGen.anchorPoints[10],
keyGroup: assetGen.groupKeys[0],
}}
makeFilter := func(opts ...filterOpt) *AssetQueryFilters {
var filter AssetQueryFilters
for _, opt := range opts {
opt(&filter)
}
return &filter
}
// First, we'll create a new assets store and then insert the set of
// assets described by the asset descriptions.
_, assetsStore, _ := newAssetStore(t)
genAssets, _ := assetGen.genAssets(t, assetsStore, availableAssets)
numGenAssets := len(genAssets)
lastAsset := genAssets[numGenAssets-1]
testCases := []struct {
name string
includeSpent bool
includeLeased bool
filter *AssetQueryFilters
numAssets int
err error
}{{
name: "no constraints",
numAssets: 6,
}, {
name: "no constraints, include leased",
includeLeased: true,
numAssets: 9,
}, {
name: "no constraints, include spent",
includeSpent: true,
numAssets: 8,
}, {
name: "no constraints, include leased, include spent",
includeLeased: true,
includeSpent: true,
numAssets: 12,
}, {
name: "min amount",
filter: makeFilter(
filterMinAmt(12),
),
numAssets: 2,
}, {
name: "min amount, include spent",
filter: makeFilter(
filterMinAmt(12),
),
includeSpent: true,
numAssets: 4,
}, {
name: "min amount, include leased",
filter: makeFilter(
filterMinAmt(12),
),
includeLeased: true,
numAssets: 5,
}, {
name: "min amount, include leased, include spent",
filter: makeFilter(
filterMinAmt(12),
),
includeLeased: true,
includeSpent: true,
numAssets: 8,
}, {
name: "max amount",
filter: makeFilter(
filterMaxAmt(100),
),
numAssets: 6,
}, {
name: "max amount, include spent",
filter: makeFilter(
filterMaxAmt(100),
),
includeSpent: true,
numAssets: 7,
}, {
name: "max amount, include leased",
filter: makeFilter(
filterMaxAmt(100),
),
includeLeased: true,
numAssets: 8,
}, {
name: "max amount, include leased, include spent",
filter: makeFilter(
filterMaxAmt(100),
),
includeLeased: true,
includeSpent: true,
numAssets: 9,
}, {
name: "default min height, include spent",
filter: makeFilter(
filterAnchorHeight(500),
),
includeSpent: true,
numAssets: 8,
}, {
name: "specific height",
filter: makeFilter(
filterAnchorHeight(512),
),
numAssets: 0,
}, {
name: "specific height, include spent",
filter: makeFilter(
filterAnchorHeight(502),
),
includeSpent: true,
numAssets: 3,
}, {
name: "script key with tapscript",
filter: makeFilter(
filterMinAmt(100),
filterScriptKeyType(asset.ScriptKeyBip86),
),
numAssets: 0,
}, {
name: "query by script key",
filter: makeFilter(
filterScriptKey(scriptKeyWithScript),
),
numAssets: 1,
}, {
name: "query by script key, include leased",
filter: makeFilter(
filterScriptKey(scriptKeyWithScript),
),
includeLeased: true,
numAssets: 2,
}, {
name: "query by group key only",
filter: makeFilter(
filterSpecifier(asset.NewSpecifierFromGroupKey(
lastAsset.GroupKey.GroupPubKey,
)),
),