-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathrequest.go
More file actions
1729 lines (1536 loc) · 58.9 KB
/
Copy pathrequest.go
File metadata and controls
1729 lines (1536 loc) · 58.9 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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package token provides the Request type for building and managing token transactions.
// A Request assembles token actions (issue, transfer, redeem) and their metadata,
// handles serialization, validation, and signature collection. It supports both
// fungible and non-fungible tokens with privacy-preserving features.
package token
import (
"context"
"maps"
"slices"
"github.com/LFDT-Panurus/panurus/token/core/common/meta"
"github.com/LFDT-Panurus/panurus/token/driver"
"github.com/LFDT-Panurus/panurus/token/driver/protos-go/v1/request"
"github.com/LFDT-Panurus/panurus/token/services/utils"
"github.com/LFDT-Panurus/panurus/token/token"
"github.com/hyperledger-labs/fabric-smart-client/pkg/utils/errors"
"github.com/hyperledger-labs/fabric-smart-client/pkg/utils/proto"
"github.com/hyperledger-labs/fabric-smart-client/platform/common/services/logging"
"go.uber.org/zap/zapcore"
)
const (
// TransferMetadataPrefix is the prefix for the metadata of a transfer action
TransferMetadataPrefix = meta.TransferMetadataPrefix
// IssueMetadataPrefix is the prefix for the metadata of an issue action
IssueMetadataPrefix = meta.IssueMetadataPrefix
// PublicMetadataPrefix is the prefix for the metadata that will be published on the ledger without further validation
PublicMetadataPrefix = meta.PublicMetadataPrefix
)
// ActionMetadata models the action metadata as a map from string to byte array
type ActionMetadata = map[string][]byte
// Binder binds ephemeral identities to long-term identities for privacy-preserving transactions.
type Binder interface {
Bind(ctx context.Context, longTerm Identity, ephemeral ...Identity) error
}
type (
// TokensUpgradeChallenge is the challenge the issuer generates to make sure the client is not cheating
TokensUpgradeChallenge = driver.TokensUpgradeChallenge
// TokensUpgradeProof is the proof generated with the respect to a given challenge to prove the validity of the tokens to be upgrade
TokensUpgradeProof = driver.TokensUpgradeProof
// RequestAnchor models the anchor of a token request
RequestAnchor = driver.TokenRequestAnchor
)
// RecipientData contains information about the identity of a token owner
type RecipientData = driver.RecipientData
// IssueOptions contains optional parameters for token issuance operations.
type IssueOptions struct {
// Attributes is a container of generic options that might be driver specific
Attributes map[string]any
}
// compileIssueOptions aggregates multiple IssueOption functions into a single IssueOptions struct.
func compileIssueOptions(opts ...IssueOption) (*IssueOptions, error) {
txOptions := &IssueOptions{}
for _, opt := range opts {
if err := opt(txOptions); err != nil {
return nil, err
}
}
return txOptions, nil
}
// IssueOption is a function that modifies IssueOptions.
type IssueOption func(*IssueOptions) error
// WithIssueAttribute adds a custom attribute to an issue operation.
func WithIssueAttribute(attr string, value any) IssueOption {
return func(o *IssueOptions) error {
if o.Attributes == nil {
o.Attributes = map[string]any{}
}
o.Attributes[attr] = value
return nil
}
}
// WithIssueMetadata adds metadata to an issue action (automatically prefixed).
func WithIssueMetadata(key string, value []byte) IssueOption {
return WithIssueAttribute(IssueMetadataPrefix+key, value)
}
// TransferOptions contains optional parameters for token transfer operations.
type TransferOptions struct {
// Attributes is a container of generic options that might be driver specific
Attributes map[string]any
// Selector is the custom token selector to use. If nil, the default will be used.
Selector Selector
// TokenIDs to transfer. If empty, the tokens will be selected.
TokenIDs []*token.ID
// RestRecipientIdentity is the recipient to which the transfer's leftover (change) amount is
// assigned when the selected inputs exceed the requested output sum. If nil, the change is
// assigned to the sender wallet's default recipient identity. Set via WithRestRecipientIdentity.
RestRecipientIdentity *RecipientData
}
// CompileTransferOptions aggregates multiple TransferOption functions into a single TransferOptions struct.
func CompileTransferOptions(opts ...TransferOption) (*TransferOptions, error) {
txOptions := &TransferOptions{}
for _, opt := range opts {
if err := opt(txOptions); err != nil {
return nil, err
}
}
return txOptions, nil
}
// TransferOption is a function that modifies TransferOptions.
type TransferOption func(*TransferOptions) error
// WithTokenSelector sets the passed token selector
func WithTokenSelector(selector Selector) TransferOption {
return func(o *TransferOptions) error {
o.Selector = selector
return nil
}
}
// WithTransferMetadata adds metadata to a transfer action (automatically prefixed).
func WithTransferMetadata(key string, value []byte) TransferOption {
return WithTransferAttribute(TransferMetadataPrefix+key, value)
}
// WithPublicTransferMetadata adds any data to the public ledger that may be relevant to the application.
// It is also made available to the participants as part of the TransactionRecord.
// The transaction fails if the key already exists on the ledger. The value is not validated.
func WithPublicTransferMetadata(key string, value []byte) TransferOption {
return WithTransferMetadata(PublicMetadataPrefix+key, value)
}
// WithPublicIssueMetadata adds any data to the public ledger that may be relevant to the application.
// It is also made available to the participants as part of the TransactionRecord.
// The transaction fails if the key already exists on the ledger. The value is not validated.
func WithPublicIssueMetadata(key string, value []byte) IssueOption {
return WithIssueMetadata(PublicMetadataPrefix+key, value)
}
// WithTokenIDs sets the tokens ids to transfer
func WithTokenIDs(ids ...*token.ID) TransferOption {
return func(o *TransferOptions) error {
o.TokenIDs = ids
return nil
}
}
// WithTransferAttribute adds a custom attribute to a transfer operation.
func WithTransferAttribute(attr string, value any) TransferOption {
return func(o *TransferOptions) error {
if o.Attributes == nil {
o.Attributes = make(map[string]any)
}
o.Attributes[attr] = value
return nil
}
}
// WithRestRecipientIdentity sets the recipient data to be used to assign any rest left during a transfer operation
func WithRestRecipientIdentity(recipientData *RecipientData) TransferOption {
return func(o *TransferOptions) error {
o.RestRecipientIdentity = recipientData
return nil
}
}
// AuditRecord models the audit record returned by the audit command
// It contains the token request's anchor, inputs (with Type and Quantity), and outputs
type AuditRecord struct {
// Anchor is used to bind the Actions to a given Transaction
Anchor RequestAnchor
// Inputs represent the input tokens of the transaction
Inputs *InputStream
// Outputs represent the output tokens of the transaction
Outputs *OutputStream
// Attributes are metadata which are stored on the public ledger as part of the transaction Actions.
Attributes map[string][]byte
}
// Issue contains information about an issue operation.
// In particular, it carries the identities of the issuer and the receivers
type Issue struct {
// Issuer is the issuer of the tokens
Issuer Identity
// Receivers is the list of identities of the receivers
Receivers []Identity
// ExtraSigners is the list of extra identities that must sign the token request to make it valid.
// This field is to be used by the token drivers to list any additional identities that must
// sign the token request.
ExtraSigners []Identity
}
// Transfer contains information about a transfer operation.
// In particular, it carries the identities of the senders and the receivers
type Transfer struct {
// Senders is the list of identities of the senders
Senders []Identity
// Receivers is the list of identities of the receivers
Receivers []Identity
// ExtraSigners is the list of extra identities that must sign the token request to make it valid.
// This field is to be used by the token drivers to list any additional identities that must
// sign the token request.
ExtraSigners []Identity
// Issuer
Issuer Identity
}
// SignerWithAction associates a signer identity with its action ID.
// This is used to preserve the action context during signature collection.
type SignerWithAction struct {
Signer Identity
ActionID uint32
}
// Request aggregates token operations that must be performed atomically.
// Operations are represented in a backend agnostic way but driver specific.
type Request struct {
// Anchor is used to bind the Actions to a given Transaction
Anchor driver.TokenRequestAnchor
// Actions contains the token operations.
Actions *driver.TokenRequest
// Metadata contains the actions' metadata used to unscramble the content of the actions, if the
// underlying token driver requires that
Metadata *driver.TokenRequestMetadata
// TokenService this request refers to
TokenService *ManagementService `json:"-"`
}
// NewRequest creates a new empty request for the given token service and anchor
func NewRequest(tokenService *ManagementService, anchor RequestAnchor) *Request {
return &Request{
Anchor: anchor,
Actions: &driver.TokenRequest{},
Metadata: &driver.TokenRequestMetadata{},
TokenService: tokenService,
}
}
// NewRequestFromBytes creates a new request from the given anchor, and whose actions and metadata
// are unmarshalled from the given bytes
func NewRequestFromBytes(tokenService *ManagementService, anchor RequestAnchor, actions []byte, trmRaw []byte) (*Request, error) {
tr := &driver.TokenRequest{}
if err := tr.FromBytes(actions); err != nil {
return nil, errors.Wrapf(err, "failed unmarshalling token request [%d]", len(actions))
}
trm := &driver.TokenRequestMetadata{}
if len(trmRaw) != 0 {
if err := trm.FromBytes(trmRaw); err != nil {
return nil, errors.Wrapf(err, "failed unmarshalling token request metadata [%d]", len(trmRaw))
}
}
return &Request{
Anchor: anchor,
Actions: tr,
Metadata: trm,
TokenService: tokenService,
}, nil
}
// NewFullRequestFromBytes creates a new request from the given byte representation
func NewFullRequestFromBytes(tokenService *ManagementService, tr []byte) (*Request, error) {
request := NewRequest(tokenService, "")
if err := request.FromBytes(tr); err != nil {
return nil, errors.Wrapf(err, "failed to unmarshal request")
}
return request, nil
}
// ID returns the anchor of the request
func (r *Request) ID() RequestAnchor {
return r.Anchor
}
// Issue appends an issue action to the request. The action will be prepared using the provided issuer wallet.
// The action issues to the receiver a token of the passed type and quantity.
// Additional options can be passed to customize the action.
func (r *Request) Issue(ctx context.Context, wallet *IssuerWallet, receiver Identity, typ token.Type, q uint64, opts ...IssueOption) (*IssueAction, error) {
logger.DebugfContext(ctx, "Start issue")
logger.DebugfContext(ctx, "Done issue")
if wallet == nil {
return nil, errors.Errorf("wallet is nil")
}
if typ == "" {
return nil, errors.Errorf("type is empty")
}
if q == 0 {
return nil, errors.Errorf("q is zero")
}
maxTokenValue := r.TokenService.PublicParametersManager().PublicParameters().MaxTokenValue()
if q > maxTokenValue {
return nil, errors.Errorf("q is larger than max token value [%d]", maxTokenValue)
}
if receiver.IsNone() {
return nil, errors.Errorf("all recipients should be defined")
}
id, err := wallet.GetIssuerIdentity(typ)
if err != nil {
return nil, errors.WithMessagef(err, "failed getting issuer identity for type [%s]", typ)
}
opt, err := compileIssueOptions(opts...)
if err != nil {
return nil, errors.WithMessagef(err, "failed compiling options [%v]", opts)
}
// Compute Issue
action, metaRaw, err := r.TokenService.tms.IssueService().Issue(
ctx,
id,
typ,
[]uint64{q},
[][]byte{receiver},
&driver.IssueOptions{
Attributes: opt.Attributes,
},
)
if err != nil {
return nil, err
}
// Append
actionRaw, err := action.Serialize()
if err != nil {
return nil, err
}
actionID := uint32(len(r.Actions.Actions)) //nolint:gosec
r.Actions.Actions = append(r.Actions.Actions, &driver.TypedAction{
Type: request.ActionType_ACTION_TYPE_ISSUE,
Raw: actionRaw,
})
r.Metadata.Actions = append(r.Metadata.Actions, &driver.ActionMetadataEntry{
ActionID: actionID,
IssueMetadata: metaRaw,
})
return &IssueAction{a: action}, nil
}
// Transfer appends a transfer action to the request. The action will be prepared using the provided owner wallet.
// The action transfers tokens of the passed types to the receivers for the passed quantities.
// In other words, owners[0] will receives values[0], and so on.
// Additional options can be passed to customize the action.
func (r *Request) Transfer(ctx context.Context, wallet *OwnerWallet, typ token.Type, values []uint64, owners []Identity, opts ...TransferOption) (*TransferAction, error) {
if slices.Contains(values, 0) {
return nil, errors.Errorf("value is zero")
}
opt, err := CompileTransferOptions(opts...)
if err != nil {
return nil, errors.WithMessagef(err, "failed compiling options [%v]", opts)
}
tokenIDs, outputTokens, err := r.prepareTransfer(ctx, false, wallet, typ, values, owners, opt)
if err != nil {
return nil, errors.Wrap(err, "failed preparing transfer")
}
r.TokenService.logger.DebugfContext(ctx, "Prepare Transfer Action [id:%s,ins:%d,outs:%d,attr:%d]", r.Anchor, len(tokenIDs), len(outputTokens), len(opt.Attributes))
ts := r.TokenService.tms.TransferService()
// Compute transfer
transfer, transferMetadata, err := ts.Transfer(
ctx,
r.Anchor,
wallet.w,
tokenIDs,
outputTokens,
&driver.TransferOptions{
Attributes: opt.Attributes,
},
)
if err != nil {
return nil, errors.Wrap(err, "failed creating transfer action")
}
if r.TokenService.logger.IsEnabledFor(zapcore.DebugLevel) {
// double check
if err := ts.VerifyTransfer(ctx, transfer, transferMetadata.Outputs); err != nil {
return nil, errors.Wrap(err, "failed checking generated proof")
}
}
// Append
raw, err := transfer.Serialize()
if err != nil {
return nil, errors.Wrap(err, "failed serializing transfer action")
}
actionID := uint32(len(r.Actions.Actions)) //nolint:gosec
r.Actions.Actions = append(r.Actions.Actions, &driver.TypedAction{
Type: request.ActionType_ACTION_TYPE_TRANSFER,
Raw: raw,
})
r.Metadata.Actions = append(r.Metadata.Actions, &driver.ActionMetadataEntry{
ActionID: actionID,
TransferMetadata: transferMetadata,
})
return &TransferAction{TransferAction: transfer}, nil
}
// Redeem appends a redeem action to the request. The action will be prepared using the provided owner wallet.
// The action redeems tokens of the passed type for a total amount matching the passed value.
// Additional options can be passed to customize the action.
func (r *Request) Redeem(ctx context.Context, wallet *OwnerWallet, typ token.Type, value uint64, opts ...TransferOption) (*TransferAction, error) {
opt, err := CompileTransferOptions(opts...)
if err != nil {
return nil, errors.WithMessagef(err, "failed compiling options [%v]", opts)
}
tokenIDs, outputTokens, err := r.prepareTransfer(ctx, true, wallet, typ, []uint64{value}, []Identity{nil}, opt)
if err != nil {
return nil, errors.Wrap(err, "failed preparing transfer")
}
r.TokenService.logger.DebugfContext(ctx, "Prepare Redeem Action [ins:%d,outs:%d]", len(tokenIDs), len(outputTokens))
ts := r.TokenService.tms.TransferService()
// Compute redeem, it is a transfer with owner set to nil
transfer, transferMetadata, err := ts.Transfer(
ctx,
r.Anchor,
wallet.w,
tokenIDs,
outputTokens,
&driver.TransferOptions{
Attributes: opt.Attributes,
},
)
if err != nil {
return nil, errors.Wrap(err, "failed creating transfer action")
}
if r.TokenService.logger.IsEnabledFor(zapcore.DebugLevel) {
// double check
if err := ts.VerifyTransfer(ctx, transfer, transferMetadata.Outputs); err != nil {
return nil, errors.Wrap(err, "failed checking generated proof")
}
}
// Append
raw, err := transfer.Serialize()
if err != nil {
return nil, errors.Wrap(err, "failed serializing transfer action")
}
actionID := uint32(len(r.Actions.Actions)) //nolint:gosec
r.Actions.Actions = append(r.Actions.Actions, &driver.TypedAction{
Type: request.ActionType_ACTION_TYPE_TRANSFER,
Raw: raw,
})
r.Metadata.Actions = append(r.Metadata.Actions, &driver.ActionMetadataEntry{
ActionID: actionID,
TransferMetadata: transferMetadata,
})
return &TransferAction{transfer}, nil
}
// Upgrade performs an upgrade operation of the passed ledger tokens.
// A proof and its challenge will be used to verify that the request of upgrade is legit.
// If the proof verifies then the passed wallet will be used to issue a new amount of tokens
// matching those whose upgrade has been requested.
func (r *Request) Upgrade(
ctx context.Context,
wallet *IssuerWallet,
receiver Identity,
challenge TokensUpgradeChallenge,
tokens []token.LedgerToken,
proof TokensUpgradeProof,
opts ...IssueOption,
) (*IssueAction, error) {
if wallet == nil {
return nil, errors.Errorf("wallet is nil")
}
if len(tokens) == 0 {
return nil, errors.Errorf("tokens is empty")
}
opt, err := compileIssueOptions(opts...)
if err != nil {
return nil, errors.WithMessagef(err, "failed compiling options [%v]", opts)
}
// Compute Issue
action, meta, err := r.TokenService.tms.IssueService().Issue(
ctx,
nil,
"",
nil,
[][]byte{receiver},
&driver.IssueOptions{
Attributes: opt.Attributes,
TokensUpgradeRequest: &driver.TokenUpgradeRequest{
Challenge: challenge,
Tokens: tokens,
Proof: proof,
},
Wallet: wallet.w,
},
)
if err != nil {
return nil, err
}
// Append
raw, err := action.Serialize()
if err != nil {
return nil, err
}
actionID := uint32(len(r.Actions.Actions)) //nolint:gosec
r.Actions.Actions = append(r.Actions.Actions, &driver.TypedAction{
Type: request.ActionType_ACTION_TYPE_ISSUE,
Raw: raw,
})
r.Metadata.Actions = append(r.Metadata.Actions, &driver.ActionMetadataEntry{
ActionID: actionID,
IssueMetadata: meta,
})
return &IssueAction{a: action}, nil
}
// Outputs returns all token outputs created by this request's actions.
func (r *Request) Outputs(ctx context.Context) (*OutputStream, error) {
return r.outputs(ctx, false)
}
func (r *Request) outputs(ctx context.Context, failOnMissing bool) (*OutputStream, error) {
tms := r.TokenService.tms
pp := tms.PublicParamsManager().PublicParameters()
if pp == nil {
return nil, errors.Errorf("public paramenters not set")
}
meta, err := r.GetMetadata()
if err != nil {
return nil, err
}
var outputs []*Output
counter := uint64(0)
is := tms.IssueService()
issues := r.Actions.GetIssues()
for i, issue := range issues {
// deserialize action
issueAction, err := is.DeserializeIssueAction(issue)
if err != nil {
return nil, errors.Wrapf(err, "failed deserializing issue action [%d]", i)
}
// get metadata for action
issueMeta, err := meta.Issue(i)
if err != nil {
return nil, errors.Wrapf(err, "failed getting issue metadata [%d]", i)
}
if err := issueMeta.Match(&IssueAction{a: issueAction}); err != nil {
return nil, errors.Wrapf(err, "failed matching issue action with its metadata [%d]", i)
}
extractedOutputs, newCounter, err := r.extractIssueOutputs(ctx, i, counter, issueAction, issueMeta, failOnMissing, false)
if err != nil {
return nil, err
}
outputs = append(outputs, extractedOutputs...)
counter = newCounter
}
ts := tms.TransferService()
transfers := r.Actions.GetTransfers()
for i, transfer := range transfers {
// deserialize action
transferAction, err := ts.DeserializeTransferAction(transfer)
if err != nil {
return nil, errors.Wrapf(err, "failed deserializing transfer action [%d]", i)
}
// get metadata for action
transferMeta, err := meta.Transfer(i)
if err != nil {
return nil, errors.Wrapf(err, "failed getting transfer metadata [%d]", i)
}
if err := transferMeta.Match(&TransferAction{transferAction}); err != nil {
return nil, errors.Wrapf(err, "failed matching transfer action with its metadata [%d]", i)
}
if len(transferAction.GetOutputs()) != len(transferMeta.Outputs) {
return nil, errors.Errorf("failed matching transfer action with its metadata [%d]: invalid metadata", i)
}
extractedOutputs, newCounter, err := r.extractTransferOutputs(ctx, i, counter, transferAction, transferMeta, failOnMissing, false)
if err != nil {
return nil, err
}
outputs = append(outputs, extractedOutputs...)
counter = newCounter
}
return NewOutputStream(outputs, tms.PublicParamsManager().PublicParameters().Precision()), nil
}
func (r *Request) extractIssueOutputs(ctx context.Context, i int, counter uint64, issueAction driver.IssueAction, issueMeta *IssueMetadata, failOnMissing, noOutputForRecipient bool) ([]*Output, uint64, error) {
if len(issueAction.GetOutputs()) != len(issueMeta.Outputs) {
return nil, 0, errors.Errorf("failed matching issue action with its metadata [%d]: invalid metadata, the number of outputs does not match", i)
}
// extract outputs for this action
tms := r.TokenService.tms
pp := tms.PublicParamsManager().PublicParameters()
if pp == nil {
return nil, 0, errors.Errorf("public paramenters not set")
}
precision := pp.Precision()
var outputs []*Output
for j, output := range issueAction.GetOutputs() {
if output == nil {
return nil, 0, errors.Errorf("%d^th output in issue action [%d] is nil", j, i)
}
raw, err := output.Serialize()
if err != nil {
return nil, 0, errors.Wrapf(err, "failed deserializing issue action output [%d,%d]", i, j)
}
// is the j-th meta present? It might have been filtered out
if issueMeta.IsOutputAbsent(j) {
r.TokenService.logger.Debugf("Issue Action Output [%d,%d] is absent", i, j)
if failOnMissing {
return nil, 0, errors.Errorf("missing token info for output [%d,%d]", i, j)
}
// // check the recipients anyway
// recipients, err := tms.TokensService().Recipients(raw)
// if err != nil {
// return nil, 0, errors.Wrapf(err, "failed getting recipients [%d,%d]", i, j)
// }
// for k, recipient := range recipients {
// metaRecipient := issueMeta.Outputs[j].RecipientAt(k)
// if metaRecipient == nil {
// return nil, 0, errors.Errorf("missing recipient metadata for output [%d,%d]", i, j)
// }
// if !recipient.Equal(metaRecipient.Identity) {
// return nil, 0, errors.Errorf("invalid recipient [%d,%d] [%s:%s]", i, j, recipient, metaRecipient.Identity)
// }
// }
counter++
continue
}
// is the j-th meta present? Yes
tok, issuer, recipients, format, err := tms.TokensService().Deobfuscate(ctx, raw, issueMeta.Outputs[j].OutputMetadata)
if err != nil {
return nil, 0, errors.Wrapf(err, "failed getting issue action output in the clear [%d,%d]", i, j)
}
if !issuer.Equal(issueAction.GetIssuer()) {
return nil, 0, errors.Errorf("invalid issuer [%d,%d]", i, j)
}
if len(recipients) == 0 {
return nil, 0, errors.Errorf("missing recipients [%d,%d]", i, j)
}
q, err := token.ToQuantity(tok.Quantity, precision)
if err != nil {
return nil, 0, errors.Wrapf(err, "failed getting quantity [%d,%d]", i, j)
}
if noOutputForRecipient {
outputs = append(outputs, &Output{
Token: *tok,
ActionIndex: i,
Index: counter,
Owner: tok.Owner,
Type: tok.Type,
Quantity: q,
Issuer: issuer,
LedgerOutput: raw,
LedgerOutputFormat: format,
LedgerOutputMetadata: issueMeta.Outputs[j].OutputMetadata,
})
} else {
for k, recipient := range recipients {
metaRecipient := issueMeta.Outputs[j].RecipientAt(k)
if metaRecipient == nil {
return nil, 0, errors.Errorf("missing recipient metadata for output [%d,%d]", i, j)
}
if !recipient.Equal(metaRecipient.Identity) {
return nil, 0, errors.Errorf("invalid recipient [%d,%d] [%s:%s]", i, j, recipient, metaRecipient.Identity)
}
eID, rID, err := tms.WalletService().GetEIDAndRH(ctx, recipient, metaRecipient.AuditInfo)
if err != nil {
return nil, 0, errors.Wrapf(err, "failed getting enrollment id and revocation handle [%d,%d]", i, j)
}
outputs = append(outputs, &Output{
Token: *tok,
ActionIndex: i,
Index: counter,
Owner: recipient,
OwnerAuditInfo: metaRecipient.AuditInfo,
EnrollmentID: eID,
RevocationHandler: rID,
Type: tok.Type,
Quantity: q,
Issuer: issuer,
LedgerOutput: raw,
LedgerOutputFormat: format,
LedgerOutputMetadata: issueMeta.Outputs[j].OutputMetadata,
})
}
}
counter++
}
return outputs, counter, nil
}
func (r *Request) extractTransferOutputs(ctx context.Context, i int, counter uint64, transferAction driver.TransferAction, transferMeta *TransferMetadata, failOnMissing, noOutputForRecipient bool) ([]*Output, uint64, error) {
tms := r.TokenService.tms
if tms.PublicParamsManager() == nil || tms.PublicParamsManager().PublicParameters() == nil {
return nil, 0, errors.New("can't get inputs: invalid token service in request")
}
precision := tms.PublicParamsManager().PublicParameters().Precision()
var outputs []*Output
recipientCounter := 0
for j, output := range transferAction.GetOutputs() {
if output == nil {
return nil, 0, errors.Errorf("%d^th output in transfer action [%d] is nil", j, i)
}
ledgerOutput, err := output.Serialize()
if err != nil {
return nil, 0, errors.Wrapf(err, "failed deserializing transfer action output [%d,%d]", i, j)
}
// is the j-th meta present? It might have been filtered out
if transferMeta.IsOutputAbsent(j) || len(transferMeta.Outputs[j].OutputMetadata) == 0 {
r.TokenService.logger.Debugf("Transfer Action Output [%d,%d] is absent", i, j)
if failOnMissing {
return nil, 0, errors.Errorf("missing token info for output [%d,%d]", i, j)
}
// check the recipients anyway
// recipients, err := tms.TokensService().Recipients(ledgerOutput)
// if err != nil {
// return nil, 0, errors.Wrapf(err, "failed getting recipients [%d,%d]", i, j)
// }
// for k, recipient := range recipients {
// metaRecipient := transferMeta.Outputs[j].RecipientAt(k)
// if metaRecipient == nil {
// return nil, 0, errors.Errorf("missing recipient metadata for output [%d,%d]", i, j)
// }
// if !recipient.Equal(metaRecipient.Identity) {
// return nil, 0, errors.Errorf("invalid recipient [%d,%d] [%s:%s]", i, j, recipient, metaRecipient.Identity)
// }
// }
counter++
continue
}
// is the j-th meta present? Yes
tok, issuer, recipients, ledgerOutputFormat, err := tms.TokensService().Deobfuscate(ctx, ledgerOutput, transferMeta.Outputs[j].OutputMetadata)
if err != nil {
return nil, 0, errors.Wrapf(err, "failed getting transfer action output in the clear [%d,%d]", i, j)
}
// For a redeem output (empty owner), the per-output metadata does not carry the
// issuer identity: it is only available at the transfer action level. Recover it
// so that downstream processing can attribute the redeem to its issuer.
if len(tok.Owner) == 0 && issuer.IsNone() {
issuer = transferAction.GetIssuer()
}
if len(recipients) == 0 {
// Add an empty recipient
recipients = append(recipients, Identity{})
}
if len(issuer) == 0 && output.IsRedeem() {
issuer = transferAction.GetIssuer()
}
q, err := token.ToQuantity(tok.Quantity, precision)
if err != nil {
return nil, 0, errors.Wrapf(err, "failed getting quantity [%d,%d]", i, j)
}
if noOutputForRecipient {
outputs = append(outputs, &Output{
Token: *tok,
ActionIndex: i,
Index: counter,
Owner: tok.Owner,
OwnerAuditInfo: transferMeta.Outputs[j].OutputAuditInfo,
EnrollmentID: "", // not available here
RevocationHandler: "", // not available here
Type: tok.Type,
Quantity: q,
LedgerOutput: ledgerOutput,
LedgerOutputFormat: ledgerOutputFormat,
LedgerOutputMetadata: transferMeta.Outputs[j].OutputMetadata,
Issuer: issuer,
})
for k, recipient := range recipients {
metaRecipient := transferMeta.Outputs[j].RecipientAt(k)
if metaRecipient == nil {
return nil, 0, errors.Errorf("missing recipient metadata for output [%d,%d]", i, j)
}
if !recipient.Equal(metaRecipient.Identity) {
return nil, 0, errors.Errorf("invalid recipient [%d,%d] [%s:%s]", i, j, recipient, metaRecipient.Identity)
}
}
} else {
for k, recipient := range recipients {
metaRecipient := transferMeta.Outputs[j].RecipientAt(k)
if metaRecipient == nil {
return nil, 0, errors.Errorf("missing recipient metadata for output [%d,%d]", i, j)
}
if !recipient.Equal(metaRecipient.Identity) {
return nil, 0, errors.Errorf("invalid recipient [%d,%d] [%s:%s]", i, j, recipient, metaRecipient.Identity)
}
var eID string
var rID string
var receiverAuditInfo []byte
var targetLedgerOutput []byte
if len(tok.Owner) != 0 {
receiverAuditInfo = metaRecipient.AuditInfo
eID, rID, err = tms.WalletService().GetEIDAndRH(ctx, recipient, receiverAuditInfo)
if err != nil {
return nil, 0, errors.Wrapf(err, "failed getting enrollment id and revocation handle [%d,%d]", i, recipientCounter)
}
targetLedgerOutput = ledgerOutput
}
r.TokenService.logger.Debugf("Transfer Action Output [%d,%d][%s:%d] is present, extract [%s]", i, j, r.Anchor, counter, Hashable(ledgerOutput))
outputs = append(outputs, &Output{
Token: *tok,
ActionIndex: i,
Index: counter,
Owner: recipient,
OwnerAuditInfo: receiverAuditInfo,
EnrollmentID: eID,
RevocationHandler: rID,
Type: tok.Type,
Quantity: q,
LedgerOutput: targetLedgerOutput,
LedgerOutputFormat: ledgerOutputFormat,
LedgerOutputMetadata: transferMeta.Outputs[j].OutputMetadata,
Issuer: issuer,
})
recipientCounter++
}
}
counter++
}
return outputs, counter, nil
}
// Inputs returns all token inputs consumed by this request's transfer actions.
// Note: Type and Quantity are not included (use AuditRecord for full details).
func (r *Request) Inputs(ctx context.Context) (*InputStream, error) {
return r.inputs(ctx, false)
}
func (r *Request) inputs(ctx context.Context, failOnMissing bool) (*InputStream, error) {
tms := r.TokenService.tms
if tms.PublicParamsManager() == nil || tms.PublicParamsManager().PublicParameters() == nil {
return nil, errors.New("can't get inputs: invalid token service in request")
}
meta, err := r.GetMetadata()
if err != nil {
return nil, err
}
var inputs []*Input
ts := tms.TransferService()
transfers := r.Actions.GetTransfers()
for i, transfer := range transfers {
// deserialize action
transferAction, err := ts.DeserializeTransferAction(transfer)
if err != nil {
return nil, errors.Wrapf(err, "failed deserializing transfer action [%d]", i)
}
// get metadata for action
transferMeta, err := meta.Transfer(i)
if err != nil {
return nil, errors.Wrapf(err, "failed getting transfer metadata [%d]", i)
}
if err := transferMeta.Match(&TransferAction{transferAction}); err != nil {
return nil, errors.Wrapf(err, "failed matching transfer action with its metadata [%d]", i)
}
// we might not have TokenIDs if they have been filtered
if len(transferMeta.Inputs) == 0 && failOnMissing {
return nil, errors.Errorf("missing token ids for transfer [%d]", i)
}
extractedInputs, err := r.extractTransferInputs(ctx, i, transferMeta, failOnMissing)
if err != nil {
return nil, err
}
inputs = append(inputs, extractedInputs...)
}
return NewInputStream(r.TokenService.Vault().NewQueryEngine(), inputs, tms.PublicParamsManager().PublicParameters().Precision()), nil
}
func (r *Request) extractIssueInputs(actionIndex int, metadata *IssueMetadata) ([]*Input, error) {
var inputs []*Input
for _, input := range metadata.Inputs {
inputs = append(inputs, &Input{
ActionIndex: actionIndex,
Id: input.TokenID,
})
}
return inputs, nil
}
func (r *Request) extractTransferInputs(ctx context.Context, actionIndex int, metadata *TransferMetadata, failOnMissing bool) ([]*Input, error) {
// Iterate over the metadata.SenderAuditInfos because we know that there will be at least one
// sender, but it might be that there are not token IDs due to filtering.
tms := r.TokenService.tms
var inputs []*Input
for j, input := range metadata.Inputs {
// The recipient might be missing because it has been filtered out. Skip in this case
if metadata.IsInputAbsent(j) {
if failOnMissing {
return nil, errors.Errorf("missing receiver for transfer [%d,%d]", actionIndex, j)
}
continue
}
for _, sender := range input.Senders {
eID, rID, err := tms.WalletService().GetEIDAndRH(ctx, sender.Identity, sender.AuditInfo)
if err != nil {
return nil, errors.Wrapf(err, "failed getting enrollment id and revocation handle [%d,%d]", actionIndex, j)
}
inputs = append(inputs, &Input{
ActionIndex: actionIndex,
Id: metadata.TokenIDAt(j),
Owner: sender.Identity,
OwnerAuditInfo: sender.AuditInfo,
EnrollmentID: eID,
RevocationHandler: rID,
})
}
}
return inputs, nil
}
// InputsAndOutputs returns both inputs and outputs along with action metadata.
func (r *Request) InputsAndOutputs(ctx context.Context) (*InputStream, *OutputStream, map[string][]byte, error) {
return r.inputsAndOutputs(ctx, false, false, false)
}
// InputsAndOutputsNoRecipients returns inputs and outputs without recipient identity information.
func (r *Request) InputsAndOutputsNoRecipients(ctx context.Context) (*InputStream, *OutputStream, error) {
is, os, _, err := r.inputsAndOutputs(ctx, false, false, true)
return is, os, err
}
func (r *Request) inputsAndOutputs(ctx context.Context, failOnMissing, verifyActions, noOutputForRecipient bool) (*InputStream, *OutputStream, ActionMetadata, error) {
tms := r.TokenService.tms
if tms.PublicParamsManager() == nil || tms.PublicParamsManager().PublicParameters() == nil {
return nil, nil, nil, errors.New("can't get inputs: invalid token service in request")
}
meta, err := r.GetMetadata()
if err != nil {
return nil, nil, nil, err
}
var inputs []*Input
var outputs []*Output
attributes := map[string][]byte{}
counter := uint64(0)
issueService := tms.IssueService()
issues := r.Actions.GetIssues()
for i, issue := range issues {
// deserialize action
issueAction, err := issueService.DeserializeIssueAction(issue)
if err != nil {
return nil, nil, nil, errors.Wrapf(err, "failed deserializing issue action [%d]", i)
}
maps.Copy(attributes, issueAction.GetMetadata())
// get metadata for action
issueMeta, err := meta.Issue(i)
if err != nil {
return nil, nil, nil, errors.Wrapf(err, "failed getting issue metadata [%d]", i)
}
if err := issueMeta.Match(&IssueAction{a: issueAction}); err != nil {
return nil, nil, nil, errors.Wrapf(err, "failed matching issue action with its metadata [%d]", i)
}
if verifyActions {