-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathasset.go
More file actions
2622 lines (2192 loc) · 79.6 KB
/
Copy pathasset.go
File metadata and controls
2622 lines (2192 loc) · 79.6 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 asset
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"reflect"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/lightninglabs/taproot-assets/fn"
"github.com/lightninglabs/taproot-assets/mssmt"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/tlv"
)
const (
// MaxAssetNameLength is the maximum byte length of an asset's name.
// This byte length is equivalent to character count for single-byte
// UTF-8 characters.
MaxAssetNameLength = 64
// MaxAssetEncodeSizeBytes is the size we expect an asset to not exceed
// in its encoded form. This is used to prevent OOMs when decoding
// assets. The main contributing factor to this size are the previous
// witnesses which we currently allow to number up to 65k witnesses.
MaxAssetEncodeSizeBytes = blockchain.MaxBlockWeight
// PedersenXPubMasterKeyFingerprint is the master key fingerprint we use
// to identify the fake xPub we create from a Pedersen commitment public
// key (which is a special form of tweaked NUMS key). Master key
// fingerprints in PSBTs are always encoded as little-endian uint32s but
// displayed as 4 bytes of hex. Serialized as little-endian uint32, this
// spells "7a9a55e7" which can be read as "TAP asset" in leet speak
// (with a bit of imagination).
PedersenXPubMasterKeyFingerprint uint32 = 0xe7559a7a
)
// SerializedKey is a type for representing a public key, serialized in the
// compressed, 33-byte form.
type SerializedKey [33]byte
// NewSerializedKeyFromBytes creates a new SerializedKey from the given byte
// slice.
func NewSerializedKeyFromBytes(key []byte) (SerializedKey, error) {
var zero SerializedKey
// Ensure that the key is a valid public key.
if _, err := btcec.ParsePubKey(key); err != nil {
return zero, fmt.Errorf("invalid public key: %w", err)
}
var serialized SerializedKey
copy(serialized[:], key)
return serialized, nil
}
// ToPubKey returns the public key parsed from the serialized key.
func (s SerializedKey) ToPubKey() (*btcec.PublicKey, error) {
return btcec.ParsePubKey(s[:])
}
// SchnorrSerialized returns the Schnorr serialized, x-only 32-byte
// representation of the serialized key.
func (s SerializedKey) SchnorrSerialized() []byte {
return s[1:]
}
// CopyBytes returns a copy of the underlying array as a byte slice.
func (s SerializedKey) CopyBytes() []byte {
c := make([]byte, 33)
copy(c, s[:])
return c
}
// String returns the hex-encoded string representation of the serialized key.
func (s SerializedKey) String() string {
return hex.EncodeToString(s[:])
}
// ToSerialized serializes a public key in its 33-byte compressed form.
func ToSerialized(pubKey *btcec.PublicKey) SerializedKey {
var serialized SerializedKey
copy(serialized[:], pubKey.SerializeCompressed())
return serialized
}
// Version denotes the version of the Taproot Asset protocol in effect for an
// asset.
type Version uint8
const (
// V0 is the initial Taproot Asset protocol version.
V0 Version = 0
// V1 is the version of asset serialization that doesn't include the
// witness field when creating a TAP commitment. This is similar to
// segwit as found in Bitcoin land.
V1 Version = 1
)
// EncodeType is used to denote the type of encoding used for an asset.
type EncodeType uint8
const (
// EncodeNormal normal is the normal encoding type for an asset.
EncodeNormal EncodeType = iota
// EncodeSegwit denotes that the witness vector field is not to be
// encoded.
EncodeSegwit
)
// ScriptKeyType denotes the type of script key used for an asset. This type is
// serialized to the database, so we don't use iota for the values to ensure
// they don't change by accident.
type ScriptKeyType uint8
const (
// ScriptKeyUnknown is the default script key type used for assets that
// we don't know the type of. This should only be stored for assets
// where we don't know the internal key of the script key (e.g. for
// imported proofs).
ScriptKeyUnknown ScriptKeyType = 0
// ScriptKeyBip86 is the script key type used for assets that use the
// BIP86 style tweak (e.g. an empty tweak).
ScriptKeyBip86 ScriptKeyType = 1
// ScriptKeyScriptPathExternal is the script key type used for assets
// that use a script path that is defined by an external application.
// Keys with script paths are normally not shown in asset balances and
// by default aren't used for coin selection unless specifically
// requested.
ScriptKeyScriptPathExternal ScriptKeyType = 2
// ScriptKeyBurn is the script key type used for assets that are burned
// and not spendable.
ScriptKeyBurn ScriptKeyType = 3
// ScriptKeyTombstone is the script key type used for assets that are
// not spendable and have been marked as tombstones. This is only the
// case for zero-value assets that result from a non-interactive (TAP
// address) send where no change was left over. The script key used for
// this is a NUMS key that is not spendable.
ScriptKeyTombstone ScriptKeyType = 4
// ScriptKeyScriptPathChannel is the script key type used for assets
// that use a script path that is somehow related to Taproot Asset
// Channels. That means the script key is either a funding key
// (OP_TRUE), a commitment output key (to_local, to_remote, htlc), or a
// HTLC second-level transaction output key.
// Keys related to channels are not shown in asset balances (unless
// specifically requested) and are _never_ used for coin selection.
ScriptKeyScriptPathChannel ScriptKeyType = 5
// ScriptKeyUniquePedersen is the script key type used for assets that
// use a unique script key, tweaked with a Pedersen commitment key in a
// single Tapscript leaf. This is used to avoid collisions in the
// universe when there are multiple grouped asset UTXOs within the same
// on-chain output.
ScriptKeyUniquePedersen ScriptKeyType = 6
)
var (
// AllScriptKeyTypes is a slice of all known script key types.
AllScriptKeyTypes = []ScriptKeyType{
ScriptKeyUnknown,
ScriptKeyBip86,
ScriptKeyScriptPathExternal,
ScriptKeyBurn,
ScriptKeyTombstone,
ScriptKeyScriptPathChannel,
ScriptKeyUniquePedersen,
}
// ScriptKeyTypesNoChannel is a slice of all known script key types
// that are not related to channels. This is used to filter out channel
// related script keys when querying for assets that are not related to
// channels.
ScriptKeyTypesNoChannel = []ScriptKeyType{
ScriptKeyUnknown,
ScriptKeyBip86,
ScriptKeyScriptPathExternal,
ScriptKeyBurn,
ScriptKeyTombstone,
ScriptKeyUniquePedersen,
}
)
// ScriptKeyTypeForDatabaseQuery returns a slice of script key types that should
// be used when querying the database for assets. The returned slice will either
// contain all script key types or only those that are not related to channels,
// depending on the `excludeChannelRelated` parameter. Unless the user specifies
// a specific script key type, in which case the returned slice will only
// contain that specific script key type.
func ScriptKeyTypeForDatabaseQuery(excludeChannelRelated bool,
userSpecified fn.Option[ScriptKeyType]) []ScriptKeyType {
// If the user specified a script key type, we use that directly to
// filter the results.
if userSpecified.IsSome() {
specifiedType := userSpecified.UnwrapOr(ScriptKeyUnknown)
dbTypes := []ScriptKeyType{
specifiedType,
}
// If the user specifically requested BIP-86 script keys, we
// also include the Pedersen unique script key type, because
// those can be spent the same way as BIP-86 script keys, and
// they should be treated the same way as BIP-86 script keys.
if specifiedType == ScriptKeyBip86 {
dbTypes = append(dbTypes, ScriptKeyUniquePedersen)
}
return dbTypes
}
// For some queries, we want to get all the assets with all possible
// script key types. For those, we use the full set of script key types.
dbTypes := fn.CopySlice(AllScriptKeyTypes)
// For some RPCs (mostly balance related), we exclude the assets that
// are specifically used for funding custom channels by default. The
// balance of those assets is reported through lnd channel balance.
// Those assets are identified by the specific script key type for
// channel keys. We exclude them unless explicitly queried for.
if excludeChannelRelated {
dbTypes = fn.CopySlice(ScriptKeyTypesNoChannel)
}
return dbTypes
}
var (
// ZeroPrevID is the blank prev ID used for genesis assets and also
// asset split leaves.
ZeroPrevID PrevID
// ZeroID is the zero asset ID, indicating the absence of an ID.
ZeroID ID
// EmptyGenesis is the empty Genesis struct used for alt leaves.
EmptyGenesis Genesis
// EmptyGenesisID is the ID of the empty genesis struct.
EmptyGenesisID = EmptyGenesis.ID()
// NUMSBytes is the NUMS point we'll use for un-spendable script keys.
// It was generated via a try-and-increment approach using the phrase
// "taproot-assets" with SHA2-256. The code for the try-and-increment
// approach can be seen here:
// https://github.com/lightninglabs/lightning-node-connect/tree/master/mailbox/numsgen
NUMSBytes, _ = hex.DecodeString(
"027c79b9b26e463895eef5679d8558942c86c4ad2233adef01bc3e6d540b" +
"3653fe",
)
NUMSPubKey, _ = btcec.ParsePubKey(NUMSBytes)
NUMSCompressedKey = ToSerialized(NUMSPubKey)
NUMSScriptKey = ScriptKey{
PubKey: NUMSPubKey,
}
// ErrUnknownVersion is returned when an asset with an unknown asset
// version is being used.
ErrUnknownVersion = errors.New("asset: unknown asset version")
// ErrUnwrapAssetID is returned when an asset ID cannot be unwrapped
// from a Specifier.
ErrUnwrapAssetID = errors.New("unable to unwrap asset ID")
// ErrDuplicateAltLeafKey is returned when a slice of AltLeaves contains
// 2 or more AltLeaves with the same AssetCommitmentKey.
ErrDuplicateAltLeafKey = errors.New("duplicate alt leaf key")
)
const (
// TaprootAssetsKeyFamily is the key family used to generate internal
// keys that tapd will use creating internal taproot keys and also any
// other keys used for asset script keys.
// This was derived via: sum(map(lambda y: ord(y), 'tapd')).
// In order words: take the word tapd and return the integer
// representation of each character and sum those. We get 425, then
// divide that by 2, to allow us to fit this into just a 2-byte integer
// and to ensure compatibility with the remote signer.
TaprootAssetsKeyFamily = 212
)
const (
// MetaHashLen is the length of the metadata hash.
MetaHashLen = 32
)
// Genesis encodes an asset's genesis metadata which directly maps to its unique
// ID within the Taproot Asset protocol.
type Genesis struct {
// FirstPrevOut represents the outpoint of the transaction's first
// input that resulted in the creation of the asset.
//
// NOTE: This is immutable for the lifetime of the asset.
FirstPrevOut wire.OutPoint
// Tag is a human-readable identifier for the asset. This does not need
// to be unique, but asset issuers should attempt for it to be unique if
// possible. Users usually recognise this field as the asset's name.
//
// NOTE: This is immutable for the lifetime of the asset.
Tag string
// MetaHash is the hash of the set of encoded meta data. This value is
// carried along for all assets transferred in the "light cone" of the
// genesis asset. The preimage for this field may optionally be
// revealed within the genesis asset proof for this asset.
//
// NOTE: This is immutable for the lifetime of the asset.
MetaHash [MetaHashLen]byte
// OutputIndex is the index of the output that carries the unique
// Taproot Asset commitment in the genesis transaction.
OutputIndex uint32
// Type uniquely identifies the type of Taproot asset.
Type Type
}
// TagHash computes the SHA-256 hash of the asset's tag.
func (g Genesis) TagHash() [sha256.Size]byte {
// TODO(roasbeef): make the tag similar to the meta data here?
// * would then mean the Genesis struct is also constant sized
return sha256.Sum256([]byte(g.Tag))
}
// Copy returns a deep copy of *Genesis. Every field is value-typed
// (OutPoint, string, fixed-size array, scalars), so a struct value
// copy is itself a deep copy. Returns nil if g is nil.
func (g *Genesis) Copy() *Genesis {
if g == nil {
return nil
}
cpy := *g
return &cpy
}
// ID serves as a unique identifier of an asset, resulting from:
//
// sha256(genesisOutPoint || sha256(tag) || sha256(metadata) ||
// outputIndex || assetType)
type ID [sha256.Size]byte
// NewIDFromBytes creates a new ID from the given byte slice. The byte slice
// must be exactly 32 bytes long, otherwise an error is returned.
func NewIDFromBytes(id []byte) (ID, error) {
var zero ID
// Basic sanity check to ensure the ID is the correct length.
if len(id) != sha256.Size {
return zero, fmt.Errorf("invalid ID length: %d", len(id))
}
// Copy the byte slice into a new ID instance.
var assetID ID
copy(assetID[:], id)
return assetID, nil
}
// String returns the hex-encoded string representation of the ID.
func (i ID) String() string {
return hex.EncodeToString(i[:])
}
// Record returns a TLV record that can be used to encode/decode an ID to/from a
// TLV stream.
//
// NOTE: This is part of the tlv.RecordProducer interface.
func (i *ID) Record() tlv.Record {
const recordSize = sha256.Size
// Note that we set the type here as zero, as when used with a
// tlv.RecordT, the type param will be used as the type.
return tlv.MakeStaticRecord(0, i, recordSize, IDEncoder, IDDecoder)
}
// Ensure ID implements the tlv.RecordProducer interface.
var _ tlv.RecordProducer = (*ID)(nil)
// ID computes an asset's unique identifier from its metadata.
func (g Genesis) ID() ID {
tagHash := g.TagHash()
h := sha256.New()
_ = wire.WriteOutPoint(h, 0, 0, &g.FirstPrevOut)
_, _ = h.Write(tagHash[:])
_, _ = h.Write(g.MetaHash[:])
_ = binary.Write(h, binary.BigEndian, g.OutputIndex)
_ = binary.Write(h, binary.BigEndian, g.Type)
return *(*ID)(h.Sum(nil))
}
// Encode encodes an asset genesis.
func (g Genesis) Encode(w io.Writer) error {
var buf [8]byte
return GenesisEncoder(w, &g, &buf)
}
// DecodeGenesis decodes an asset genesis.
func DecodeGenesis(r io.Reader) (Genesis, error) {
var (
buf [8]byte
gen Genesis
)
err := GenesisDecoder(r, &gen, &buf, 0)
return gen, err
}
// Specifier is a type that can be used to specify an asset by its ID, its asset
// group public key, or both.
type Specifier struct {
// id is the asset ID.
id fn.Option[ID]
// groupKey is the asset group public key.
groupKey fn.Option[btcec.PublicKey]
}
// NewSpecifier creates a new Specifier instance based on the provided
// parameters.
//
// The Specifier identifies an asset using either an asset ID, a group public
// key, or a group key. At least one of these must be specified if the
// `mustBeSpecified` parameter is set to true.
func NewSpecifier(id *ID, groupPubKey *btcec.PublicKey, groupKey *GroupKey,
mustBeSpecified bool) (Specifier, error) {
// Return an error if the asset ID, group public key, and group key are
// all nil and at least one of them must be specified.
isAnySpecified := id != nil || groupPubKey != nil || groupKey != nil
if !isAnySpecified && mustBeSpecified {
return Specifier{}, fmt.Errorf("at least one of the asset ID "+
"or asset group key fields must be specified "+
"(id=%v, groupPubKey=%v, groupKey=%v)",
id, groupPubKey, groupKey)
}
// Create an option for the asset ID.
optId := fn.MaybeSome(id)
// Create an option for the group public key.
optGroupPubKey := fn.MaybeSome(groupPubKey)
if groupKey != nil {
optGroupPubKey = fn.Some(groupKey.GroupPubKey)
}
return Specifier{
id: optId,
groupKey: optGroupPubKey,
}, nil
}
// NewSpecifierOptionalGroupPubKey creates a new specifier that specifies an
// asset by its ID and an optional group public key.
func NewSpecifierOptionalGroupPubKey(id ID,
groupPubKey *btcec.PublicKey) Specifier {
s := Specifier{
id: fn.Some(id),
}
if groupPubKey != nil {
s.groupKey = fn.Some(*groupPubKey)
}
return s
}
// NewSpecifierOptionalGroupKey creates a new specifier that specifies an
// asset by its ID and an optional group key.
func NewSpecifierOptionalGroupKey(id ID, groupKey *GroupKey) Specifier {
s := Specifier{
id: fn.Some(id),
}
if groupKey != nil {
s.groupKey = fn.Some(groupKey.GroupPubKey)
}
return s
}
// NewSpecifierFromId creates a new specifier that specifies an asset by its ID.
func NewSpecifierFromId(id ID) Specifier {
return Specifier{
id: fn.Some(id),
}
}
// NewSpecifierFromGroupKey creates a new specifier that specifies an asset by
// its group public key.
func NewSpecifierFromGroupKey(groupPubKey btcec.PublicKey) Specifier {
return Specifier{
groupKey: fn.Some(groupPubKey),
}
}
// NewExclusiveSpecifier creates a specifier that may only include one of asset
// ID or group key. If both are set then a specifier over the group key is
// created.
func NewExclusiveSpecifier(id *ID,
groupPubKey *btcec.PublicKey) (Specifier, error) {
switch {
case groupPubKey != nil:
return NewSpecifierFromGroupKey(*groupPubKey), nil
case id != nil:
return NewSpecifierFromId(*id), nil
}
return Specifier{}, fmt.Errorf("must set either asset ID or group key")
}
// String returns a human-readable description of the specifier.
func (s *Specifier) String() string {
// An unset asset ID is represented as an empty string.
var assetIdStr string
s.WhenId(func(id ID) {
assetIdStr = id.String()
})
var groupKeyBytes []byte
s.WhenGroupPubKey(func(key btcec.PublicKey) {
groupKeyBytes = key.SerializeCompressed()
})
return fmt.Sprintf("AssetSpecifier(id=%s, group_pub_key=%x)",
assetIdStr, groupKeyBytes)
}
// AsBytes returns the asset ID and group public key as byte slices.
func (s *Specifier) AsBytes() ([]byte, []byte) {
var assetIDBytes, groupKeyBytes []byte
s.WhenGroupPubKey(func(groupKey btcec.PublicKey) {
groupKeyBytes = groupKey.SerializeCompressed()
})
s.WhenId(func(id ID) {
assetIDBytes = id[:]
})
return assetIDBytes, groupKeyBytes
}
// HasId returns true if the asset ID field is specified.
func (s *Specifier) HasId() bool {
return s.id.IsSome()
}
// HasGroupPubKey returns true if the asset group public key field is specified.
func (s *Specifier) HasGroupPubKey() bool {
return s.groupKey.IsSome()
}
// IsSome returns true if the specifier is set.
func (s *Specifier) IsSome() bool {
return s.HasId() || s.HasGroupPubKey()
}
// WhenId executes the given function if the ID field is specified.
func (s *Specifier) WhenId(f func(ID)) {
s.id.WhenSome(f)
}
// ID returns the underlying asset ID option of the specifier.
func (s *Specifier) ID() fn.Option[ID] {
return s.id
}
// GroupKey returns the underlying asset group public key option of the
// specifier.
func (s *Specifier) GroupKey() fn.Option[btcec.PublicKey] {
return s.groupKey
}
// WhenGroupPubKey executes the given function if asset group public key field
// is specified.
func (s *Specifier) WhenGroupPubKey(f func(btcec.PublicKey)) {
s.groupKey.WhenSome(f)
}
// UnwrapIdOrErr unwraps the ID field or returns an error if it is not
// specified.
func (s *Specifier) UnwrapIdOrErr() (ID, error) {
id := s.id.UnwrapToPtr()
if id == nil {
return ID{}, ErrUnwrapAssetID
}
return *id, nil
}
// UnwrapIdToPtr unwraps the ID field to a pointer.
func (s *Specifier) UnwrapIdToPtr() *ID {
return s.id.UnwrapToPtr()
}
// UnwrapGroupKeyToPtr unwraps the asset group public key field to a pointer.
func (s *Specifier) UnwrapGroupKeyToPtr() *btcec.PublicKey {
return s.groupKey.UnwrapToPtr()
}
// UnwrapGroupKeyOrErr unwraps the group public key field or returns an error if
// it is not specified.
func (s *Specifier) UnwrapGroupKeyOrErr() (*btcec.PublicKey, error) {
groupKey := s.groupKey.UnwrapToPtr()
if groupKey == nil {
return nil, fmt.Errorf("unable to unwrap asset group public " +
"key")
}
return groupKey, nil
}
// UnwrapToPtr unwraps the asset ID and asset group public key fields,
// returning them as pointers.
func (s *Specifier) UnwrapToPtr() (*ID, *btcec.PublicKey) {
return s.UnwrapIdToPtr(), s.UnwrapGroupKeyToPtr()
}
// AssertNotEmpty checks whether the specifier is empty, returning an error if
// so.
func (s *Specifier) AssertNotEmpty() error {
if !s.HasId() && !s.HasGroupPubKey() {
return fmt.Errorf("asset specifier is empty")
}
return nil
}
// Equal compares this specifier to another one, returning true if they are
// equal. If strict is true, then both specifiers need to either have both equal
// asset IDs and group keys set or only one of those (but matching). If strict
// is false, then it's enough to have the same group key _or_ the same asset ID
// (if one has no group key set). This is useful for cases where one specifier
// only specifies the group key, while the other one specifies both the group
// key and the asset ID. In that case, we can consider them equal if the group
// keys match, even if the asset IDs are different (or one is not set).
func (s *Specifier) Equal(other *Specifier, strict bool) (bool, error) {
// If both specifiers are nil, they are equal.
if s == nil && other == nil {
return true, nil
}
// If one of the specifiers is nil, they are not equal.
if s == nil || other == nil {
return false, nil
}
// If either of them is empty while the other is not, they are not
// equal.
if (s.HasId() || s.HasGroupPubKey()) !=
(other.HasId() || other.HasGroupPubKey()) {
return false, nil
}
// If they both have distinct elements set, then they are not equal.
if s.HasId() != other.HasId() &&
s.HasGroupPubKey() != other.HasGroupPubKey() {
return false, nil
}
// If both specifiers have a group public key, compare them.
if s.HasGroupPubKey() && other.HasGroupPubKey() {
groupKeyA := s.UnwrapGroupKeyToPtr()
groupKeyB := other.UnwrapGroupKeyToPtr()
// If any unwrapped element is nil, something's wrong, and we
// can't compare them.
if groupKeyA == nil || groupKeyB == nil {
return false, fmt.Errorf("unable to unwrap group key "+
"from specifier: %v vs %v", s, other)
}
if !groupKeyA.IsEqual(groupKeyB) {
return false, nil
}
// If we're not doing a strict comparison, then we can return
// true here if the group keys match. The group key has higher
// priority than the ID, so if they match and the comparison
// isn't strict, we can consider the specifiers equal.
if !strict {
return true, nil
}
}
// If both specifiers have an ID, compare them.
if s.HasId() && other.HasId() {
idA := s.UnwrapIdToPtr()
idB := other.UnwrapIdToPtr()
// If any unwrapped element is nil, something's wrong and we
// can't compare them.
if idA == nil || idB == nil {
return false, fmt.Errorf("unable to unwrap asset ID "+
"from specifier: %v vs %v", s, other)
}
if *idA != *idB {
return false, nil
}
}
return true, nil
}
// Type denotes the asset types supported by the Taproot Asset protocol.
type Type uint8
const (
// Normal is an asset that can be represented in multiple units,
// resembling a divisible asset.
Normal Type = 0
// Collectible is a unique asset, one that cannot be represented in
// multiple units.
Collectible Type = 1
)
// String returns a human-readable description of the type.
func (t Type) String() string {
switch t {
case Normal:
return "Normal"
case Collectible:
return "Collectible"
default:
return "<Unknown>"
}
}
// PrevID serves as a reference to an asset's previous input.
type PrevID struct {
// OutPoint is the Bitcoin-level identifier (TXID + vout) of the UTXO
// anchoring the asset state.
OutPoint wire.OutPoint
// ID is the TAP-level asset identifier.
ID ID
// ScriptKey is the TAP-level Taproot output key that committed to the
// asset's spending conditions. Serialized to ensure comparability.
ScriptKey SerializedKey
}
// Hash returns the SHA-256 hash of all items encapsulated by PrevID.
func (id PrevID) Hash() [sha256.Size]byte {
h := sha256.New()
_ = wire.WriteOutPoint(h, 0, 0, &id.OutPoint)
_, _ = h.Write(id.ID[:])
_, _ = h.Write(id.ScriptKey.SchnorrSerialized())
return *(*[sha256.Size]byte)(h.Sum(nil))
}
// String returns a human-readable description of the PrevID.
func (id PrevID) String() string {
return fmt.Sprintf("PrevID(outpoint=%s, id=%s, script_key=%x)",
id.OutPoint.String(), id.ID.String(), id.ScriptKey[:])
}
// AnchorPoint is a type alias for an asset anchor outpoint. It relates the
// on-chain anchor outpoint (txid:vout) to the corresponding committed asset.
type AnchorPoint = PrevID
// SplitCommitment represents the asset witness for an asset split.
type SplitCommitment struct {
// Proof is the proof for a particular asset split resulting from a
// split commitment.
Proof mssmt.Proof
// RootAsset is the asset containing the root of the split commitment
// tree from which the `Proof` above was computed from.
RootAsset Asset
}
// DeepEqual returns true if this split commitment is equal with the given split
// commitment.
func (s *SplitCommitment) DeepEqual(o *SplitCommitment) bool {
if s == nil || o == nil {
return s == o
}
if len(s.Proof.Nodes) != len(o.Proof.Nodes) {
return false
}
for i := range s.Proof.Nodes {
nodeA := s.Proof.Nodes[i]
nodeB := o.Proof.Nodes[i]
if !mssmt.IsEqualNode(nodeA, nodeB) {
return false
}
}
// We can't directly compare the root assets, as some non-TLV fields
// might be different in unit tests. To avoid introducing flakes, we
// only compare the encoded TLV data.
var bufA, bufB bytes.Buffer
// We ignore errors here, these possible errors (incorrect TLV stream
// being created) are covered in unit tests.
_ = s.RootAsset.Encode(&bufA)
_ = o.RootAsset.Encode(&bufB)
return bytes.Equal(bufA.Bytes(), bufB.Bytes())
}
// Witness is a nested TLV stream within the main Asset TLV stream that contains
// the necessary data to verify the movement of an asset. All fields should be
// nil to represent the creation of an asset, `TxWitness` and
// `SplitCommitmentProof` are mutually exclusive otherwise.
type Witness struct {
// PrevID is a reference to an asset's previous input.
//
// NOTE: This should only be nil upon the creation of an asset.
PrevID *PrevID
// TxWitness is a witness that satisfies the asset's previous ScriptKey.
//
// NOTE: This field and `SplitCommitmentProof` are mutually exclusive,
// except upon the creation of an asset, where both should be nil.
TxWitness wire.TxWitness
// SplitCommitmentProof is used to permit the spending of an asset UTXO
// created as a result of an asset split. When an asset is split, the
// non-change UTXO commits to the location of all other splits within an
// MS-SMT tree. When spending a change UTXO resulting from a
// `SplitCommitment`, a normal `Witness` isn't required, instead the
// owner of the change asset UTXO must prove that it holds a valid split
// which was authorized by the main transfer transaction.
//
// Outputs with the same `SplitCommitment` are said to share a single
// `Witness` as such outputs are the result of a new asset split.
// Therefore, we only need a single witness and the resulting merkle-sum
// asset tree to verify a transfer.
//
// NOTE: This field and `TxWitness` are mutually exclusive,
// except upon the creation of an asset, where both should be nil.
//
// TODO: This still needs to be specified further in the BIPs, see
// https://github.com/lightninglabs/taproot-assets/issues/3.
SplitCommitment *SplitCommitment
}
// encodeRecords determines the non-nil records to include when encoding an
// asset witness at runtime. This version takes an extra param to determine if
// the witness should be encoded or not.
func (w *Witness) encodeRecords(encodeType EncodeType) []tlv.Record {
var records []tlv.Record
if w == nil {
return records
}
if w.PrevID != nil {
records = append(records, NewWitnessPrevIDRecord(&w.PrevID))
}
if len(w.TxWitness) > 0 && encodeType == EncodeNormal {
records = append(records, NewWitnessTxWitnessRecord(
&w.TxWitness,
))
}
if w.SplitCommitment != nil {
records = append(records, NewWitnessSplitCommitmentRecord(
&w.SplitCommitment,
))
}
return records
}
// EncodeRecords determines the non-nil records to include when encoding an
// asset witness at runtime.
func (w *Witness) EncodeRecords() []tlv.Record {
return w.encodeRecords(EncodeNormal)
}
// DecodeRecords provides all records known for an asset witness for proper
// decoding.
func (w *Witness) DecodeRecords() []tlv.Record {
return []tlv.Record{
NewWitnessPrevIDRecord(&w.PrevID),
NewWitnessTxWitnessRecord(&w.TxWitness),
NewWitnessSplitCommitmentRecord(&w.SplitCommitment),
}
}
// Encode encodes an asset witness into a TLV stream.
func (w *Witness) Encode(writer io.Writer) error {
if w == nil {
return fmt.Errorf("cannot encode nil witness")
}
stream, err := tlv.NewStream(w.EncodeRecords()...)
if err != nil {
return err
}
return stream.Encode(writer)
}
// EncodeNoWitness encodes an asset witness into a TLV stream, but does not
// include the raw witness field. The prevID and the split commitment are still
// included.
func (w *Witness) EncodeNoWitness(writer io.Writer) error {
stream, err := tlv.NewStream(w.encodeRecords(EncodeSegwit)...)
if err != nil {
return err
}
return stream.Encode(writer)
}
// Decode decodes an asset witness from a TLV stream.
func (w *Witness) Decode(r io.Reader) error {
stream, err := tlv.NewStream(w.DecodeRecords()...)
if err != nil {
return err
}
return stream.Decode(r)
}
// DeepEqual returns true if this witness is equal with the given witness. If
// the skipTxWitness boolean is set, the TxWitness field of the Witness is not
// compared.
func (w *Witness) DeepEqual(skipTxWitness bool, o *Witness) bool {
if w == nil || o == nil {
return w == o
}
if !reflect.DeepEqual(w.PrevID, o.PrevID) {
return false
}
if !w.SplitCommitment.DeepEqual(o.SplitCommitment) {
return false
}
// If we're not comparing the TxWitness, we're done. This might be
// useful when comparing witnesses of segregated witness version assets.
if skipTxWitness {
return true
}
return reflect.DeepEqual(w.TxWitness, o.TxWitness)
}
// ScriptVersion denotes the asset script versioning scheme.
type ScriptVersion uint16
const (
// ScriptV0 represents the initial asset script version of the Taproot
// Asset protocol. In this version, assets commit to a tweaked Taproot
// output key, allowing the ability for an asset to indirectly commit to
// multiple spending conditions.
ScriptV0 ScriptVersion = 0
)
// TapscriptTreeNodes represents the two supported ways to define a tapscript
// tree to be used as a sibling for a Taproot Asset commitment, an asset group
// key, or an asset script key. This type is used for interfacing with the DB,
// not for supplying in a proof or key derivation. The inner fields are mutually
// exclusive.
type TapscriptTreeNodes struct {
// leaves is created from an ordered list of TapLeaf objects and
// represents a Tapscript tree.
leaves *TapLeafNodes
// branch is created from a TapBranch and represents the tapHashes of
// the child nodes of a TapBranch.
branch *TapBranchNodes
}