-
Notifications
You must be signed in to change notification settings - Fork 111
/
rpcserver.go
7490 lines (6286 loc) · 208 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"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/psbt"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/davecgh/go-spew/spew"
proxy "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/lightninglabs/lndclient"
"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/rfq"
"github.com/lightninglabs/taproot-assets/rfqmath"
"github.com/lightninglabs/taproot-assets/rfqmsg"
"github.com/lightninglabs/taproot-assets/rpcperms"
"github.com/lightninglabs/taproot-assets/tapchannel"
"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/rfqrpc"
tchrpc "github.com/lightninglabs/taproot-assets/taprpc/tapchannelrpc"
"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/tapsend"
"github.com/lightninglabs/taproot-assets/universe"
"github.com/lightningnetwork/lnd/build"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/record"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/signal"
"github.com/lightningnetwork/lnd/tlv"
"github.com/lightningnetwork/lnd/zpay32"
"golang.org/x/exp/maps"
"golang.org/x/time/rate"
"google.golang.org/grpc"
)
var (
// MaxMsgReceiveSize is the largest message our client will receive. We
// set this to 200MiB atm.
MaxMsgReceiveSize = grpc.MaxCallRecvMsgSize(lnrpc.MaxGrpcMsgSize)
// ServerMaxMsgReceiveSize is the largest message our server will
// receive.
ServerMaxMsgReceiveSize = grpc.MaxRecvMsgSize(lnrpc.MaxGrpcMsgSize)
// P2TRChangeType is the type of change address that should be used for
// funding PSBTs, as we'll always want to use P2TR change addresses.
P2TRChangeType = walletrpc.ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR
)
const (
// tapdMacaroonLocation is the value we use for the tapd macaroons'
// "Location" field when baking them.
tapdMacaroonLocation = "tapd"
// AssetBurnConfirmationText is the text that needs to be set on the
// RPC to confirm an asset burn.
AssetBurnConfirmationText = "assets will be destroyed"
// proofTypeSend is an alias for the proof type used for sending assets.
proofTypeSend = tapdevrpc.ProofTransferType_PROOF_TRANSFER_TYPE_SEND
// proofTypeReceive is an alias for the proof type used for receiving
// assets.
proofTypeReceive = tapdevrpc.ProofTransferType_PROOF_TRANSFER_TYPE_RECEIVE
)
type (
// cacheableTimestamp is a wrapper around a uint32 that can be used as a
// value in an LRU cache.
cacheableTimestamp uint32
// devSendEventStream is a type alias for the asset send event
// notification stream.
devSendEventStream = tapdevrpc.TapDev_SubscribeSendAssetEventNtfnsServer
// sendEventStream is a type alias for the asset send event notification
// stream.
sendEventStream = taprpc.TaprootAssets_SubscribeSendEventsServer
// sendBackoff is a type alias for the backoff event that is sent when a
// proof transfer receive process failed and needs to re-try.
sendBackoff = tapdevrpc.SendAssetEvent_ProofTransferBackoffWaitEvent
// sendExecute is a type alias for the complete event that is sent when
// an asset is sent.
sendExecute = tapdevrpc.SendAssetEvent_ExecuteSendStateEvent
// devReceiveEventStream is a type alias for the asset receive event
// notification stream.
devReceiveEventStream = tapdevrpc.TapDev_SubscribeReceiveAssetEventNtfnsServer
// receiveEventStream is a type alias for the asset receive event
// notification stream.
receiveEventStream = taprpc.TaprootAssets_SubscribeReceiveEventsServer
// mintEventStream is a type alias for the asset mint event notification
// stream.
mintEventStream = mintrpc.Mint_SubscribeMintEventsServer
// receiveBackOff is a type alias for the backoff event that is sent
// when a proof transfer process failed and needs to re-try.
receiveBackoff = tapdevrpc.ReceiveAssetEvent_ProofTransferBackoffWaitEvent
// receiveComplete is a type alias for the complete event that is sent
// when an asset is received.
receiveComplete = tapdevrpc.ReceiveAssetEvent_AssetReceiveCompleteEvent
// EventStream is a generic interface type for notification streams.
EventStream[T any] interface {
// Send sends an event object to the notification stream.
Send(T) error
grpc.ServerStream
}
)
// 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
rfqrpc.UnimplementedRfqServer
tchrpc.UnimplementedTaprootAssetChannelsServer
tapdevrpc.UnimplementedTapDevServer
unirpc.UnimplementedUniverseServer
interceptor signal.Interceptor
interceptorChain *rpcperms.InterceptorChain
cfg *Config
proofQueryRateLimiter *rate.Limiter
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,
quit: make(chan struct{}),
proofQueryRateLimiter: rate.NewLimiter(
cfg.UniverseQueriesPerSecond, cfg.UniverseQueriesBurst,
),
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)
rfqrpc.RegisterRfqServer(grpcServer, r)
tchrpc.RegisterTaprootAssetChannelsServer(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 = rfqrpc.RegisterRfqHandlerFromEndpoint(
restCtx, restMux, restProxyDest, restDialOpts,
)
if err != nil {
return err
}
err = tchrpc.RegisterTaprootAssetChannelsHandlerFromEndpoint(
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(ctx context.Context,
_ *taprpc.GetInfoRequest) (*taprpc.GetInfoResponse, error) {
// Retrieve the best block hash and height from the chain backend.
blockHash, blockHeight, err := r.cfg.Lnd.ChainKit.GetBestBlock(ctx)
if err != nil {
return nil, err
}
// Retrieve the current lnd node's info.
info, err := r.cfg.Lnd.Client.GetInfo(context.Background())
if err != nil {
return nil, err
}
return &taprpc.GetInfoResponse{
Version: Version(),
LndVersion: r.cfg.Lnd.Version.Version,
Network: r.cfg.ChainParams.Name,
LndIdentityPubkey: r.cfg.Lnd.NodePubkey.String(),
NodeAlias: info.Alias,
BlockHeight: uint32(blockHeight),
BlockHash: blockHash.String(),
SyncToChain: info.SyncedToChain,
}, 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) {
if req.Asset == nil {
return nil, fmt.Errorf("asset cannot be nil")
}
err := asset.ValidateAssetName(req.Asset.Name)
if err != nil {
return nil, fmt.Errorf("invalid asset name: %w", err)
}
specificGroupKey := len(req.Asset.GroupKey) != 0
specificGroupAnchor := len(req.Asset.GroupAnchor) != 0
specificGroupInternalKey := req.Asset.GroupInternalKey != nil
groupTapscriptRootSize := len(req.Asset.GroupTapscriptRoot)
// A group tapscript root must be 32 bytes.
if groupTapscriptRootSize != 0 &&
groupTapscriptRootSize != sha256.Size {
return nil, fmt.Errorf("group tapscript root must be %d bytes",
sha256.Size)
}
switch {
// New grouped asset and grouped asset cannot both be set.
case req.Asset.NewGroupedAsset && req.Asset.GroupedAsset:
return nil, fmt.Errorf("cannot set both new grouped asset " +
"and grouped asset",
)
// Using a specific group key or anchor implies disabling emission.
case req.Asset.NewGroupedAsset:
if specificGroupKey || specificGroupAnchor {
return nil, fmt.Errorf("must disable emission to " +
"specify a group")
}
// A group tapscript root cannot be specified if emission is disabled.
case !req.Asset.NewGroupedAsset && groupTapscriptRootSize != 0:
return nil, fmt.Errorf("cannot specify a group tapscript root" +
"with emission disabled")
// A group internal key cannot be specified if emission is disabled.
case !req.Asset.NewGroupedAsset && specificGroupInternalKey:
return nil, fmt.Errorf("cannot specify a group internal key" +
"with emission disabled")
// If the asset is intended to be part of an existing group, a group key
// or anchor must be specified, but not both. Neither a group tapscript
// root nor group internal key can be specified.
case req.Asset.GroupedAsset:
if !specificGroupKey && !specificGroupAnchor {
return nil, fmt.Errorf("must specify a group key or" +
"group anchor")
}
if specificGroupKey && specificGroupAnchor {
return nil, fmt.Errorf("cannot specify both a group " +
"key and a group anchor")
}
if groupTapscriptRootSize != 0 {
return nil, fmt.Errorf("cannot specify a group " +
"tapscript root with emission disabled")
}
if specificGroupInternalKey {
return nil, fmt.Errorf("cannot specify a group " +
"internal key with emission disabled")
}
// A group was specified without GroupedAsset being set.
case specificGroupKey || specificGroupAnchor:
return nil, fmt.Errorf("must set grouped asset to mint into " +
"a specific group")
}
assetVersion, err := taprpc.UnmarshalAssetVersion(
req.Asset.AssetVersion,
)
if err != nil {
return nil, err
}
var seedlingMeta *proof.MetaReveal
// If a custom decimal display is set, the meta type must also be set to
// JSON.
if req.Asset.DecimalDisplay != 0 && req.Asset.AssetMeta == nil {
return nil, fmt.Errorf("decimal display requires JSON asset " +
"metadata")
}
if req.Asset.AssetMeta != nil {
// Ensure that the meta type is valid.
metaType, err := proof.IsValidMetaType(req.Asset.AssetMeta.Type)
if err != nil {
return nil, err
}
// If the meta type is not JSON, then a custom decimal display
// cannot be set.
if metaType != proof.MetaJson && req.Asset.DecimalDisplay != 0 {
return nil, fmt.Errorf("cannot set decimal display " +
"if meta type is not JSON")
}
// If the asset meta field was specified, then the data inside
// must be valid. Let's check that now.
seedlingMeta = &proof.MetaReveal{
Data: req.Asset.AssetMeta.Data,
Type: metaType,
}
// If a custom decimal display was requested correctly, but no
// metadata was provided, we'll set the metadata to an empty
// JSON object. The decimal display will be added as the only
// object.
if metaType == proof.MetaJson && req.Asset.DecimalDisplay != 0 {
if len(req.Asset.AssetMeta.Data) == 0 {
seedlingMeta.Data = []byte("{}")
}
}
err = seedlingMeta.Validate()
if err != nil {
return nil, err
}
// If a custom decimal display was requested, add that to the
// metadata and re-validate it.
if metaType == proof.MetaJson && req.Asset.DecimalDisplay != 0 {
updatedMeta, err := seedlingMeta.SetDecDisplay(
req.Asset.DecimalDisplay,
)
if err != nil {
return nil, err
}
seedlingMeta = updatedMeta
err = seedlingMeta.Validate()
if err != nil {
return nil, err
}
}
}
// Parse the optional script key and group internal key. The group
// tapscript root was length-checked above.
var (
scriptKey *asset.ScriptKey
groupInternalKey keychain.KeyDescriptor
groupTapscriptRoot []byte
)
if req.Asset.ScriptKey != nil {
scriptKey, err = taprpc.UnmarshalScriptKey(req.Asset.ScriptKey)
if err != nil {
return nil, err
}
}
if specificGroupInternalKey {
groupInternalKey, err = taprpc.UnmarshalKeyDescriptor(
req.Asset.GroupInternalKey,
)
if err != nil {
return nil, err
}
}
if groupTapscriptRootSize != 0 {
groupTapscriptRoot = bytes.Clone(req.Asset.GroupTapscriptRoot)
}
seedling := &tapgarden.Seedling{
AssetVersion: assetVersion,
AssetType: asset.Type(req.Asset.AssetType),
AssetName: req.Asset.Name,
Amount: req.Asset.Amount,
EnableEmission: req.Asset.NewGroupedAsset,
Meta: seedlingMeta,
}
rpcsLog.Infof("[MintAsset]: version=%v, type=%v, name=%v, amt=%v, "+
"issuance=%v", seedling.AssetVersion, seedling.AssetType,
seedling.AssetName, seedling.Amount, seedling.EnableEmission)
if scriptKey != nil {
seedling.ScriptKey = *scriptKey
}
if specificGroupInternalKey {
seedling.GroupInternalKey = &groupInternalKey
}
if groupTapscriptRootSize != 0 {
seedling.GroupTapscriptRoot = groupTapscriptRoot
}
switch {
// If a group key is provided, parse the provided group public key
// before creating the asset seedling.
case specificGroupKey:
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.
case specificGroupAnchor:
seedling.GroupAnchor = &req.Asset.GroupAnchor
}
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)
}
rpcBatch, err := marshalMintingBatch(
update.PendingBatch, req.ShortResponse,
)
if err != nil {
return nil, err
}
return &mintrpc.MintAssetResponse{
PendingBatch: rpcBatch,
}, nil
}
}
// checkFeeRateSanity ensures that the provided fee rate, in sat/kw, is above
// the same minimum fee used as a floor in the fee estimator.
func checkFeeRateSanity(rpcFeeRate uint32) (*chainfee.SatPerKWeight, error) {
feeFloor := uint32(chainfee.FeePerKwFloor)
switch {
// No manual fee rate was set, which is the default.
case rpcFeeRate == 0:
return nil, nil
// A manual fee was set but is below a reasonable floor.
case rpcFeeRate < feeFloor:
return nil, fmt.Errorf("manual fee rate below floor: "+
"(fee_rate=%d, floor=%d sat/kw)", rpcFeeRate, feeFloor)
// Set the fee rate for this transaction.
default:
return fn.Ptr(chainfee.SatPerKWeight(rpcFeeRate)), nil
}
}
// FundBatch attempts to fund the current pending batch.
func (r *rpcServer) FundBatch(_ context.Context,
req *mintrpc.FundBatchRequest) (*mintrpc.FundBatchResponse, error) {
feeRate, err := checkFeeRateSanity(req.FeeRate)
if err != nil {
return nil, err
}
feeRateOpt := fn.MaybeSome(feeRate)
tapTreeOpt, err := taprpc.UnmarshalTapscriptSibling(
req.GetFullTree(), req.GetBranch(),
)
if err != nil {
return nil, err
}
batch, err := r.cfg.AssetMinter.FundBatch(
tapgarden.FundParams{
FeeRate: feeRateOpt,
SiblingTapTree: tapTreeOpt,
},
)
if err != nil {
return nil, fmt.Errorf("unable to fund batch: %w", err)
}
// If there was no batch to fund, return an empty response.
if batch == nil {
return &mintrpc.FundBatchResponse{}, nil
}
rpcBatch, err := marshalMintingBatch(batch, req.ShortResponse)
if err != nil {
return nil, err
}
return &mintrpc.FundBatchResponse{
Batch: rpcBatch,
}, nil
}
// SealBatch attempts to seal the current pending batch, validating provided
// asset group witnesses and generating asset group witnesses as needed.
func (r *rpcServer) SealBatch(ctx context.Context,
req *mintrpc.SealBatchRequest) (*mintrpc.SealBatchResponse, error) {
var groupWitnesses []asset.PendingGroupWitness
for i := range req.GroupWitnesses {
wit, err := taprpc.UnmarshalGroupWitness(req.GroupWitnesses[i])
if err != nil {
return nil, err
}
groupWitnesses = append(groupWitnesses, *wit)
}
batch, err := r.cfg.AssetMinter.SealBatch(
tapgarden.SealParams{
GroupWitnesses: groupWitnesses,
},
)
if err != nil {
return nil, err
}
rpcBatch, err := marshalMintingBatch(batch, req.ShortResponse)
if err != nil {
return nil, err
}
return &mintrpc.SealBatchResponse{
Batch: rpcBatch,
}, nil
}
// FinalizeBatch attempts to finalize the current pending batch.
func (r *rpcServer) FinalizeBatch(_ context.Context,
req *mintrpc.FinalizeBatchRequest) (*mintrpc.FinalizeBatchResponse,
error) {
feeRate, err := checkFeeRateSanity(req.FeeRate)
if err != nil {
return nil, err
}
feeRateOpt := fn.MaybeSome(feeRate)
tapTreeOpt, err := taprpc.UnmarshalTapscriptSibling(
req.GetFullTree(), req.GetBranch(),
)
if err != nil {
return nil, err
}
batch, err := r.cfg.AssetMinter.FinalizeBatch(
tapgarden.FinalizeParams{
FeeRate: feeRateOpt,
SiblingTapTree: tapTreeOpt,
},
)
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 batch == nil {
return &mintrpc.FinalizeBatchResponse{}, nil
}
rpcBatch, err := marshalMintingBatch(batch, req.ShortResponse)
if err != nil {
return nil, err
}
return &mintrpc.FinalizeBatchResponse{
Batch: rpcBatch,
}, 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(
tapgarden.ListBatchesParams{
BatchKey: batchKey,
Verbose: req.Verbose,
},
)
if err != nil {
return nil, fmt.Errorf("unable to list batches: %w", err)
}
rpcBatches, err := fn.MapErr(
batches, func(b *tapgarden.VerboseBatch) (*mintrpc.VerboseBatch,
error) {
return marshalVerboseBatch(b, req.Verbose, false)
},
)
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, true,
)
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, true,
)
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) {
if 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
}
var (
filteredAssets []*taprpc.Asset
unconfirmedMints uint64
)
// We now count and filter the assets according to the
// IncludeUnconfirmedMints flag.
//
// TODO(guggero): Do this on the SQL level once we add pagination to the
// asset list query, as this will no longer work with pagination.
for idx := range rpcAssets {
switch {
// If the asset isn't confirmed yet, we count it but only
// include it in the output list if the client requested it.
case rpcAssets[idx].ChainAnchor.BlockHeight == 0:
unconfirmedMints++
if req.IncludeUnconfirmedMints {
filteredAssets = append(
filteredAssets, rpcAssets[idx],
)
}
// Don't filter out confirmed assets.
default:
filteredAssets = append(
filteredAssets, rpcAssets[idx],
)
}
}