-
Notifications
You must be signed in to change notification settings - Fork 2
/
inputs_sig.go
2569 lines (2152 loc) · 62.4 KB
/
inputs_sig.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 c_polygonid
import (
"bytes"
"context"
"crypto/sha256"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"math/big"
"runtime/trace"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/dgraph-io/badger/v4"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/iden3/go-circuits/v2"
core "github.com/iden3/go-iden3-core/v2"
"github.com/iden3/go-iden3-core/v2/w3c"
"github.com/iden3/go-iden3-crypto/babyjub"
"github.com/iden3/go-iden3-crypto/poseidon"
"github.com/iden3/go-iden3-crypto/utils"
"github.com/iden3/go-merkletree-sql/v2"
json2 "github.com/iden3/go-schema-processor/v2/json"
"github.com/iden3/go-schema-processor/v2/merklize"
"github.com/iden3/go-schema-processor/v2/processor"
"github.com/iden3/go-schema-processor/v2/verifiable"
"github.com/iden3/iden3comm/v2"
"github.com/iden3/iden3comm/v2/packers"
i3cResolvers "github.com/iden3/iden3comm/v2/resolvers"
"github.com/iden3/merkletree-proof/resolvers"
"github.com/piprate/json-gold/ld"
)
const mtLevels = 40
type jsonObj = map[string]any
//go:embed schemas/credentials-v1.json-ld
var credentialsV1JsonLDBytes []byte
func stringByPath(obj jsonObj, path string) (string, error) {
v, err := getByPath(obj, path)
if err != nil {
return "", err
}
s, ok := v.(string)
if !ok {
return "", fmt.Errorf("not a string at path: %v", path)
}
return s, nil
}
func bigIntOrZeroByPath(obj jsonObj, path string,
allowNumbers bool) (*big.Int, error) {
i, err := bigIntByPath(obj, path, allowNumbers)
if errors.As(err, &errPathNotFound{}) {
return big.NewInt(0), nil
}
return i, err
}
// if allowNumbers is true, then the value can also be a number, not only strings
func bigIntByPath(obj jsonObj, path string,
allowNumbers bool) (*big.Int, error) {
v, err := getByPath(obj, path)
if err != nil {
return nil, err
}
switch vt := v.(type) {
case string:
i, ok := new(big.Int).SetString(vt, 10)
if !ok {
return nil, errors.New("not a big int")
}
return i, nil
case float64:
if !allowNumbers {
return nil, errors.New("not a string")
}
ii := int64(vt)
if float64(ii) != vt {
return nil, errors.New("not an int")
}
return big.NewInt(0).SetInt64(ii), nil
default:
return nil, errors.New("not a string")
}
}
func objByBath(proof jsonObj, s string) (jsonObj, error) {
v, err := getByPath(proof, s)
if err != nil {
return nil, err
}
obj, ok := v.(jsonObj)
if !ok {
return nil, errors.New("not an object")
}
return obj, nil
}
type errPathNotFound struct {
path string
}
func (e errPathNotFound) Error() string {
return fmt.Sprintf("path not found: %v", e.path)
}
func getByPath(obj jsonObj, path string) (any, error) {
parts := strings.Split(path, ".")
var curObj = obj
for i, part := range parts {
if part == "" {
return nil, errors.New("path is empty")
}
if i == len(parts)-1 {
v, ok := curObj[part]
if !ok {
return nil, errPathNotFound{path}
}
return v, nil
}
nextObj, ok := curObj[part]
if !ok {
return nil, errPathNotFound{path}
}
curObj, ok = nextObj.(jsonObj)
if !ok {
return nil, errors.New("not a json object")
}
}
return nil, errors.New("should not happen")
}
type errProofNotFound verifiable.ProofType
func (e errProofNotFound) Error() string {
return fmt.Sprintf("proof not found: %v", string(e))
}
func claimWithSigProofFromObj(ctx context.Context, cfg EnvConfig,
w3cCred verifiable.W3CCredential,
skipClaimRevocationCheck bool) (circuits.ClaimWithSigProof, error) {
var out circuits.ClaimWithSigProof
proofI := findProofByType(w3cCred, verifiable.BJJSignatureProofType)
if proofI == nil {
return out, errProofNotFound(verifiable.BJJSignatureProofType)
}
var err error
proof, ok := proofI.(*verifiable.BJJSignatureProof2021)
if !ok {
return out, errors.New("proof is not of type BJJSignatureProof2021")
}
issuerDID, err := w3c.ParseDID(proof.IssuerData.ID)
if err != nil {
return out, err
}
issuerID, err := core.IDFromDID(*issuerDID)
if err != nil {
return out, fmt.Errorf("can't get issuer ID from DID (%v): %w",
issuerDID, err)
}
out.IssuerID = &issuerID
out.Claim, err = proof.GetCoreClaim()
if err != nil {
return out, err
}
credStatus, ok := w3cCred.CredentialStatus.(jsonObj)
if !ok {
return out, errors.New("not a json object")
}
userDID, err := userDIDFromCred(w3cCred)
if err != nil {
return out, err
}
out.NonRevProof, err = buildAndValidateCredentialStatus(ctx, cfg,
credStatus, issuerDID, userDID, skipClaimRevocationCheck)
if err != nil {
return out, ErrCredentialStatus{
err: err,
owner: CredentialStatusOwnerUser,
}
}
out.SignatureProof, err = signatureProof(ctx, cfg, *proof, issuerDID,
userDID)
if err != nil {
return out, err
}
return out, nil
}
// returned DID maybe nil if we do not find it in the credential
func userDIDFromCred(w3cCred verifiable.W3CCredential) (*w3c.DID, error) {
if userDIDi, ok := w3cCred.CredentialSubject["id"]; ok {
var userDIDs string
userDIDs, ok = userDIDi.(string)
if ok {
userDID, err := w3c.ParseDID(userDIDs)
if err != nil {
return nil, fmt.Errorf(
"error parsing user DID from credentialSubject.id field: %w",
err)
}
return userDID, nil
} else {
return nil, errors.New(
"credentialSubject.id field supposed to be a string type and in DID format")
}
}
return nil, nil
}
func getResolversRegistry(ctx context.Context,
cfg PerChainConfig) (*verifiable.CredentialStatusResolverRegistry, func(), error) {
var ethClients = make(map[core.ChainID]*ethclient.Client, len(cfg))
var stateContractAddresses = make(map[core.ChainID]common.Address, len(cfg))
var registry = &verifiable.CredentialStatusResolverRegistry{}
cleanupFn := func() {
registry.Delete(verifiable.SparseMerkleTreeProof)
registry.Delete(verifiable.Iden3ReverseSparseMerkleTreeProof)
registry.Delete(verifiable.Iden3OnchainSparseMerkleTreeProof2023)
registry.Delete(verifiable.Iden3commRevocationStatusV1)
for _, cli := range ethClients {
cli.Close()
}
}
for chainID, chainCfg := range cfg {
err := chainCfg.validate()
if err != nil {
cleanupFn()
return nil, nil, fmt.Errorf(
"chain config validation failed for chain ID %v: %w",
chainID, err)
}
ethCli, err := ethclient.DialContext(ctx, chainCfg.RPCUrl)
if err != nil {
cleanupFn()
return nil, nil, err
}
ethClients[chainID] = ethCli
stateContractAddresses[chainID] = chainCfg.StateContractAddr
}
registry.Register(verifiable.SparseMerkleTreeProof,
verifiable.IssuerResolver{})
rhsResolver := resolvers.NewRHSResolver(ethClients, stateContractAddresses)
registry.Register(verifiable.Iden3ReverseSparseMerkleTreeProof, rhsResolver)
onChainRHSResolver := resolvers.NewOnChainResolver(ethClients,
stateContractAddresses)
registry.Register(verifiable.Iden3OnchainSparseMerkleTreeProof2023,
onChainRHSResolver)
pm := iden3comm.NewPackageManager()
err := pm.RegisterPackers(&packers.PlainMessagePacker{})
if err != nil {
cleanupFn()
return nil, nil, err
}
iden3comResolver := i3cResolvers.NewAgentResolver(
i3cResolvers.AgentResolverConfig{PackageManager: pm})
registry.Register(verifiable.Iden3commRevocationStatusV1, iden3comResolver)
return registry, cleanupFn, nil
}
func stringToHash(h string) (*merkletree.Hash, error) {
if h == "" {
return nil, nil
}
return merkletree.NewHashFromHex(h)
}
func verifiableTreeStateToCircuitsTreeState(
s verifiable.TreeState) (circuits.TreeState, error) {
var err error
var out circuits.TreeState
out.ClaimsRoot = &merkletree.HashZero
out.RootOfRoots = &merkletree.HashZero
out.RevocationRoot = &merkletree.HashZero
if s.State != nil {
out.State, err = stringToHash(*s.State)
if err != nil {
return out, fmt.Errorf("can't parse state: %w", err)
}
}
if s.ClaimsTreeRoot != nil {
out.ClaimsRoot, err = stringToHash(*s.ClaimsTreeRoot)
if err != nil {
return out, fmt.Errorf("can't parse claims tree root: %w", err)
}
}
if s.RevocationTreeRoot != nil {
out.RevocationRoot, err = stringToHash(*s.RevocationTreeRoot)
if err != nil {
return out, fmt.Errorf("can't parse revocation tree root: %w", err)
}
}
if s.RootOfRoots != nil {
out.RootOfRoots, err = stringToHash(*s.RootOfRoots)
if err != nil {
return out, fmt.Errorf("can't parse root of roots tree root: %w", err)
}
}
return out, nil
}
func revStatusToCircuitsMTPProof(
revStatus verifiable.RevocationStatus) (circuits.MTProof, error) {
p := circuits.MTProof{Proof: &revStatus.MTP}
var err error
p.TreeState, err = verifiableTreeStateToCircuitsTreeState(revStatus.Issuer)
if err != nil {
return p, fmt.Errorf(
"can't convert verifiable.TreeState to circuits.TreeState: %w", err)
}
return p, nil
}
func buildAndValidateCredentialStatus(ctx context.Context, cfg EnvConfig,
credStatus jsonObj, issuerDID, userDID *w3c.DID,
skipClaimRevocationCheck bool) (circuits.MTProof, error) {
credStatus2, err := credStatusFromJsonObj(credStatus)
if err != nil {
return circuits.MTProof{}, ErrCredentialStatusExtract{err: err}
}
revStatus, err := cachedResolve(ctx, cfg, issuerDID, userDID,
credStatus2, getResolversRegistry)
if err != nil {
return circuits.MTProof{}, ErrCredentialStatusResolve{err: err}
}
cProof, err := revStatusToCircuitsMTPProof(revStatus)
if err != nil {
return circuits.MTProof{}, ErrCredentialStatusTreeBuild{err: err}
}
if skipClaimRevocationCheck {
return cProof, nil
}
treeStateOk, err := validateTreeState(cProof.TreeState)
if err != nil {
return circuits.MTProof{},
ErrCredentialStatusTreeState{
msg: "tree state validation failed",
err: err,
}
}
if !treeStateOk {
return circuits.MTProof{},
ErrCredentialStatusTreeState{
msg: "invalid tree state",
err: err,
}
}
revNonce := new(big.Int).SetUint64(credStatus2.RevocationNonce)
proofValid := merkletree.VerifyProof(cProof.TreeState.RevocationRoot,
cProof.Proof, revNonce, big.NewInt(0))
if !proofValid {
return circuits.MTProof{}, ErrCredentialStatusTreeState{
msg: "proof validation failed",
}
}
if cProof.Proof.Existence {
return circuits.MTProof{}, ErrCredentialStatusRevoked
}
return cProof, nil
}
// check TreeState consistency
func validateTreeState(s circuits.TreeState) (bool, error) {
if s.State == nil {
return false, errors.New("state is nil")
}
ctrHash := &merkletree.HashZero
if s.ClaimsRoot != nil {
ctrHash = s.ClaimsRoot
}
rtrHash := &merkletree.HashZero
if s.RevocationRoot != nil {
rtrHash = s.RevocationRoot
}
rorHash := &merkletree.HashZero
if s.RootOfRoots != nil {
rorHash = s.RootOfRoots
}
wantState, err := poseidon.Hash([]*big.Int{ctrHash.BigInt(),
rtrHash.BigInt(), rorHash.BigInt()})
if err != nil {
return false, err
}
return wantState.Cmp(s.State.BigInt()) == 0, nil
}
func sigFromHex(sigHex string) (*babyjub.Signature, error) {
sigBytes, err := hex.DecodeString(sigHex)
if err != nil {
return nil, err
}
var compSig babyjub.SignatureComp
if len(sigBytes) != len(compSig) {
return nil, fmt.Errorf("signature length is not %v", len(compSig))
}
copy(compSig[:], sigBytes)
return compSig.Decompress()
}
func signatureProof(ctx context.Context, cfg EnvConfig,
proof verifiable.BJJSignatureProof2021, issuerDID,
userDID *w3c.DID) (out circuits.BJJSignatureProof, err error) {
out.Signature, err = sigFromHex(proof.Signature)
if err != nil {
return out, err
}
out.IssuerAuthClaim = new(core.Claim)
err = out.IssuerAuthClaim.FromHex(proof.IssuerData.AuthCoreClaim)
if err != nil {
return out, err
}
out.IssuerAuthIncProof.TreeState, err = circuitsTreeStateFromSchemaState(proof.IssuerData.State)
if err != nil {
return out, err
}
out.IssuerAuthIncProof.Proof = proof.IssuerData.MTP
credStatus, ok := proof.IssuerData.CredentialStatus.(jsonObj)
if !ok {
return out, errors.New("credential status is not of object type")
}
out.IssuerAuthNonRevProof, err =
buildAndValidateCredentialStatus(ctx, cfg, credStatus, issuerDID,
userDID, false)
if err != nil {
return out, ErrCredentialStatus{
err: err,
owner: CredentialStatusOwnerIssuer,
}
}
return out, nil
}
func findProofByType(w3cCred verifiable.W3CCredential,
proofType verifiable.ProofType) verifiable.CredentialProof {
for _, p := range w3cCred.Proof {
if p.ProofType() == proofType {
return p
}
}
return nil
}
type inputsRequest struct {
ID core.ID `json:"id"`
ProfileNonce JsonBigInt `json:"profileNonce"`
ClaimSubjectProfileNonce JsonBigInt `json:"claimSubjectProfileNonce"`
VerifiableCredentials json.RawMessage `json:"verifiableCredentials"`
Request jsonObj `json:"request"`
}
type v3InputsRequest struct {
inputsRequest
VerifierID *w3c.DID `json:"verifierId"`
LinkNonce JsonBigInt `json:"linkNonce"`
}
type linkedMultiQueryInputsRequest struct {
inputsRequest
LinkNonce *JsonBigInt `json:"linkNonce"`
}
type onChainInputsRequest struct {
ID *core.ID `json:"id"`
ProfileNonce *JsonBigInt `json:"profileNonce"`
ClaimSubjectProfileNonce *JsonBigInt `json:"claimSubjectProfileNonce"`
AuthClaim *core.Claim `json:"authClaim"`
AuthClaimIncMtp *merkletree.Proof `json:"authClaimIncMtp"`
AuthClaimNonRevMtp *merkletree.Proof `json:"authClaimNonRevMtp"`
TreeState *circuits.TreeState `json:"treeState"`
GistProof *circuits.GISTProof `json:"gistProof"`
Signature *hexSigJson `json:"signature"`
Challenge *JsonBigInt `json:"challenge"`
VerifiableCredentials json.RawMessage `json:"verifiableCredentials"`
Request jsonObj `json:"request"`
}
type txData struct {
ContractAddress common.Address `json:"contractAddress"`
ChainID core.ChainID `json:"chainId"`
}
type v3OnChainInputsRequest struct {
onChainInputsRequest
VerifierID *w3c.DID `json:"verifierId"`
LinkNonce JsonBigInt `json:"linkNonce"`
TxData *txData `json:"transactionData"`
}
type AtomicQueryInputsResponse struct {
Inputs circuits.InputsMarshaller
VerifiablePresentation map[string]any
}
func AtomicQueryMtpV2InputsFromJson(ctx context.Context, cfg EnvConfig,
in []byte) (AtomicQueryInputsResponse, error) {
ctx, task := trace.NewTask(ctx, "AtomicQueryMtpV2InputsFromJson")
defer task.End()
var out AtomicQueryInputsResponse
var inpMarsh circuits.AtomicQueryMTPV2Inputs
var obj inputsRequest
err := json.Unmarshal(in, &obj)
if err != nil {
return out, err
}
inpMarsh.RequestID, err = bigIntByPath(obj.Request, "id", true)
if err != nil {
return out, err
}
inpMarsh.ID = &obj.ID
inpMarsh.ProfileNonce = obj.ProfileNonce.BigInt()
inpMarsh.ClaimSubjectProfileNonce = obj.ClaimSubjectProfileNonce.BigInt()
circuitID, err := getCircuitID(obj.Request)
if err != nil {
return out, err
}
if circuitID != circuits.AtomicQueryMTPV2CircuitID {
return out, errors.New("wrong circuit")
}
var w3cCred verifiable.W3CCredential
err = json.Unmarshal(obj.VerifiableCredentials, &w3cCred)
if err != nil {
return out, err
}
inpMarsh.SkipClaimRevocationCheck, err = querySkipRevocation(obj.Request)
if err != nil {
return out, err
}
var wg sync.WaitGroup
var queryErr error
var proofErr error
onClaimReady := func(claim *core.Claim) {
wg.Add(1)
go func() {
defer wg.Done()
start := time.Now()
inpMarsh.Query, out.VerifiablePresentation, queryErr = queryFromObj(
ctx, w3cCred, obj.Request, claim, cfg.documentLoader(),
circuitID)
slog.Debug("query done in", "time", time.Since(start))
}()
}
wg.Add(1)
go func() {
defer wg.Done()
start := time.Now()
inpMarsh.Claim, proofErr = claimWithMtpProofFromObj(ctx, cfg, w3cCred,
inpMarsh.SkipClaimRevocationCheck, onClaimReady)
slog.Debug("rev proof done in", "time", time.Since(start))
}()
wg.Wait()
if proofErr != nil {
return out, proofErr
}
if queryErr != nil {
return out, queryErr
}
inpMarsh.CurrentTimeStamp = time.Now().Unix()
out.Inputs = inpMarsh
return out, nil
}
type objEntry struct {
key string
value any
}
func mkVPObj(tp string, kvs ...objEntry) (jsonObj, error) {
out := jsonObj{"@type": tp}
for _, kv := range kvs {
err := insertKV(out, kv)
if err != nil {
return nil, err
}
}
return out, nil
}
func insertKV(obj jsonObj, kv objEntry) error {
if kv.key == "" {
return errors.New("empty key")
}
idx := strings.Index(kv.key, ".")
if idx == -1 {
if _, ok := obj[kv.key]; ok {
return fmt.Errorf("key already exists: %v", kv.key)
}
obj[kv.key] = kv.value
return nil
}
if idx == 0 || idx == len(kv.key)-1 {
return fmt.Errorf("invalid key with an empty part: %v", kv.key)
}
var nestedObj jsonObj
nestedObjI, ok := obj[kv.key[:idx]]
if !ok {
nestedObj = make(jsonObj)
obj[kv.key[:idx]] = nestedObj
} else {
nestedObj, ok = nestedObjI.(jsonObj)
if !ok {
return fmt.Errorf("not a json object: %v", kv.key[:idx])
}
}
return insertKV(nestedObj, objEntry{key: kv.key[idx+1:], value: kv.value})
}
func fmtVerifiablePresentation(context string, tp string,
kvs ...objEntry) (map[string]any, error) {
var ldContext any
var baseContext = []any{"https://www.w3.org/2018/credentials/v1"}
if context == baseContext[0] {
ldContext = baseContext
} else {
ldContext = append(baseContext, context)
}
vcTypes := []any{"VerifiableCredential"}
if tp != "VerifiableCredential" {
vcTypes = append(vcTypes, tp)
}
credSubject, err := mkVPObj(tp, kvs...)
if err != nil {
return nil, err
}
return map[string]any{
"@context": baseContext,
"@type": "VerifiablePresentation",
"verifiableCredential": map[string]any{
"@context": ldContext,
"@type": vcTypes,
"credentialSubject": credSubject,
},
}, nil
}
func AtomicQuerySigV2InputsFromJson(ctx context.Context, cfg EnvConfig,
in []byte) (AtomicQueryInputsResponse, error) {
var out AtomicQueryInputsResponse
var inpMarsh circuits.AtomicQuerySigV2Inputs
var obj inputsRequest
err := json.Unmarshal(in, &obj)
if err != nil {
return out, err
}
inpMarsh.RequestID, err = bigIntByPath(obj.Request, "id", true)
if err != nil {
return out, err
}
inpMarsh.ID = &obj.ID
inpMarsh.ProfileNonce = obj.ProfileNonce.BigInt()
inpMarsh.ClaimSubjectProfileNonce = obj.ClaimSubjectProfileNonce.BigInt()
circuitID, err := getCircuitID(obj.Request)
if err != nil {
return out, err
}
if circuitID != circuits.AtomicQuerySigV2CircuitID {
return out, errors.New("wrong circuit")
}
var w3cCred verifiable.W3CCredential
err = json.Unmarshal(obj.VerifiableCredentials, &w3cCred)
if err != nil {
return out, err
}
inpMarsh.SkipClaimRevocationCheck, err = querySkipRevocation(obj.Request)
if err != nil {
return out, err
}
inpMarsh.Claim, err = claimWithSigProofFromObj(ctx, cfg, w3cCred,
inpMarsh.SkipClaimRevocationCheck)
if err != nil {
return out, err
}
inpMarsh.Query, out.VerifiablePresentation, err = queryFromObj(ctx, w3cCred,
obj.Request, inpMarsh.Claim.Claim, cfg.documentLoader(), circuitID)
if err != nil {
return out, err
}
inpMarsh.CurrentTimeStamp = time.Now().Unix()
out.Inputs = inpMarsh
return out, nil
}
func AtomicQueryMtpV2OnChainInputsFromJson(ctx context.Context, cfg EnvConfig,
in []byte) (AtomicQueryInputsResponse, error) {
var out AtomicQueryInputsResponse
var inpMarsh circuits.AtomicQueryMTPV2OnChainInputs
var obj onChainInputsRequest
err := json.Unmarshal(in, &obj)
if err != nil {
return out, err
}
inpMarsh.RequestID, err = bigIntByPath(obj.Request, "id", true)
if err != nil {
return out, err
}
if obj.ID == nil {
return out, errors.New(`"id" field is required`)
}
inpMarsh.ID = obj.ID
inpMarsh.ProfileNonce = obj.ProfileNonce.BigInt()
inpMarsh.ClaimSubjectProfileNonce = obj.ClaimSubjectProfileNonce.BigInt()
inpMarsh.AuthClaim = obj.AuthClaim
inpMarsh.AuthClaimIncMtp = obj.AuthClaimIncMtp
inpMarsh.AuthClaimNonRevMtp = obj.AuthClaimNonRevMtp
if obj.TreeState == nil {
return out, errors.New("treeState is required")
}
inpMarsh.TreeState = *obj.TreeState
if obj.GistProof == nil {
return out, errors.New("gistProof is required")
}
inpMarsh.GISTProof = *obj.GistProof
inpMarsh.Signature = (*babyjub.Signature)(obj.Signature)
inpMarsh.Challenge = obj.Challenge.BigInt()
circuitID, err := getCircuitID(obj.Request)
if err != nil {
return out, err
}
if circuitID != circuits.AtomicQueryMTPV2OnChainCircuitID {
return out, errors.New("wrong circuit")
}
var w3cCred verifiable.W3CCredential
err = json.Unmarshal(obj.VerifiableCredentials, &w3cCred)
if err != nil {
return out, err
}
inpMarsh.SkipClaimRevocationCheck, err = querySkipRevocation(obj.Request)
if err != nil {
return out, err
}
var wg sync.WaitGroup
var queryErr error
var proofErr error
onClaimReady := func(claim *core.Claim) {
wg.Add(1)
go func() {
defer wg.Done()
inpMarsh.Query, out.VerifiablePresentation, queryErr = queryFromObj(
ctx, w3cCred, obj.Request, claim, cfg.documentLoader(),
circuitID)
}()
}
wg.Add(1)
go func() {
defer wg.Done()
inpMarsh.Claim, proofErr = claimWithMtpProofFromObj(ctx, cfg, w3cCred,
inpMarsh.SkipClaimRevocationCheck, onClaimReady)
}()
wg.Wait()
if proofErr != nil {
return out, proofErr
}
if queryErr != nil {
return out, queryErr
}
inpMarsh.CurrentTimeStamp = time.Now().Unix()
out.Inputs = inpMarsh
return out, nil
}
func AtomicQuerySigV2OnChainInputsFromJson(ctx context.Context, cfg EnvConfig,
in []byte) (AtomicQueryInputsResponse, error) {
var out AtomicQueryInputsResponse
var inpMarsh circuits.AtomicQuerySigV2OnChainInputs
var obj onChainInputsRequest
err := json.Unmarshal(in, &obj)
if err != nil {
return out, err
}
inpMarsh.RequestID, err = bigIntByPath(obj.Request, "id", true)
if err != nil {
return out, err
}
if obj.ID == nil {
return out, errors.New(`"id" field is required`)
}
inpMarsh.ID = obj.ID
inpMarsh.ProfileNonce = obj.ProfileNonce.BigInt()
inpMarsh.ClaimSubjectProfileNonce = obj.ClaimSubjectProfileNonce.BigInt()
inpMarsh.AuthClaim = obj.AuthClaim
inpMarsh.AuthClaimIncMtp = obj.AuthClaimIncMtp
inpMarsh.AuthClaimNonRevMtp = obj.AuthClaimNonRevMtp
if obj.TreeState == nil {
return out, errors.New("treeState is required")
}
inpMarsh.TreeState = *obj.TreeState
if obj.GistProof == nil {
return out, errors.New("gistProof is required")
}
inpMarsh.GISTProof = *obj.GistProof
inpMarsh.Signature = (*babyjub.Signature)(obj.Signature)
inpMarsh.Challenge = obj.Challenge.BigInt()
circuitID, err := getCircuitID(obj.Request)
if err != nil {
return out, err
}
if circuitID != circuits.AtomicQuerySigV2OnChainCircuitID {
return out, errors.New("wrong circuit")
}
var w3cCred verifiable.W3CCredential
err = json.Unmarshal(obj.VerifiableCredentials, &w3cCred)
if err != nil {
return out, err
}
inpMarsh.SkipClaimRevocationCheck, err = querySkipRevocation(obj.Request)
if err != nil {
return out, err
}
inpMarsh.Claim, err = claimWithSigProofFromObj(ctx, cfg, w3cCred,
inpMarsh.SkipClaimRevocationCheck)
if err != nil {
return out, err
}
inpMarsh.Query, out.VerifiablePresentation, err = queryFromObj(ctx, w3cCred,
obj.Request, inpMarsh.Claim.Claim, cfg.documentLoader(), circuitID)
if err != nil {
return out, err
}
inpMarsh.CurrentTimeStamp = time.Now().Unix()
out.Inputs = inpMarsh
return out, nil
}
func AtomicQueryV3OnChainInputsFromJson(ctx context.Context, cfg EnvConfig,
in []byte) (AtomicQueryInputsResponse, error) {
var out AtomicQueryInputsResponse
var inpMarsh circuits.AtomicQueryV3OnChainInputs
inpMarsh.IsBJJAuthEnabled = 1
var obj v3OnChainInputsRequest
err := json.Unmarshal(in, &obj)
if err != nil {
return out, err
}
inpMarsh.RequestID, err = bigIntByPath(obj.Request, "id", true)
if err != nil {
return out, err
}
if obj.ID == nil {
return out, errors.New(`"id" field is required`)
}
inpMarsh.ID = obj.ID
inpMarsh.ProfileNonce = obj.ProfileNonce.BigInt()
inpMarsh.ClaimSubjectProfileNonce = obj.ClaimSubjectProfileNonce.BigInt()
inpMarsh.AuthClaim = obj.AuthClaim
inpMarsh.AuthClaimIncMtp = obj.AuthClaimIncMtp
inpMarsh.AuthClaimNonRevMtp = obj.AuthClaimNonRevMtp
if obj.TreeState == nil {
return out, errors.New("treeState is required")
}
inpMarsh.TreeState = *obj.TreeState
if obj.GistProof == nil {
return out, errors.New("gistProof is required")
}
inpMarsh.GISTProof = *obj.GistProof
inpMarsh.Signature = (*babyjub.Signature)(obj.Signature)
inpMarsh.Challenge = obj.Challenge.BigInt()
circuitID, err := getCircuitID(obj.Request)
if err != nil {
return out, err
}
if circuitID != circuits.AtomicQueryV3OnChainCircuitID {