forked from lightninglabs/taproot-assets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcserver.go
3365 lines (2787 loc) · 90.9 KB
/
rpcserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
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 taprootassets
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew"
proxy "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/lightninglabs/neutrino/cache/lru"
"github.com/lightninglabs/taproot-assets/address"
"github.com/lightninglabs/taproot-assets/asset"
"github.com/lightninglabs/taproot-assets/commitment"
"github.com/lightninglabs/taproot-assets/fn"
"github.com/lightninglabs/taproot-assets/mssmt"
"github.com/lightninglabs/taproot-assets/proof"
"github.com/lightninglabs/taproot-assets/rpcperms"
"github.com/lightninglabs/taproot-assets/tapdb"
"github.com/lightninglabs/taproot-assets/tapfreighter"
"github.com/lightninglabs/taproot-assets/tapgarden"
"github.com/lightninglabs/taproot-assets/tappsbt"
"github.com/lightninglabs/taproot-assets/taprpc"
wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc"
"github.com/lightninglabs/taproot-assets/taprpc/mintrpc"
"github.com/lightninglabs/taproot-assets/taprpc/tapdevrpc"
unirpc "github.com/lightninglabs/taproot-assets/taprpc/universerpc"
"github.com/lightninglabs/taproot-assets/tapscript"
"github.com/lightninglabs/taproot-assets/universe"
"github.com/lightningnetwork/lnd/build"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/signal"
"google.golang.org/grpc"
)
const (
// tapdMacaroonLocation is the value we use for the tapd macaroons'
// "Location" field when baking them.
tapdMacaroonLocation = "tapd"
// maxNumBlocksInCache is the maximum number of blocks we'll cache
// timestamps for. With 100k blocks we should only take up approximately
// 800kB of memory (4 bytes for the block height and 4 bytes for the
// timestamp, not including any map/cache overhead).
maxNumBlocksInCache = 100_000
)
// cacheableTimestamp is a wrapper around a uint32 that can be used as a value
// in an LRU cache.
type cacheableTimestamp uint32
// Size returns the size of the cacheable timestamp. Since we scale the cache by
// the number of items and not the total memory size, we can simply return 1
// here to count each timestamp as 1 item.
func (c cacheableTimestamp) Size() (uint64, error) {
return 1, nil
}
// rpcServer is the main RPC server for the Taproot Assets daemon that handles
// gRPC/REST/Websockets incoming requests.
type rpcServer struct {
started int32
shutdown int32
taprpc.UnimplementedTaprootAssetsServer
wrpc.UnimplementedAssetWalletServer
mintrpc.UnimplementedMintServer
unirpc.UnimplementedUniverseServer
tapdevrpc.UnimplementedTapDevServer
interceptor signal.Interceptor
interceptorChain *rpcperms.InterceptorChain
cfg *Config
blockTimestampCache *lru.Cache[uint32, cacheableTimestamp]
quit chan struct{}
wg sync.WaitGroup
}
// newRPCServer creates a new RPC sever from the set of input dependencies.
func newRPCServer(interceptor signal.Interceptor,
interceptorChain *rpcperms.InterceptorChain,
cfg *Config) (*rpcServer, error) {
return &rpcServer{
interceptor: interceptor,
interceptorChain: interceptorChain,
blockTimestampCache: lru.NewCache[uint32, cacheableTimestamp](
maxNumBlocksInCache,
),
quit: make(chan struct{}),
cfg: cfg,
}, nil
}
// TODO(roasbeef): build in batching for asset creation?
// Start signals that the RPC server starts accepting requests.
func (r *rpcServer) Start() error {
if atomic.AddInt32(&r.started, 1) != 1 {
return nil
}
rpcsLog.Infof("Starting RPC Server")
return nil
}
// Stop signals that the RPC server should attempt a graceful shutdown and
// cancel any outstanding requests.
func (r *rpcServer) Stop() error {
if atomic.AddInt32(&r.shutdown, 1) != 1 {
return nil
}
rpcsLog.Infof("Stopping RPC Server")
close(r.quit)
r.wg.Wait()
return nil
}
// RegisterWithGrpcServer registers the rpcServer with the passed root gRPC
// server.
func (r *rpcServer) RegisterWithGrpcServer(grpcServer *grpc.Server) error {
// Register the main RPC server.
taprpc.RegisterTaprootAssetsServer(grpcServer, r)
wrpc.RegisterAssetWalletServer(grpcServer, r)
mintrpc.RegisterMintServer(grpcServer, r)
unirpc.RegisterUniverseServer(grpcServer, r)
tapdevrpc.RegisterGrpcServer(grpcServer, r)
return nil
}
// RegisterWithRestProxy registers the RPC server with the given rest proxy.
func (r *rpcServer) RegisterWithRestProxy(restCtx context.Context,
restMux *proxy.ServeMux, restDialOpts []grpc.DialOption,
restProxyDest string) error {
// With our custom REST proxy mux created, register our main RPC and
// give all subservers a chance to register as well.
err := taprpc.RegisterTaprootAssetsHandlerFromEndpoint(
restCtx, restMux, restProxyDest, restDialOpts,
)
if err != nil {
return err
}
err = wrpc.RegisterAssetWalletHandlerFromEndpoint(
restCtx, restMux, restProxyDest, restDialOpts,
)
if err != nil {
return err
}
err = mintrpc.RegisterMintHandlerFromEndpoint(
restCtx, restMux, restProxyDest, restDialOpts,
)
if err != nil {
return err
}
err = unirpc.RegisterUniverseHandlerFromEndpoint(
restCtx, restMux, restProxyDest, restDialOpts,
)
if err != nil {
return err
}
return nil
}
// allowCORS wraps the given http.Handler with a function that adds the
// Access-Control-Allow-Origin header to the response.
func allowCORS(handler http.Handler, origins []string) http.Handler {
allowHeaders := "Access-Control-Allow-Headers"
allowMethods := "Access-Control-Allow-Methods"
allowOrigin := "Access-Control-Allow-Origin"
// If the user didn't supply any origins that means CORS is disabled
// and we should return the original handler.
if len(origins) == 0 {
return handler
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
// Skip everything if the browser doesn't send the Origin field.
if origin == "" {
handler.ServeHTTP(w, r)
return
}
// Set the static header fields first.
w.Header().Set(
allowHeaders,
"Content-Type, Accept, Grpc-Metadata-Macaroon",
)
w.Header().Set(allowMethods, "GET, POST, DELETE")
// Either we allow all origins or the incoming request matches
// a specific origin in our list of allowed origins.
for _, allowedOrigin := range origins {
if allowedOrigin == "*" || origin == allowedOrigin {
// Only set allowed origin to requested origin.
w.Header().Set(allowOrigin, origin)
break
}
}
// For a pre-flight request we only need to send the headers
// back. No need to call the rest of the chain.
if r.Method == "OPTIONS" {
return
}
// Everything's prepared now, we can pass the request along the
// chain of handlers.
handler.ServeHTTP(w, r)
})
}
// StopDaemon will send a shutdown request to the interrupt handler, triggering
// a graceful shutdown of the daemon.
func (r *rpcServer) StopDaemon(_ context.Context,
_ *taprpc.StopRequest) (*taprpc.StopResponse, error) {
r.interceptor.RequestShutdown()
return &taprpc.StopResponse{}, nil
}
// DebugLevel allows a caller to programmatically set the logging verbosity of
// tapd. The logging can be targeted according to a coarse daemon-wide logging
// level, or in a granular fashion to specify the logging for a target
// sub-system.
func (r *rpcServer) DebugLevel(ctx context.Context,
req *taprpc.DebugLevelRequest) (*taprpc.DebugLevelResponse, error) {
// If show is set, then we simply print out the list of available
// sub-systems.
if req.Show {
return &taprpc.DebugLevelResponse{
SubSystems: strings.Join(
r.cfg.LogWriter.SupportedSubsystems(), " ",
),
}, nil
}
rpcsLog.Infof("[debuglevel] changing debug level to: %v", req.LevelSpec)
// Otherwise, we'll attempt to set the logging level using the
// specified level spec.
err := build.ParseAndSetDebugLevels(req.LevelSpec, r.cfg.LogWriter)
if err != nil {
return nil, err
}
return &taprpc.DebugLevelResponse{}, nil
}
// GetInfo returns general information relating to the active daemon. For
// example: its version, network, and lnd version.
func (r *rpcServer) GetInfo(context.Context,
*taprpc.GetInfoRequest) (*taprpc.GetInfoResponse, error) {
return &taprpc.GetInfoResponse{
Version: Version(),
LndVersion: r.cfg.Lnd.Version.Version,
Network: r.cfg.ChainParams.Name,
}, nil
}
// MintAsset attempts to mint the set of assets (async by default to ensure
// proper batching) specified in the request.
func (r *rpcServer) MintAsset(ctx context.Context,
req *mintrpc.MintAssetRequest) (*mintrpc.MintAssetResponse, error) {
// An asset name is mandatory, and cannot be the empty string.
if len(req.Asset.Name) == 0 {
return nil, fmt.Errorf("asset name cannot be empty")
}
specificGroupKey := len(req.Asset.GroupKey) != 0
specificGroupAnchor := len(req.Asset.GroupAnchor) != 0
// Using a specific group key or anchor implies disabling emission.
if req.EnableEmission {
if specificGroupKey || specificGroupAnchor {
return nil, fmt.Errorf("must disable emission to " +
"specify a group")
}
}
seedling := &tapgarden.Seedling{
AssetType: asset.Type(req.Asset.AssetType),
AssetName: req.Asset.Name,
Amount: req.Asset.Amount,
EnableEmission: req.EnableEmission,
}
// If a group key is provided, parse the provided group public key
// before creating the asset seedling.
if specificGroupKey {
if specificGroupAnchor {
return nil, fmt.Errorf("cannot specify a group key " +
"and a group anchor")
}
groupTweakedKey, err := btcec.ParsePubKey(req.Asset.GroupKey)
if err != nil {
return nil, fmt.Errorf("invalid group key: %w", err)
}
err = r.checkBalanceOverflow(
ctx, nil, groupTweakedKey,
req.Asset.Amount,
)
if err != nil {
return nil, err
}
seedling.GroupInfo = &asset.AssetGroup{
GroupKey: &asset.GroupKey{
GroupPubKey: *groupTweakedKey,
},
}
}
// If a group anchor is provided, propoate the name to the seedling.
// We cannot do any name validation from outside the minter.
if specificGroupAnchor {
seedling.GroupAnchor = &req.Asset.GroupAnchor
}
if req.Asset.AssetMeta != nil {
seedling.Meta = &proof.MetaReveal{
Type: proof.MetaType(req.Asset.AssetMeta.Type),
Data: req.Asset.AssetMeta.Data,
}
}
updates, err := r.cfg.AssetMinter.QueueNewSeedling(seedling)
if err != nil {
return nil, fmt.Errorf("unable to mint new asset: %w", err)
}
// Wait for an initial update so we can report back if things succeeded
// or failed.
select {
case <-ctx.Done():
return nil, fmt.Errorf("context closed: %w", ctx.Err())
case update := <-updates:
if update.Error != nil {
return nil, fmt.Errorf("unable to mint asset: %w",
update.Error)
}
return &mintrpc.MintAssetResponse{
BatchKey: update.BatchKey.SerializeCompressed(),
}, nil
}
}
// FinalizeBatch attempts to finalize the current pending batch.
func (r *rpcServer) FinalizeBatch(_ context.Context,
_ *mintrpc.FinalizeBatchRequest) (*mintrpc.FinalizeBatchResponse,
error) {
batchKey, err := r.cfg.AssetMinter.FinalizeBatch()
if err != nil {
return nil, fmt.Errorf("unable to finalize batch: %w", err)
}
// If there was no batch to finalize, return an empty response.
if batchKey == nil {
return &mintrpc.FinalizeBatchResponse{}, nil
}
return &mintrpc.FinalizeBatchResponse{
BatchKey: batchKey.SerializeCompressed(),
}, nil
}
// CancelBatch attempts to cancel the current pending batch.
func (r *rpcServer) CancelBatch(_ context.Context,
_ *mintrpc.CancelBatchRequest) (*mintrpc.CancelBatchResponse,
error) {
batchKey, err := r.cfg.AssetMinter.CancelBatch()
if err != nil {
return nil, fmt.Errorf("unable to cancel batch: %w", err)
}
// If there was no batch to cancel, return an empty response.
if batchKey == nil {
return &mintrpc.CancelBatchResponse{}, nil
}
return &mintrpc.CancelBatchResponse{
BatchKey: batchKey.SerializeCompressed(),
}, nil
}
// ListBatches lists the set of batches submitted for minting, including pending
// and cancelled batches.
func (r *rpcServer) ListBatches(_ context.Context,
req *mintrpc.ListBatchRequest) (*mintrpc.ListBatchResponse, error) {
var (
batchKey *btcec.PublicKey
err error
)
switch {
case len(req.GetBatchKey()) > 0 && len(req.GetBatchKeyStr()) > 0:
return nil, fmt.Errorf("cannot specify both batch_key and " +
"batch_key_string")
case len(req.GetBatchKey()) > 0:
batchKey, err = btcec.ParsePubKey(req.GetBatchKey())
if err != nil {
return nil, fmt.Errorf("invalid batch key: %w", err)
}
case len(req.GetBatchKeyStr()) > 0:
batchKeyBytes, err := hex.DecodeString(req.GetBatchKeyStr())
if err != nil {
return nil, fmt.Errorf("invalid batch key string: %w",
err)
}
batchKey, err = btcec.ParsePubKey(batchKeyBytes)
if err != nil {
return nil, fmt.Errorf("invalid batch key: %w", err)
}
}
batches, err := r.cfg.AssetMinter.ListBatches(batchKey)
if err != nil {
return nil, fmt.Errorf("unable to list batches: %w", err)
}
rpcBatches, err := fn.MapErr(batches, marshalMintingBatch)
if err != nil {
return nil, err
}
return &mintrpc.ListBatchResponse{
Batches: rpcBatches,
}, nil
}
// checkBalanceOverflow ensures that the new asset amount will not overflow
// the max allowed asset (or asset group) balance.
func (r *rpcServer) checkBalanceOverflow(ctx context.Context,
assetID *asset.ID, groupPubKey *btcec.PublicKey,
newAmount uint64) error {
if assetID != nil && groupPubKey != nil {
return fmt.Errorf("asset ID and group public key cannot both " +
"be set")
}
if assetID == nil && groupPubKey == nil {
return fmt.Errorf("asset ID and group public key cannot both " +
"be nil")
}
var balance uint64
switch {
case assetID != nil:
// Retrieve the current asset balance.
balances, err := r.cfg.AssetStore.QueryBalancesByAsset(
ctx, assetID,
)
if err != nil {
return fmt.Errorf("unable to query asset balance: %w",
err)
}
// There should only be one balance entry per asset.
for _, balanceEntry := range balances {
balance = balanceEntry.Balance
break
}
case groupPubKey != nil:
// Retrieve the current balance of the group.
balances, err := r.cfg.AssetStore.QueryAssetBalancesByGroup(
ctx, groupPubKey,
)
if err != nil {
return fmt.Errorf("unable to query group balance: %w",
err)
}
// There should only be one balance entry per group.
for _, balanceEntry := range balances {
balance = balanceEntry.Balance
break
}
}
// Check for overflow.
err := mssmt.CheckSumOverflowUint64(balance, newAmount)
if err != nil {
return fmt.Errorf("new asset amount would overflow "+
"asset balance: %w", err)
}
return nil
}
// ListAssets lists the set of assets owned by the target daemon.
func (r *rpcServer) ListAssets(ctx context.Context,
req *taprpc.ListAssetRequest) (*taprpc.ListAssetResponse, error) {
switch {
case req.IncludeSpent && req.IncludeLeased:
return nil, fmt.Errorf("cannot specify both include_spent " +
"and include_leased")
}
rpcAssets, err := r.fetchRpcAssets(
ctx, req.WithWitness, req.IncludeSpent, req.IncludeLeased,
)
if err != nil {
return nil, err
}
return &taprpc.ListAssetResponse{
Assets: rpcAssets,
}, nil
}
func (r *rpcServer) fetchRpcAssets(ctx context.Context, withWitness,
includeSpent, includeLeased bool) ([]*taprpc.Asset, error) {
assets, err := r.cfg.AssetStore.FetchAllAssets(
ctx, includeSpent, includeLeased, nil,
)
if err != nil {
return nil, fmt.Errorf("unable to read chain assets: %w", err)
}
rpcAssets := make([]*taprpc.Asset, len(assets))
for i, a := range assets {
rpcAssets[i], err = r.marshalChainAsset(ctx, a, withWitness)
if err != nil {
return nil, fmt.Errorf("unable to marshal asset: %w",
err)
}
}
return rpcAssets, nil
}
func (r *rpcServer) marshalChainAsset(ctx context.Context, a *tapdb.ChainAsset,
withWitness bool) (*taprpc.Asset, error) {
rpcAsset, err := MarshalAsset(
ctx, a.Asset, a.IsSpent, withWitness, r.cfg.AddrBook,
)
if err != nil {
return nil, err
}
var anchorTxBytes []byte
if a.AnchorTx != nil {
var anchorTxBuf bytes.Buffer
err := a.AnchorTx.Serialize(&anchorTxBuf)
if err != nil {
return nil, fmt.Errorf("unable to serialize anchor "+
"tx: %w", err)
}
anchorTxBytes = anchorTxBuf.Bytes()
}
rpcAsset.ChainAnchor = &taprpc.AnchorInfo{
AnchorTx: anchorTxBytes,
AnchorTxid: a.AnchorTxid.String(),
AnchorBlockHash: a.AnchorBlockHash.String(),
AnchorOutpoint: a.AnchorOutpoint.String(),
InternalKey: a.AnchorInternalKey.SerializeCompressed(),
MerkleRoot: a.AnchorMerkleRoot,
TapscriptSibling: a.AnchorTapscriptSibling,
BlockHeight: a.AnchorBlockHeight,
}
if a.AnchorLeaseOwner != [32]byte{} {
rpcAsset.LeaseOwner = a.AnchorLeaseOwner[:]
rpcAsset.LeaseExpiry = a.AnchorLeaseExpiry.UTC().Unix()
}
return rpcAsset, nil
}
// KeyLookup is used to determine whether a key is under the control of the
// local wallet.
type KeyLookup interface {
// IsLocalKey returns true if the key is under the control of the
// wallet and can be derived by it.
IsLocalKey(ctx context.Context, desc keychain.KeyDescriptor) bool
}
func MarshalAsset(ctx context.Context, a *asset.Asset,
isSpent, withWitness bool,
keyRing KeyLookup) (*taprpc.Asset, error) {
assetID := a.Genesis.ID()
scriptKeyIsLocal := false
if a.ScriptKey.TweakedScriptKey != nil && keyRing != nil {
scriptKeyIsLocal = keyRing.IsLocalKey(
ctx, a.ScriptKey.RawKey,
)
}
rpcAsset := &taprpc.Asset{
Version: int32(a.Version),
AssetGenesis: &taprpc.GenesisInfo{
GenesisPoint: a.Genesis.FirstPrevOut.String(),
Name: a.Genesis.Tag,
MetaHash: a.Genesis.MetaHash[:],
AssetId: assetID[:],
OutputIndex: a.Genesis.OutputIndex,
},
AssetType: taprpc.AssetType(a.Type),
Amount: a.Amount,
LockTime: int32(a.LockTime),
RelativeLockTime: int32(a.RelativeLockTime),
ScriptVersion: int32(a.ScriptVersion),
ScriptKey: a.ScriptKey.PubKey.SerializeCompressed(),
ScriptKeyIsLocal: scriptKeyIsLocal,
IsSpent: isSpent,
}
if a.GroupKey != nil {
var rawKey []byte
if a.GroupKey.RawKey.PubKey != nil {
rawKey = a.GroupKey.RawKey.PubKey.SerializeCompressed()
}
rpcAsset.AssetGroup = &taprpc.AssetGroup{
RawGroupKey: rawKey,
TweakedGroupKey: a.GroupKey.GroupPubKey.SerializeCompressed(),
AssetIdSig: a.GroupKey.Sig.Serialize(),
}
}
if withWitness {
for idx := range a.PrevWitnesses {
witness := a.PrevWitnesses[idx]
prevID := witness.PrevID
rpcPrevID := &taprpc.PrevInputAsset{
AnchorPoint: prevID.OutPoint.String(),
AssetId: prevID.ID[:],
ScriptKey: prevID.ScriptKey[:],
}
var rpcSplitCommitment *taprpc.SplitCommitment
if witness.SplitCommitment != nil {
rootAsset, err := MarshalAsset(
ctx, &witness.SplitCommitment.RootAsset,
false, true, nil,
)
if err != nil {
return nil, err
}
rpcSplitCommitment = &taprpc.SplitCommitment{
RootAsset: rootAsset,
}
}
rpcAsset.PrevWitnesses = append(
rpcAsset.PrevWitnesses, &taprpc.PrevWitness{
PrevId: rpcPrevID,
TxWitness: witness.TxWitness,
SplitCommitment: rpcSplitCommitment,
},
)
}
}
return rpcAsset, nil
}
func (r *rpcServer) listBalancesByAsset(ctx context.Context,
assetID *asset.ID) (*taprpc.ListBalancesResponse, error) {
balances, err := r.cfg.AssetStore.QueryBalancesByAsset(ctx, assetID)
if err != nil {
return nil, fmt.Errorf("unable to list balances: %w", err)
}
resp := &taprpc.ListBalancesResponse{
AssetBalances: make(map[string]*taprpc.AssetBalance, len(balances)),
}
for _, balance := range balances {
balance := balance
assetIDStr := hex.EncodeToString(balance.ID[:])
resp.AssetBalances[assetIDStr] = &taprpc.AssetBalance{
AssetGenesis: &taprpc.GenesisInfo{
Version: int32(balance.Version),
GenesisPoint: balance.GenesisPoint.String(),
Name: balance.Tag,
MetaHash: balance.MetaHash[:],
AssetId: balance.ID[:],
},
AssetType: taprpc.AssetType(balance.Type),
Balance: balance.Balance,
}
}
return resp, nil
}
func (r *rpcServer) listBalancesByGroupKey(ctx context.Context,
groupKey *btcec.PublicKey) (*taprpc.ListBalancesResponse, error) {
balances, err := r.cfg.AssetStore.QueryAssetBalancesByGroup(
ctx, groupKey,
)
if err != nil {
return nil, fmt.Errorf("unable to list balances: %w", err)
}
resp := &taprpc.ListBalancesResponse{
AssetGroupBalances: make(
map[string]*taprpc.AssetGroupBalance, len(balances),
),
}
for _, balance := range balances {
balance := balance
var groupKey []byte
if balance.GroupKey != nil {
groupKey = balance.GroupKey.SerializeCompressed()
}
groupKeyString := hex.EncodeToString(groupKey)
resp.AssetGroupBalances[groupKeyString] = &taprpc.AssetGroupBalance{
GroupKey: groupKey,
Balance: balance.Balance,
}
}
return resp, nil
}
// ListUtxos lists the UTXOs managed by the target daemon, and the assets they
// hold.
func (r *rpcServer) ListUtxos(ctx context.Context,
req *taprpc.ListUtxosRequest) (*taprpc.ListUtxosResponse, error) {
rpcAssets, err := r.fetchRpcAssets(ctx, false, false, req.IncludeLeased)
if err != nil {
return nil, err
}
managedUtxos, err := r.cfg.AssetStore.FetchManagedUTXOs(ctx)
if err != nil {
return nil, err
}
utxos := make(map[string]*taprpc.ManagedUtxo)
for _, u := range managedUtxos {
utxos[u.OutPoint.String()] = &taprpc.ManagedUtxo{
OutPoint: u.OutPoint.String(),
AmtSat: int64(u.OutputValue),
InternalKey: u.InternalKey.PubKey.SerializeCompressed(),
TaprootAssetRoot: u.TaprootAssetRoot,
MerkleRoot: u.MerkleRoot,
}
}
// Populate the assets managed by each UTXO.
for _, a := range rpcAssets {
op := a.ChainAnchor.AnchorOutpoint
utxo, ok := utxos[op]
if !ok {
return nil, fmt.Errorf("unable to find utxo %s for "+
"asset_id=%x", op, a.AssetGenesis.AssetId)
}
utxo.Assets = append(utxo.Assets, a)
utxos[op] = utxo
}
// As a final pass, we'll prune out any UTXOs that don't have any
// assets, as these may be in the DB just for record keeping.
for _, utxo := range utxos {
if len(utxo.Assets) == 0 {
delete(utxos, utxo.OutPoint)
}
}
return &taprpc.ListUtxosResponse{
ManagedUtxos: utxos,
}, nil
}
// ListGroups lists known groups and the assets held in each group.
func (r *rpcServer) ListGroups(ctx context.Context,
_ *taprpc.ListGroupsRequest) (*taprpc.ListGroupsResponse, error) {
readableAssets, err := r.cfg.AssetStore.FetchGroupedAssets(ctx)
if err != nil {
return nil, err
}
groupsWithAssets := make(map[string]*taprpc.GroupedAssets)
// Populate the map of group keys to assets in that group.
for _, a := range readableAssets {
groupKey := hex.EncodeToString(a.GroupKey.SerializeCompressed())
asset := &taprpc.AssetHumanReadable{
Id: a.ID[:],
Amount: a.Amount,
LockTime: int32(a.LockTime),
RelativeLockTime: int32(a.RelativeLockTime),
Tag: a.Tag,
MetaHash: a.MetaHash[:],
Type: taprpc.AssetType(a.Type),
}
_, ok := groupsWithAssets[groupKey]
if !ok {
groupsWithAssets[groupKey] = &taprpc.GroupedAssets{
Assets: []*taprpc.AssetHumanReadable{},
}
}
groupsWithAssets[groupKey].Assets = append(
groupsWithAssets[groupKey].Assets, asset,
)
}
return &taprpc.ListGroupsResponse{Groups: groupsWithAssets}, nil
}
// ListBalances lists the asset balances owned by the daemon.
func (r *rpcServer) ListBalances(ctx context.Context,
in *taprpc.ListBalancesRequest) (*taprpc.ListBalancesResponse, error) {
switch groupBy := in.GroupBy.(type) {
case *taprpc.ListBalancesRequest_AssetId:
if !groupBy.AssetId {
return nil, fmt.Errorf("invalid group_by")
}
var assetID *asset.ID
if len(in.AssetFilter) != 0 {
assetID = &asset.ID{}
if len(in.AssetFilter) != len(assetID) {
return nil, fmt.Errorf("invalid asset filter")
}
copy(assetID[:], in.AssetFilter)
}
return r.listBalancesByAsset(ctx, assetID)
case *taprpc.ListBalancesRequest_GroupKey:
if !groupBy.GroupKey {
return nil, fmt.Errorf("invalid group_by")
}
var groupKey *btcec.PublicKey
if len(in.GroupKeyFilter) != 0 {
var err error
groupKey, err = btcec.ParsePubKey(in.GroupKeyFilter)
if err != nil {
return nil, fmt.Errorf("invalid group key "+
"filter: %v", err)
}
}
return r.listBalancesByGroupKey(ctx, groupKey)
default:
return nil, fmt.Errorf("invalid group_by")
}
}
// ListTransfers lists all asset transfers managed by this deamon.
func (r *rpcServer) ListTransfers(ctx context.Context,
in *taprpc.ListTransfersRequest) (*taprpc.ListTransfersResponse,
error) {
parcels, err := r.cfg.AssetStore.QueryParcels(ctx, false)
if err != nil {
return nil, fmt.Errorf("failed to query parcels: %w", err)
}
resp := &taprpc.ListTransfersResponse{
Transfers: make([]*taprpc.AssetTransfer, len(parcels)),
}
for idx := range parcels {
resp.Transfers[idx], err = marshalOutboundParcel(parcels[idx])
if err != nil {
return nil, fmt.Errorf("failed to marshal parcel: %w",
err)
}
}
return resp, nil
}
// QueryAddrs queries the set of Taproot Asset addresses stored in the database.
func (r *rpcServer) QueryAddrs(ctx context.Context,
in *taprpc.QueryAddrRequest) (*taprpc.QueryAddrResponse, error) {
query := address.QueryParams{
Limit: in.Limit,
Offset: in.Offset,
}
// The unix time of 0 (1970-01-01) is not the same as an empty Time
// struct (0000-00-00). For our query to succeed, we need to set the
// time values the way the address book expects them.
if in.CreatedBefore > 0 {
query.CreatedBefore = time.Unix(in.CreatedBefore, 0)
}
if in.CreatedAfter > 0 {
query.CreatedAfter = time.Unix(in.CreatedAfter, 0)
}
rpcsLog.Debugf("[QueryAddrs]: addr query params: %v",
spew.Sdump(query))
dbAddrs, err := r.cfg.AddrBook.ListAddrs(ctx, query)
if err != nil {
return nil, fmt.Errorf("unable to query addrs: %w", err)
}
// TODO(roasbeef): just stop storing the hrp in the addr?
tapParams := address.ParamsForChain(r.cfg.ChainParams.Name)
addrs := make([]*taprpc.Addr, len(dbAddrs))
for i, dbAddr := range dbAddrs {
dbAddr.ChainParams = &tapParams
addrs[i], err = marshalAddr(dbAddr.Tap, r.cfg.TapAddrBook)
if err != nil {
return nil, fmt.Errorf("unable to marshal addr: %w",
err)
}
}
rpcsLog.Debugf("[QueryAddrs]: returning %v addrs", len(addrs))
return &taprpc.QueryAddrResponse{
Addrs: addrs,
}, nil
}
// NewAddr makes a new address from the set of request params.
func (r *rpcServer) NewAddr(ctx context.Context,
in *taprpc.NewAddrRequest) (*taprpc.Addr, error) {
var err error
if len(in.AssetId) != 32 {
return nil, fmt.Errorf("invalid asset id length")
}
var assetID asset.ID
copy(assetID[:], in.AssetId)
rpcsLog.Infof("[NewAddr]: making new addr: asset_id=%x, amt=%v",
assetID[:], in.Amt)
err = r.checkBalanceOverflow(ctx, &assetID, nil, in.Amt)