-
Notifications
You must be signed in to change notification settings - Fork 119
/
planter.go
2158 lines (1816 loc) · 60.9 KB
/
planter.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 tapgarden
import (
"bytes"
"context"
"errors"
"fmt"
"slices"
"sync"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil/psbt"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew"
"github.com/lightninglabs/taproot-assets/asset"
"github.com/lightninglabs/taproot-assets/fn"
"github.com/lightninglabs/taproot-assets/proof"
"github.com/lightninglabs/taproot-assets/tapscript"
"github.com/lightninglabs/taproot-assets/tapsend"
"github.com/lightninglabs/taproot-assets/universe"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"golang.org/x/exp/maps"
)
// GardenKit holds the set of shared fundamental interfaces all sub-systems of
// the tapgarden need to function.
type GardenKit struct {
// Wallet is an active on chain wallet for the target chain.
Wallet WalletAnchor
// ChainBridge provides access to the chain for confirmation
// notification, and other block related actions.
ChainBridge ChainBridge
// Log stores the current state of any active batch, throughout the
// various states the planter will progress it through.
Log MintingStore
// TreeStore provides access to optional tapscript trees used with
// script keys, minting output keys, and group keys.
TreeStore asset.TapscriptTreeManager
// KeyRing is used for obtaining internal keys for the anchor
// transaction, as well as script keys for each asset and group keys
// for assets created that permit ongoing emission.
KeyRing KeyRing
// GenSigner is used to generate signatures for the key group tweaked
// by the genesis point when creating assets that permit on going
// emission.
GenSigner asset.GenesisSigner
// GenTxBuilder is used to create virtual transactions for the group
// witness generation process.
GenTxBuilder asset.GenesisTxBuilder
// TxValidator is used to validate group witnesses when creating assets
// that support reissuance.
TxValidator tapscript.TxValidator
// ProofFiles stores the set of flat proof files.
ProofFiles proof.Archiver
// Universe is used to register new asset issuance with a local/remote
// base universe instance.
Universe universe.BatchRegistrar
// ProofWatcher is used to watch new proofs for their anchor transaction
// to be confirmed safely with a minimum number of confirmations.
ProofWatcher proof.Watcher
// UniversePushBatchSize is the number of minted items to push to the
// local universe in a single batch.
UniversePushBatchSize int
}
// PlanterConfig is the main config for the ChainPlanter.
type PlanterConfig struct {
GardenKit
// ProofUpdates is the storage backend for updated proofs.
ProofUpdates proof.Archiver
// ErrChan is the main error channel the planter will report back
// critical errors to the main server.
ErrChan chan<- error
// TODO(roasbeef): something notification related?
}
// BatchKey is a type alias for a serialized public key.
type BatchKey = asset.SerializedKey
// CancelResp is the response from a caretaker attempting to cancel a batch.
type CancelResp struct {
cancelAttempted bool
err error
}
type stateRequest interface {
Resolve(any)
Error(error)
Return(any, error)
Type() reqType
Param() any
}
type stateReq[T any] struct {
resp chan T
err chan error
reqType reqType
}
func newStateReq[T any](req reqType) *stateReq[T] {
return &stateReq[T]{
resp: make(chan T, 1),
err: make(chan error, 1),
reqType: req,
}
}
type stateParamReq[T, S any] struct {
stateReq[T]
param S
}
// ListBatchesParams are the options available to specify which minting batches
// are listed, and how verbose the listing should be.
type ListBatchesParams struct {
BatchKey *btcec.PublicKey
Verbose bool
}
// PendingAssetGroup is the group key request and virtual TX necessary to
// produce an asset group witness for a seedling.
type PendingAssetGroup struct {
asset.GroupKeyRequest
asset.GroupVirtualTx
}
// UnsealedSeedling is a previously submitted seedling and its associated
// PendingAssetGroup, which can be used to produce an asset group witness.
type UnsealedSeedling struct {
*Seedling
*PendingAssetGroup
}
// FinalizeParams are the options available to change how a batch is finalized,
// and how the genesis TX is constructed.
type FinalizeParams struct {
FeeRate fn.Option[chainfee.SatPerKWeight]
SiblingTapTree fn.Option[asset.TapscriptTreeNodes]
}
// FundParams are the options available to change how a batch is funded, and how
// the genesis TX is constructed.
type FundParams struct {
FeeRate fn.Option[chainfee.SatPerKWeight]
SiblingTapTree fn.Option[asset.TapscriptTreeNodes]
}
// SealParams change how asset groups in a minting batch are created.
type SealParams struct {
GroupWitnesses []asset.PendingGroupWitness
}
func newStateParamReq[T, S any](req reqType, param S) *stateParamReq[T, S] {
return &stateParamReq[T, S]{
stateReq: *newStateReq[T](req),
param: param,
}
}
func (s *stateReq[T]) Resolve(resp any) {
s.resp <- resp.(T)
close(s.err)
}
func (s *stateReq[T]) Error(err error) {
s.err <- err
close(s.resp)
}
func (s *stateReq[T]) Return(resp any, err error) {
s.resp <- resp.(T)
s.err <- err
}
func (s *stateReq[T]) Type() reqType {
return s.reqType
}
func (s *stateReq[T]) Param() any {
return nil
}
func (s *stateParamReq[T, S]) Param() any {
return s.param
}
func typedParam[T any](req stateRequest) (*T, error) {
if param, ok := req.Param().(T); ok {
return ¶m, nil
}
return nil, fmt.Errorf("invalid type")
}
type reqType uint8
const (
reqTypePendingBatch = iota
reqTypeNumActiveBatches
reqTypeListBatches
reqTypeFinalizeBatch
reqTypeCancelBatch
reqTypeFundBatch
reqTypeSealBatch
)
// ChainPlanter is responsible for accepting new incoming requests to create
// taproot assets. The planter will periodically batch those requests into a new
// minting batch, which is handed off to a caretaker. While batches are
// progressing through maturity the planter will be responsible for sending
// notifications back to the relevant caller.
type ChainPlanter struct {
startOnce sync.Once
stopOnce sync.Once
cfg PlanterConfig
// seedlingReqs is used to accept new asset issuance requests.
seedlingReqs chan *Seedling
// pendingBatch is the current pending, non-frozen batch. Only one of
// these will exist at any given time.
pendingBatch *MintingBatch
// caretakers maps a batch key (which is used as the internal key for
// the transaction that mints the assets) to the caretaker that will
// progress the batch through the final phases.
caretakers map[BatchKey]*BatchCaretaker
// completionSignals is a channel used to allow the caretakers to
// signal that the batch is fully final, allowing garbage collection of
// any relevant resources.
completionSignals chan BatchKey
// stateReqs is the channel that any outside requests for the state of
// the planter will come across.
stateReqs chan stateRequest
// subscribers is a map of components that want to be notified on new
// events, keyed by their subscription ID.
subscribers map[uint64]*fn.EventReceiver[fn.Event]
// subscriberMtx guards the subscribers map.
subscriberMtx sync.Mutex
// ContextGuard provides a wait group and main quit channel that can be
// used to create guarded contexts.
*fn.ContextGuard
}
// NewChainPlanter creates a new ChainPlanter instance given the passed config.
func NewChainPlanter(cfg PlanterConfig) *ChainPlanter {
return &ChainPlanter{
cfg: cfg,
caretakers: make(map[BatchKey]*BatchCaretaker),
completionSignals: make(chan BatchKey),
seedlingReqs: make(chan *Seedling),
stateReqs: make(chan stateRequest),
subscribers: make(map[uint64]*fn.EventReceiver[fn.Event]),
ContextGuard: &fn.ContextGuard{
DefaultTimeout: DefaultTimeout,
Quit: make(chan struct{}),
},
}
}
// newCaretakerForBatch creates a new BatchCaretaker for a given batch and
// inserts it into the caretaker map.
func (c *ChainPlanter) newCaretakerForBatch(batch *MintingBatch,
feeRate *chainfee.SatPerKWeight) *BatchCaretaker {
batchKey := asset.ToSerialized(batch.BatchKey.PubKey)
batchConfig := &BatchCaretakerConfig{
Batch: batch,
GardenKit: c.cfg.GardenKit,
BroadcastCompleteChan: make(chan struct{}, 1),
BroadcastErrChan: make(chan error, 1),
SignalCompletion: func() {
c.completionSignals <- batchKey
},
CancelReqChan: make(chan struct{}, 1),
CancelRespChan: make(chan CancelResp, 1),
UpdateMintingProofs: c.updateMintingProofs,
PublishMintEvent: c.publishSubscriberEvent,
ErrChan: c.cfg.ErrChan,
}
if feeRate != nil {
batchConfig.BatchFeeRate = feeRate
}
caretaker := NewBatchCaretaker(batchConfig)
c.caretakers[batchKey] = caretaker
return caretaker
}
// Start starts the ChainPlanter and any goroutines it needs to carry out its
// duty.
func (c *ChainPlanter) Start() error {
var startErr error
c.startOnce.Do(func() {
log.Infof("Starting ChainPlanter")
// First, we'll read out any minting batches that aren't yet
// fully finalized (minting transaction well confirmed on
// chain). This includes batches that were still pending before
// our last restart, so were never frozen in the first place.
// The caretaker will handle progressing the batch to the
// frozen state, and beyond.
//
// TODO(roasbeef): instead do RBF here? so only a single
// pending batch at a time? but would end up changing assetIDs.
ctx, cancel := c.WithCtxQuit()
defer cancel()
nonFinalBatches, err := c.cfg.Log.FetchNonFinalBatches(ctx)
if err != nil {
startErr = err
return
}
log.Infof("Retrieved %v non-finalized batches from DB",
len(nonFinalBatches))
// Now for each of these non-final batches, we'll make a new
// caretaker which'll handle progressing each batch to
// completion. We'll skip batches that were cancelled.
for _, batch := range nonFinalBatches {
batchState := batch.State()
batchKey := batch.BatchKey.PubKey.SerializeCompressed()
if batchState == BatchStateSeedlingCancelled ||
batchState == BatchStateSproutCancelled {
continue
}
// For batches before the actual assets have been
// committed, we'll need to populate this field
// manually.
if batch.AssetMetas == nil {
batch.AssetMetas = make(AssetMetas)
}
// If batch funding or sealing fail during startup, the
// batch will be marked as cancelled. The batch can
// still be displayed by the planter, and can be
// resubmitted manually.
cancelBatch := func() {
log.Warnf("Marking batch as cancelled (%x)",
batchKey)
err := c.cfg.Log.UpdateBatchState(
ctx, batch.BatchKey.PubKey,
BatchStateSeedlingCancelled,
)
// If updating the batch state fails, the batch
// will still be skipped on this startup; we can
// continue without passing the error further.
if err != nil {
log.Warnf("Unable to cancel batch (%x)",
batchKey)
}
}
// TODO(jhb): Log manual fee rates?
// If the batch was still pending, or if batch
// finalization was interrupted, it may need to be
// funded or sealed before being assigned a caretaker.
// A batch that was already properly frozen at this
// point should not be modified before being assigned a
// caretaker.
if batchState == BatchStatePending ||
batchState == BatchStateFrozen {
var (
fundErr error
sealErr error
)
if !batch.IsFunded() {
log.Infof("Funding non-finalized "+
"batch from DB (%x)", batchKey)
fundErr = c.fundBatch(
ctx, FundParams{}, batch,
)
}
if fundErr != nil {
log.Warnf("Failed to fund batch from "+
"DB (%x): %s",
batchKey, fundErr.Error())
cancelBatch()
continue
}
log.Infof("Sealing non-finalized batch from "+
"DB (%x)", batchKey)
_, sealErr = c.sealBatch(
ctx, SealParams{}, batch,
)
if sealErr != nil {
if !errors.Is(
sealErr, ErrBatchAlreadySealed,
) {
log.Warnf("Failed to seal "+
"batch from DB (%x): "+
"%s", batchKey,
sealErr.Error())
cancelBatch()
continue
}
}
// Any pending batch that was funded and sealed
// can now be set as frozen. We are already not
// able to add new seedlings to the batch.
batch.UpdateState(BatchStateFrozen)
}
log.Infof("Launching ChainCaretaker(%x)", batchKey)
caretaker := c.newCaretakerForBatch(batch, nil)
if err := caretaker.Start(); err != nil {
startErr = err
return
}
}
// With all the caretakers for each minting batch launched,
// we'll start up the main gardener goroutine so we can accept
// new minting requests.
c.Wg.Add(1)
go c.gardener()
})
return startErr
}
// Stop signals the ChainPlanter to halt all operations gracefully.
func (c *ChainPlanter) Stop() error {
var stopErr error
c.stopOnce.Do(func() {
log.Infof("Stopping ChainPlanter")
close(c.Quit)
c.Wg.Wait()
// Remove all subscribers.
c.subscriberMtx.Lock()
defer c.subscriberMtx.Unlock()
for _, subscriber := range c.subscribers {
subscriber.Stop()
delete(c.subscribers, subscriber.ID())
}
})
return stopErr
}
// stopCaretakers attempts to gracefully stop all the active caretakers.
func (c *ChainPlanter) stopCaretakers() {
for batchKey, caretaker := range c.caretakers {
log.Debugf("Stopping ChainCaretaker(%x)", batchKey[:])
if err := caretaker.Stop(); err != nil {
// TODO(roasbeef): continue and stop the rest
// of them?
log.Warnf("Unable to stop ChainCaretaker(%x)",
batchKey[:])
return
}
}
}
// newBatch creates a new minting batch, which includes deriving a new internal
// key. The batch is not written to disk nor set as the pending batch.
func (c *ChainPlanter) newBatch() (*MintingBatch, error) {
ctx, cancel := c.WithCtxQuit()
defer cancel()
// To create a new batch we'll first need to grab a new internal key,
// which will be used in the output we create, and also will serve as
// the primary identifier for a batch.
log.Infof("Creating new MintingBatch")
newInternalKey, err := c.cfg.KeyRing.DeriveNextKey(
ctx, asset.TaprootAssetsKeyFamily,
)
if err != nil {
return nil, err
}
currentHeight, err := c.cfg.ChainBridge.CurrentHeight(ctx)
if err != nil {
return nil, fmt.Errorf("unable to get current height: %w", err)
}
// Create the new batch.
newBatch := &MintingBatch{
CreationTime: time.Now(),
HeightHint: currentHeight,
BatchKey: newInternalKey,
Seedlings: make(map[string]*Seedling),
AssetMetas: make(AssetMetas),
}
newBatch.UpdateState(BatchStatePending)
return newBatch, nil
}
// fundGenesisPsbt generates a PSBT packet we'll use to create an asset. In
// order to be able to create an asset, we need an initial genesis outpoint. To
// obtain this we'll ask the wallet to fund a PSBT template for GenesisAmtSats
// (all outputs need to hold some BTC to not be dust), and with a dummy script.
// We need to use a dummy script as we can't know the actual script key since
// that's dependent on the genesis outpoint.
func (c *ChainPlanter) fundGenesisPsbt(ctx context.Context,
batchKey asset.SerializedKey,
manualFeeRate *chainfee.SatPerKWeight) (*tapsend.FundedPsbt, error) {
log.Infof("Attempting to fund batch: %x", batchKey)
// Construct a 1-output TX as a template for our genesis TX, which the
// backing wallet will fund.
txTemplate := wire.NewMsgTx(2)
txTemplate.AddTxOut(tapsend.CreateDummyOutput())
genesisPkt, err := psbt.NewFromUnsignedTx(txTemplate)
if err != nil {
return nil, fmt.Errorf("unable to make psbt packet: %w", err)
}
log.Infof("creating skeleton PSBT for batch: %x", batchKey)
log.Tracef("PSBT: %v", spew.Sdump(genesisPkt))
var feeRate chainfee.SatPerKWeight
switch {
// If a fee rate was manually assigned for this batch, use that instead
// of a fee rate estimate.
case manualFeeRate != nil:
feeRate = *manualFeeRate
log.Infof("using manual fee rate for batch: %x, %s, %d sat/vB",
batchKey[:], feeRate.String(),
feeRate.FeePerKVByte()/1000)
default:
feeRate, err = c.cfg.ChainBridge.EstimateFee(
ctx, GenesisConfTarget,
)
if err != nil {
return nil, fmt.Errorf("unable to estimate fee: %w",
err)
}
log.Infof("estimated fee rate for batch: %x, %s",
batchKey[:], feeRate.FeePerKVByte().String())
}
fundedGenesisPkt, err := c.cfg.Wallet.FundPsbt(
ctx, genesisPkt, 1, feeRate, -1,
)
if err != nil {
return nil, fmt.Errorf("unable to fund psbt: %w", err)
}
log.Infof("Funded GenesisPacket for batch: %x", batchKey)
log.Tracef("GenesisPacket: %v", spew.Sdump(fundedGenesisPkt))
return fundedGenesisPkt, nil
}
// filterSeedlingsWithGroup separates a set of seedlings into two sets based on
// their relation to an asset group, which has not been constructed yet.
func filterSeedlingsWithGroup(
seedlings map[string]*Seedling) (map[string]*Seedling,
map[string]*Seedling) {
withGroup := make(map[string]*Seedling)
withoutGroup := make(map[string]*Seedling)
fn.ForEachMapItem(seedlings, func(name string, seedling *Seedling) {
switch {
case seedling.GroupInfo != nil || seedling.GroupAnchor != nil ||
seedling.EnableEmission:
withGroup[name] = seedling
default:
withoutGroup[name] = seedling
}
})
return withGroup, withoutGroup
}
// buildGroupReqs creates group key requests and asset group genesis TXs for
// seedlings that are part of a funded batch.
func buildGroupReqs(genesisPoint wire.OutPoint, assetOutputIndex uint32,
genBuilder asset.GenesisTxBuilder,
groupSeedlings map[string]*Seedling) ([]asset.GroupKeyRequest,
[]asset.GroupVirtualTx, error) {
// Seedlings that anchor a group may be referenced by other seedlings,
// and therefore need to be mapped to sprouts first so that we derive
// the initial tweaked group key early.
orderedSeedlings := SortSeedlings(maps.Values(groupSeedlings))
newGroups := make(map[string]*asset.AssetGroup)
groupReqs := make([]asset.GroupKeyRequest, 0, len(orderedSeedlings))
genTXs := make([]asset.GroupVirtualTx, 0, len(orderedSeedlings))
for _, seedlingName := range orderedSeedlings {
seedling := groupSeedlings[seedlingName]
assetGen := seedling.Genesis(genesisPoint, assetOutputIndex)
// If the seedling has a meta data reveal set, then we'll bind
// that by including the hash of the meta data in the asset
// genesis.
if seedling.Meta != nil {
assetGen.MetaHash = seedling.Meta.MetaHash()
}
var (
amount uint64
groupInfo *asset.AssetGroup
protoAsset *asset.Asset
err error
)
// Determine the amount for the actual asset.
switch seedling.AssetType {
case asset.Normal:
amount = seedling.Amount
case asset.Collectible:
amount = 1
}
// If the seedling has a group key specified,
// that group key was validated earlier. We need to
// sign the new genesis with that group key.
if seedling.HasGroupKey() {
groupInfo = seedling.GroupInfo
}
// If the seedling has a group anchor specified, that anchor
// was validated earlier and the corresponding group has already
// been created. We need to look up the group key and sign
// the asset genesis with that key.
if seedling.GroupAnchor != nil {
groupInfo = newGroups[*seedling.GroupAnchor]
}
// If a group witness needs to be produced, then we will need a
// partially filled asset as part of the signing process.
if groupInfo != nil || seedling.EnableEmission {
protoAsset, err = asset.New(
assetGen, amount, 0, 0, seedling.ScriptKey,
nil,
asset.WithAssetVersion(seedling.AssetVersion),
)
if err != nil {
return nil, nil, fmt.Errorf("unable to create "+
"asset for group key signing: %w", err)
}
}
if groupInfo != nil {
groupReq, err := asset.NewGroupKeyRequest(
groupInfo.GroupKey.RawKey, *groupInfo.Genesis,
protoAsset, groupInfo.GroupKey.TapscriptRoot,
)
if err != nil {
return nil, nil, fmt.Errorf("unable to "+
"request asset group membership: %w",
err)
}
genTx, err := groupReq.BuildGroupVirtualTx(
genBuilder,
)
if err != nil {
return nil, nil, err
}
groupReqs = append(groupReqs, *groupReq)
genTXs = append(genTXs, *genTx)
}
// If emission is enabled, an internal key for the group should
// already be specified. Use that to derive the key group
// signature along with the tweaked key group.
if seedling.EnableEmission {
if seedling.GroupInternalKey == nil {
return nil, nil, fmt.Errorf("unable to " +
"derive group key")
}
groupReq, err := asset.NewGroupKeyRequest(
*seedling.GroupInternalKey, assetGen,
protoAsset, seedling.GroupTapscriptRoot,
)
if err != nil {
return nil, nil, fmt.Errorf("unable to "+
"request asset group creation: %w", err)
}
genTx, err := groupReq.BuildGroupVirtualTx(
genBuilder,
)
if err != nil {
return nil, nil, err
}
groupReqs = append(groupReqs, *groupReq)
genTXs = append(genTXs, *genTx)
newGroupKey := &asset.GroupKey{
RawKey: *seedling.GroupInternalKey,
TapscriptRoot: seedling.GroupTapscriptRoot,
}
newGroups[seedlingName] = &asset.AssetGroup{
Genesis: &assetGen,
GroupKey: newGroupKey,
}
}
}
return groupReqs, genTXs, nil
}
// freezeMintingBatch freezes a target minting batch which means that no new
// assets can be added to the batch.
func freezeMintingBatch(ctx context.Context, batchStore MintingStore,
batch *MintingBatch) error {
batchKey := batch.BatchKey.PubKey
log.Infof("Freezing MintingBatch(key=%x, num_assets=%v)",
batchKey.SerializeCompressed(), len(batch.Seedlings))
// In order to freeze a batch, we need to update the state of the batch
// to BatchStateFrozen, meaning that no other changes can happen.
//
// TODO(roasbeef): assert not in some other state first?
return batchStore.UpdateBatchState(
ctx, batchKey, BatchStateFrozen,
)
}
// filterFinalizedBatches separates a set of batches into two sets based on
// their batch state.
func filterFinalizedBatches(batches []*MintingBatch) ([]*MintingBatch,
[]*MintingBatch) {
finalized := []*MintingBatch{}
nonFinalized := []*MintingBatch{}
fn.ForEach(batches, func(batch *MintingBatch) {
switch batch.State() {
case BatchStateFinalized:
finalized = append(finalized, batch)
default:
nonFinalized = append(nonFinalized, batch)
}
})
return finalized, nonFinalized
}
// fetchFinalizedBatch fetches the assets of a batch in their genesis state,
// given a batch populated with seedlings.
func fetchFinalizedBatch(ctx context.Context, batchStore MintingStore,
archiver proof.Archiver, batch *MintingBatch) (*MintingBatch, error) {
// Collect genesis TX information from the batch to build the proof
// locators.
anchorOutputIndex := extractAnchorOutputIndex(batch.GenesisPacket)
signedTx, err := psbt.Extract(batch.GenesisPacket.Pkt)
if err != nil {
return nil, err
}
genOutpoint := extractGenesisOutpoint(signedTx)
genScript := signedTx.TxOut[anchorOutputIndex].PkScript
anchorOutpoint := wire.OutPoint{
Hash: signedTx.TxHash(),
Index: anchorOutputIndex,
}
batchAssets := make([]*asset.Asset, 0, len(batch.Seedlings))
assetMetas := make(AssetMetas)
for _, seedling := range batch.Seedlings {
gen := seedling.Genesis(genOutpoint, anchorOutputIndex)
issuanceProof, err := archiver.FetchIssuanceProof(
ctx, gen.ID(), anchorOutpoint,
)
if err != nil {
return nil, err
}
proofFile, err := issuanceProof.AsFile()
if err != nil {
return nil, err
}
if proofFile.NumProofs() != 1 {
return nil, fmt.Errorf("expected single proof for " +
"issuance proof")
}
rawProof, err := proofFile.RawLastProof()
if err != nil {
return nil, err
}
// Decode the sprouted asset from the issuance proof.
var sproutedAsset asset.Asset
assetRecord := proof.AssetLeafRecord(&sproutedAsset)
err = proof.SparseDecode(bytes.NewReader(rawProof), assetRecord)
if err != nil {
return nil, fmt.Errorf("unable to decode issuance "+
"proof: %w", err)
}
if !sproutedAsset.IsGenesisAsset() {
return nil, fmt.Errorf("decoded asset is not a " +
"genesis asset")
}
// Populate the key info for the script key and group key.
if sproutedAsset.ScriptKey.PubKey == nil {
return nil, fmt.Errorf("decoded asset is missing " +
"script key")
}
tweakedScriptKey, err := batchStore.FetchScriptKeyByTweakedKey(
ctx, sproutedAsset.ScriptKey.PubKey,
)
if err != nil {
return nil, err
}
sproutedAsset.ScriptKey.TweakedScriptKey = tweakedScriptKey
if sproutedAsset.GroupKey != nil {
assetGroup, err := batchStore.FetchGroupByGroupKey(
ctx, &sproutedAsset.GroupKey.GroupPubKey,
)
if err != nil {
return nil, err
}
sproutedAsset.GroupKey = assetGroup.GroupKey
}
batchAssets = append(batchAssets, &sproutedAsset)
scriptKey := asset.ToSerialized(sproutedAsset.ScriptKey.PubKey)
assetMetas[scriptKey] = seedling.Meta
}
// Verify that we can reconstruct the genesis output script used in the
// anchor TX.
batchSibling := batch.TapSibling()
var tapSibling *chainhash.Hash
if len(batchSibling) != 0 {
var err error
tapSibling, err = chainhash.NewHash(batchSibling)
if err != nil {
return nil, err
}
}
tapCommitment, err := VerifyOutputScript(
batch.BatchKey.PubKey, tapSibling, genScript, batchAssets,
)
if err != nil {
return nil, err
}
// With the batch assets validated, construct the populated finalized
// batch.
batch.Seedlings = nil
finalizedBatch := batch.Copy()
finalizedBatch.RootAssetCommitment = tapCommitment
finalizedBatch.AssetMetas = assetMetas
return finalizedBatch, nil
}
// ListBatches returns the single batch specified by the batch key, or the set
// of batches not yet finalized on disk.
func listBatches(ctx context.Context, batchStore MintingStore,
archiver proof.Archiver, genBuilder asset.GenesisTxBuilder,
params ListBatchesParams) ([]*VerboseBatch, error) {
var (
batches []*MintingBatch
err error
)
switch {
case params.BatchKey == nil:
batches, err = batchStore.FetchAllBatches(ctx)
default:
var batch *MintingBatch
batch, err = batchStore.FetchMintingBatch(ctx, params.BatchKey)
batches = []*MintingBatch{batch}
}
if err != nil {
return nil, err
}
var (
finalBatches, nonFinalBatches = filterFinalizedBatches(batches)
verboseBatches []*VerboseBatch
)
switch {
case len(finalBatches) == 0:
verboseBatches = fn.Map(batches,
func(b *MintingBatch) *VerboseBatch {
return &VerboseBatch{
MintingBatch: b,
UnsealedSeedlings: nil,
}
},
)
// For finalized batches, we need to fetch the assets from the proof
// archiver, not the DB.
default:
finalizedBatches := make([]*MintingBatch, 0, len(finalBatches))
for _, batch := range finalBatches {
finalizedBatch, err := fetchFinalizedBatch(
ctx, batchStore, archiver, batch,
)
if err != nil {
return nil, err
}
finalizedBatches = append(
finalizedBatches, finalizedBatch,
)
}
// Re-sort the batches by creation time for consistent display.
allBatches := append(nonFinalBatches, finalizedBatches...)
slices.SortFunc(allBatches, func(a, b *MintingBatch) int {
return a.CreationTime.Compare(b.CreationTime)
})
verboseBatches = fn.Map(allBatches,
func(b *MintingBatch) *VerboseBatch {
return &VerboseBatch{
MintingBatch: b,
UnsealedSeedlings: nil,
}
},
)
}
// Return the batches without any extra asset group info.
if !params.Verbose {
return verboseBatches, nil
}
for _, batch := range verboseBatches {
currentBatch := batch
// The batch must be pending, funded, and have seedlings for us
// to show pending asset group information.
switch {
case currentBatch.State() != BatchStatePending:
continue
case !currentBatch.IsFunded():
continue
case len(currentBatch.Seedlings) == 0:
continue
default:
}
// Filter the batch seedlings to only consider those that will
// become grouped assets. If there are no such seedlings, then
// there is no extra information to show.
groupSeedlings, _ := filterSeedlingsWithGroup(
currentBatch.Seedlings,