-
Notifications
You must be signed in to change notification settings - Fork 36
/
query_server.go
1200 lines (1069 loc) · 43 KB
/
query_server.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 keeper
import (
"context"
b64 "encoding/base64"
"errors"
"fmt"
"net/url"
"time"
"github.com/google/uuid"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/cosmos/cosmos-sdk/store/prefix"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/provenance-io/provenance/x/metadata/types"
)
const defaultLimit = 100
var _ types.QueryServer = Keeper{}
// Params queries params of metadata module.
func (k Keeper) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "Params")
ctx := sdk.UnwrapSDKContext(c)
var params types.Params
k.paramSpace.GetParamSet(ctx, ¶ms)
return &types.QueryParamsResponse{Params: params, Request: req}, nil
}
// Scope returns a specific scope by id.
func (k Keeper) Scope(c context.Context, req *types.ScopeRequest) (*types.ScopeResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "Scope")
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.ScopeResponse{Request: req}
var scopeAddr, sessionAddr types.MetadataAddress
if len(req.ScopeId) > 0 {
var err error
scopeAddr, err = ParseScopeID(req.ScopeId)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
}
if len(req.SessionAddr) > 0 {
var err error
sessionAddr, err = ParseSessionAddr(req.SessionAddr)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
// ParseSessionAddr if this would fail.
scopeAddr2 := sessionAddr.MustGetAsScopeAddress()
if scopeAddr.Empty() {
scopeAddr = scopeAddr2
} else if !scopeAddr.Equals(scopeAddr2) {
return &retval, status.Errorf(codes.InvalidArgument, "session %s is not in scope %s", sessionAddr, scopeAddr)
}
}
if len(req.RecordAddr) > 0 {
recordAddr, err := ParseRecordAddr(req.RecordAddr)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
// ParseRecordAddr if this would fail.
scopeAddr2 := recordAddr.MustGetAsScopeAddress()
switch {
case !sessionAddr.Empty():
// This assumes that we have checked and set scopeAddr while processing the sessionAddr.
scopeAddr3 := sessionAddr.MustGetAsScopeAddress()
if !scopeAddr2.Equals(scopeAddr3) {
return &retval, status.Errorf(codes.InvalidArgument, "session %s and record %s are not associated with the same scope", sessionAddr, recordAddr)
}
case scopeAddr.Empty():
scopeAddr = scopeAddr2
case !scopeAddr.Equals(scopeAddr2):
return &retval, status.Errorf(codes.InvalidArgument, "session %s is not part of scope %s", recordAddr, scopeAddr)
}
}
if scopeAddr.Empty() {
return &retval, status.Error(codes.InvalidArgument, "empty request parameters")
}
ctx := sdk.UnwrapSDKContext(c)
scope, found := k.GetScope(ctx, scopeAddr)
if found {
retval.Scope = types.WrapScope(&scope)
} else {
retval.Scope = types.WrapScopeNotFound(scopeAddr)
}
var sessErr, recErr error
if req.IncludeSessions {
err := k.IterateSessions(ctx, scopeAddr, func(session types.Session) (stop bool) {
retval.Sessions = append(retval.Sessions, types.WrapSession(&session))
return false
})
if err != nil {
sessErr = fmt.Errorf("error iterating scope [%s] sessions: %w", scopeAddr, err)
}
}
if req.IncludeRecords {
err := k.IterateRecords(ctx, scopeAddr, func(record types.Record) (stop bool) {
retval.Records = append(retval.Records, types.WrapRecord(&record))
return false
})
if err != nil {
recErr = fmt.Errorf("error iterating scope [%s] records: %w", scopeAddr, err)
}
}
var err error
switch {
case sessErr != nil && recErr != nil:
err = fmt.Errorf("errors getting sessions and records: %v, %v", sessErr, recErr) //nolint:errorlint // Can't wrap two errors at once.
case sessErr != nil:
err = sessErr
case recErr != nil:
err = recErr
}
if err != nil {
return &retval, status.Error(codes.Unavailable, err.Error())
}
return &retval, nil
}
// ScopesAll returns all scopes (limited by pagination).
func (k Keeper) ScopesAll(c context.Context, req *types.ScopesAllRequest) (*types.ScopesAllResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "ScopesAll")
retval := types.ScopesAllResponse{Request: req}
pageRequest := getPageRequest(req)
ctx := sdk.UnwrapSDKContext(c)
kvStore := ctx.KVStore(k.storeKey)
prefixStore := prefix.NewStore(kvStore, types.ScopeKeyPrefix)
pageRes, err := query.Paginate(prefixStore, pageRequest, func(key, value []byte) error {
var scope types.Scope
vErr := scope.Unmarshal(value)
if vErr == nil {
retval.Scopes = append(retval.Scopes, types.WrapScope(&scope))
return nil
}
// Something's wrong. Let's do what we can to give indications of it.
var addr types.MetadataAddress
kErr := addr.Unmarshal(key)
if kErr == nil {
k.Logger(ctx).Error("failed to unmarshal scope", "address", addr, "error", vErr)
retval.Scopes = append(retval.Scopes, types.WrapScopeNotFound(addr))
} else {
k64 := b64.StdEncoding.EncodeToString(key)
k.Logger(ctx).Error("failed to unmarshal scope key and value",
"key error", kErr, "value error", vErr, "key (base64)", k64)
retval.Scopes = append(retval.Scopes, &types.ScopeWrapper{})
}
return nil // Still want to move on to the next.
})
if err != nil {
return &retval, status.Error(codes.Unavailable, err.Error())
}
retval.Pagination = pageRes
return &retval, nil
}
// Sessions returns sessions based on the provided request.
func (k Keeper) Sessions(c context.Context, req *types.SessionsRequest) (*types.SessionsResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "Sessions")
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.SessionsResponse{Request: req}
ctx := sdk.UnwrapSDKContext(c)
var scopeAddr, sessionAddr, recordAddr types.MetadataAddress
if len(req.ScopeId) > 0 {
var err error
scopeAddr, err = ParseScopeID(req.ScopeId)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
}
if len(req.RecordAddr) > 0 {
var err error
recordAddr, err = ParseRecordAddr(req.RecordAddr)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
scopeAddr2 := recordAddr.MustGetAsScopeAddress()
if scopeAddr.Empty() {
scopeAddr = scopeAddr2
} else if !scopeAddr.Equals(scopeAddr2) {
return &retval, status.Errorf(codes.InvalidArgument, "record %s is not part of scope %s", recordAddr, scopeAddr)
}
}
if len(req.SessionId) > 0 {
var err error
scopeIDForParsing := req.ScopeId
if len(scopeIDForParsing) == 0 && !scopeAddr.Empty() {
scopeIDForParsing = scopeAddr.String()
}
sessionAddr, err = ParseSessionID(scopeIDForParsing, req.SessionId)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
// ParseSessionID ensures that this will not return an error.
scopeAddr2 := sessionAddr.MustGetAsScopeAddress()
switch {
case !recordAddr.Empty():
// This assumes that we have checked and set scopeAddr while processing the recordAddr.
scopeAddr3 := recordAddr.MustGetAsScopeAddress()
if !scopeAddr2.Equals(scopeAddr3) {
return &retval, status.Errorf(codes.InvalidArgument, "session %s and record %s are not associated with the same scope", sessionAddr, recordAddr)
}
case scopeAddr.Empty():
scopeAddr = scopeAddr2
case !scopeAddr.Equals(scopeAddr2):
return &retval, status.Errorf(codes.InvalidArgument, "session %s is not part of scope %s", recordAddr, scopeAddr)
}
}
if len(req.RecordName) > 0 {
if scopeAddr.Empty() {
// assumes scopeAddr is set previously while parsing other input.
return &retval, status.Error(codes.InvalidArgument, "a scope is required to look up sessions by record name")
}
// We know that scopeAddr is legit, and that we have a name. So this won't give an error.
recordAddr2 := scopeAddr.MustGetAsRecordAddress(req.RecordName)
if recordAddr.Empty() {
recordAddr = recordAddr2
} else if !recordAddr.Equals(recordAddr2) {
return &retval, status.Errorf(codes.InvalidArgument, "record %s does not have name %s", recordAddr, req.RecordName)
}
}
// If a record was identified in the search, we need to get it and either use it to set the sessionAddr,
// or make sure the provided sessionAddr matches what the record has.
if !recordAddr.Empty() {
record, found := k.GetRecord(ctx, recordAddr)
switch {
case !found:
return &retval, status.Errorf(codes.InvalidArgument, "record %s does not exist", recordAddr)
case !sessionAddr.Empty():
if !sessionAddr.Equals(record.SessionId) {
return &retval, status.Errorf(codes.InvalidArgument, "record %s belongs to session %s (not %s)",
recordAddr, record.SessionId, sessionAddr)
}
default:
sessionAddr = record.SessionId
}
}
// Get all the sessions based on the input, and set things up for extra info.
switch {
case !sessionAddr.Empty():
session, found := k.GetSession(ctx, sessionAddr)
if found {
retval.Sessions = append(retval.Sessions, types.WrapSession(&session))
} else {
retval.Sessions = append(retval.Sessions, types.WrapSessionNotFound(sessionAddr))
}
case !scopeAddr.Empty():
itErr := k.IterateSessions(ctx, scopeAddr, func(s types.Session) (stop bool) {
retval.Sessions = append(retval.Sessions, types.WrapSession(&s))
return false
})
if itErr != nil {
return &retval, status.Error(codes.Unavailable, fmt.Sprintf("error getting sessions for scope with address %s", scopeAddr))
}
default:
return &retval, status.Error(codes.InvalidArgument, "empty request parameters")
}
if req.IncludeScope {
scope, found := k.GetScope(ctx, scopeAddr)
if found {
retval.Scope = types.WrapScope(&scope)
} else {
retval.Scope = types.WrapScopeNotFound(scopeAddr)
}
}
if req.IncludeRecords {
// Get all the session ids
sessionAddrs := []types.MetadataAddress{}
for _, s := range retval.Sessions {
if s.Session != nil {
sessionAddrs = append(sessionAddrs, s.Session.SessionId)
}
}
// Iterate the records for the whole scope, and just keep the ones for our sessions.
err := k.IterateRecords(ctx, scopeAddr, func(r types.Record) (stop bool) {
keep := false
for _, a := range sessionAddrs {
if r.SessionId.Equals(a) {
keep = true
break
}
}
if keep {
retval.Records = append(retval.Records, types.WrapRecord(&r))
}
return false
})
if err != nil {
return &retval, status.Errorf(codes.Unavailable, "error iterating scope [%s] records: %s", scopeAddr, err.Error())
}
}
return &retval, nil
}
// SessionsAll returns all sessions (limited by pagination).
func (k Keeper) SessionsAll(c context.Context, req *types.SessionsAllRequest) (*types.SessionsAllResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "SessionsAll")
retval := types.SessionsAllResponse{Request: req}
pageRequest := getPageRequest(req)
ctx := sdk.UnwrapSDKContext(c)
kvStore := ctx.KVStore(k.storeKey)
prefixStore := prefix.NewStore(kvStore, types.SessionKeyPrefix)
pageRes, err := query.Paginate(prefixStore, pageRequest, func(key, value []byte) error {
var session types.Session
vErr := session.Unmarshal(value)
if vErr == nil {
retval.Sessions = append(retval.Sessions, types.WrapSession(&session))
return nil
}
// Something's wrong. Let's do what we can to give indications of it.
var addr types.MetadataAddress
kErr := addr.Unmarshal(key)
if kErr == nil {
k.Logger(ctx).Error("failed to unmarshal session", "address", addr, "error", vErr)
retval.Sessions = append(retval.Sessions, types.WrapSessionNotFound(addr))
} else {
k64 := b64.StdEncoding.EncodeToString(key)
k.Logger(ctx).Error("failed to unmarshal session key and value",
"key error", kErr, "value error", vErr, "key (base64)", k64)
retval.Sessions = append(retval.Sessions, &types.SessionWrapper{})
}
return nil // Still want to move on to the next.
})
if err != nil {
return &retval, status.Error(codes.Unavailable, err.Error())
}
retval.Pagination = pageRes
return &retval, nil
}
// Records returns records based on the provided request.
func (k Keeper) Records(c context.Context, req *types.RecordsRequest) (*types.RecordsResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "Records")
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.RecordsResponse{Request: req}
ctx := sdk.UnwrapSDKContext(c)
var scopeAddr, sessionAddr, recordAddr types.MetadataAddress
if len(req.ScopeId) > 0 {
var err error
scopeAddr, err = ParseScopeID(req.ScopeId)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
}
if len(req.RecordAddr) > 0 {
var err error
recordAddr, err = ParseRecordAddr(req.RecordAddr)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
scopeAddr2 := recordAddr.MustGetAsScopeAddress()
if scopeAddr.Empty() {
scopeAddr = scopeAddr2
} else if !scopeAddr.Equals(scopeAddr2) {
return &retval, status.Errorf(codes.InvalidArgument, "record %s is not part of scope %s", recordAddr, scopeAddr)
}
}
if len(req.SessionId) > 0 {
var err error
sessionAddr, err = ParseSessionID(req.ScopeId, req.SessionId)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
// ParseSessionID ensures that this will not return an error.
scopeAddr2 := sessionAddr.MustGetAsScopeAddress()
switch {
case !recordAddr.Empty():
// This assumes that we have checked and set scopeAddr while processing the recordAddr.
scopeAddr3 := recordAddr.MustGetAsScopeAddress()
if !scopeAddr2.Equals(scopeAddr3) {
return &retval, status.Errorf(codes.InvalidArgument, "session %s and record %s are not associated with the same scope", sessionAddr, recordAddr)
}
case scopeAddr.Empty():
scopeAddr = scopeAddr2
case !scopeAddr.Equals(scopeAddr2):
return &retval, status.Errorf(codes.InvalidArgument, "session %s is not part of scope %s", recordAddr, scopeAddr)
}
}
if len(req.Name) > 0 {
if scopeAddr.Empty() {
// assumes scopeAddr is set previously while parsing other input.
return &retval, status.Error(codes.InvalidArgument, "a scope or session is required to look up records by name")
}
// We know that scopeAddr is legit, and that we have a name. So this won't give an error.
recordAddr2 := scopeAddr.MustGetAsRecordAddress(req.Name)
if recordAddr.Empty() {
recordAddr = recordAddr2
} else if !recordAddr.Equals(recordAddr2) {
return &retval, status.Errorf(codes.InvalidArgument, "record %s does not have name %s", recordAddr, req.Name)
}
}
// Get all the records based on the input, and set things up for extra info.
switch {
case !recordAddr.Empty():
record, found := k.GetRecord(ctx, recordAddr)
if found {
retval.Records = append(retval.Records, types.WrapRecord(&record))
} else {
retval.Records = append(retval.Records, types.WrapRecordNotFound(recordAddr))
}
case !scopeAddr.Empty():
var records []*types.Record
// Get all the records for the scope (and thin them out later if needed).
var err error
records, err = k.GetRecords(ctx, scopeAddr, req.Name)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
// Wrap (and possibly filter) the records and add them to the return value.
if len(records) > 0 {
haveSessionAddr := !sessionAddr.Empty()
for _, r := range records {
if !haveSessionAddr || sessionAddr.Equals(r.SessionId) {
retval.Records = append(retval.Records, types.WrapRecord(r))
}
}
}
default:
return &retval, status.Error(codes.InvalidArgument, "empty request parameters")
}
if req.IncludeScope {
scope, found := k.GetScope(ctx, scopeAddr)
if found {
retval.Scope = types.WrapScope(&scope)
} else {
retval.Scope = types.WrapScopeNotFound(scopeAddr)
}
}
if req.IncludeSessions {
// Get a list of unique session addresses from the records.
sessionAddrs := []types.MetadataAddress{}
for _, r := range retval.Records {
if r.Record != nil {
alreadyHave := false
for _, a := range sessionAddrs {
if r.Record.SessionId.Equals(a) {
alreadyHave = true
break
}
}
if !alreadyHave {
sessionAddrs = append(sessionAddrs, r.Record.SessionId)
}
}
}
// Get each session.
for _, a := range sessionAddrs {
session, found := k.GetSession(ctx, a)
if found {
retval.Sessions = append(retval.Sessions, types.WrapSession(&session))
} else {
retval.Sessions = append(retval.Sessions, types.WrapSessionNotFound(a))
}
}
}
return &retval, nil
}
// RecordsAll returns all records (limited by pagination).
func (k Keeper) RecordsAll(c context.Context, req *types.RecordsAllRequest) (*types.RecordsAllResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "RecordsAll")
retval := types.RecordsAllResponse{Request: req}
pageRequest := getPageRequest(req)
ctx := sdk.UnwrapSDKContext(c)
kvStore := ctx.KVStore(k.storeKey)
prefixStore := prefix.NewStore(kvStore, types.RecordKeyPrefix)
pageRes, err := query.Paginate(prefixStore, pageRequest, func(key, value []byte) error {
var record types.Record
vErr := record.Unmarshal(value)
if vErr == nil {
retval.Records = append(retval.Records, types.WrapRecord(&record))
return nil
}
// Something's wrong. Let's do what we can to give indications of it.
var addr types.MetadataAddress
kErr := addr.Unmarshal(key)
if kErr == nil {
k.Logger(ctx).Error("failed to unmarshal record", "address", addr, "error", vErr)
retval.Records = append(retval.Records, types.WrapRecordNotFound(addr))
} else {
k64 := b64.StdEncoding.EncodeToString(key)
k.Logger(ctx).Error("failed to unmarshal record key and value",
"key error", kErr, "value error", vErr, "key (base64)", k64)
retval.Records = append(retval.Records, &types.RecordWrapper{})
}
return nil // Still want to move on to the next.
})
if err != nil {
return &retval, status.Error(codes.Unavailable, err.Error())
}
retval.Pagination = pageRes
return &retval, nil
}
// Ownership returns a list of scope identifiers that list the given address as a data or value owner.
func (k Keeper) Ownership(c context.Context, req *types.OwnershipRequest) (*types.OwnershipResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "Ownership")
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.OwnershipResponse{Request: req}
if req.Address == "" {
return &retval, status.Error(codes.InvalidArgument, "address cannot be empty")
}
addr, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return &retval, status.Errorf(codes.InvalidArgument, "invalid address: %s", err.Error())
}
ctx := sdk.UnwrapSDKContext(c)
store := ctx.KVStore(k.storeKey)
scopeStore := prefix.NewStore(store, types.GetAddressScopeCacheIteratorPrefix(addr))
pageRes, err := query.Paginate(scopeStore, req.Pagination, func(key, _ []byte) error {
var ma types.MetadataAddress
if mErr := ma.Unmarshal(key); mErr != nil {
return mErr
}
scopeUUID, sErr := ma.ScopeUUID()
if sErr != nil {
return sErr
}
retval.ScopeUuids = append(retval.ScopeUuids, scopeUUID.String())
return nil
})
if err != nil {
return &retval, status.Errorf(codes.InvalidArgument, "paginate: %v", err)
}
retval.Pagination = pageRes
return &retval, nil
}
// ValueOwnership returns a list of scope identifiers that list the given address as a value owner.
func (k Keeper) ValueOwnership(c context.Context, req *types.ValueOwnershipRequest) (*types.ValueOwnershipResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "ValueOwnership")
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.ValueOwnershipResponse{Request: req}
if req.Address == "" {
return &retval, status.Error(codes.InvalidArgument, "address cannot be empty")
}
addr, err := sdk.AccAddressFromBech32(req.Address)
if err != nil {
return &retval, status.Errorf(codes.InvalidArgument, "invalid address: %s", err.Error())
}
ctx := sdk.UnwrapSDKContext(c)
store := ctx.KVStore(k.storeKey)
scopeStore := prefix.NewStore(store, types.GetValueOwnerScopeCacheIteratorPrefix(addr))
pageRes, err := query.Paginate(scopeStore, req.Pagination, func(key, _ []byte) error {
var ma types.MetadataAddress
if mErr := ma.Unmarshal(key); mErr != nil {
return mErr
}
scopeID, sErr := ma.ScopeUUID()
if sErr != nil {
return sErr
}
retval.ScopeUuids = append(retval.ScopeUuids, scopeID.String())
return nil
})
if err != nil {
return &retval, status.Errorf(codes.InvalidArgument, "paginate: %v", err)
}
retval.Pagination = pageRes
return &retval, nil
}
// ScopeSpecification returns a specific scope specification by id.
func (k Keeper) ScopeSpecification(c context.Context, req *types.ScopeSpecificationRequest) (*types.ScopeSpecificationResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "ScopeSpecification")
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.ScopeSpecificationResponse{Request: req}
if len(req.SpecificationId) == 0 {
return &retval, status.Error(codes.InvalidArgument, "specification id cannot be empty")
}
specAddr, err := ParseScopeSpecID(req.SpecificationId)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
ctx := sdk.UnwrapSDKContext(c)
spec, found := k.GetScopeSpecification(ctx, specAddr)
if found {
retval.ScopeSpecification = types.WrapScopeSpec(&spec)
} else {
retval.ScopeSpecification = types.WrapScopeSpecNotFound(specAddr)
}
if found && req.IncludeContractSpecs {
for _, id := range spec.ContractSpecIds {
cs, ok := k.GetContractSpecification(ctx, id)
if ok {
retval.ContractSpecs = append(retval.ContractSpecs, types.WrapContractSpec(&cs))
} else {
retval.ContractSpecs = append(retval.ContractSpecs, types.WrapContractSpecNotFound(id))
}
}
}
if found && req.IncludeRecordSpecs {
var err error
for _, id := range spec.ContractSpecIds {
err = k.IterateRecordSpecsForContractSpec(ctx, id, func(recordSpecID types.MetadataAddress) (stop bool) {
rs, ok := k.GetRecordSpecification(ctx, recordSpecID)
if ok {
retval.RecordSpecs = append(retval.RecordSpecs, types.WrapRecordSpec(&rs))
} else {
retval.RecordSpecs = append(retval.RecordSpecs, types.WrapRecordSpecNotFound(recordSpecID))
}
return false
})
if err != nil {
return &retval, fmt.Errorf("error retrieving contract spec [%s] record specs: %w", id, err)
}
}
}
return &retval, nil
}
// ScopeSpecificationsAll returns all scope specifications (limited by pagination).
func (k Keeper) ScopeSpecificationsAll(c context.Context, req *types.ScopeSpecificationsAllRequest) (*types.ScopeSpecificationsAllResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "ScopeSpecificationsAll")
retval := types.ScopeSpecificationsAllResponse{Request: req}
pageRequest := getPageRequest(req)
ctx := sdk.UnwrapSDKContext(c)
kvStore := ctx.KVStore(k.storeKey)
prefixStore := prefix.NewStore(kvStore, types.ScopeSpecificationKeyPrefix)
pageRes, err := query.Paginate(prefixStore, pageRequest, func(key, value []byte) error {
var scopeSpec types.ScopeSpecification
vErr := scopeSpec.Unmarshal(value)
if vErr == nil {
retval.ScopeSpecifications = append(retval.ScopeSpecifications, types.WrapScopeSpec(&scopeSpec))
return nil
}
// Something's wrong. Let's do what we can to give indications of it.
var addr types.MetadataAddress
kErr := addr.Unmarshal(key)
if kErr == nil {
k.Logger(ctx).Error("failed to unmarshal scope spec", "address", addr, "error", vErr)
retval.ScopeSpecifications = append(retval.ScopeSpecifications, types.WrapScopeSpecNotFound(addr))
} else {
k64 := b64.StdEncoding.EncodeToString(key)
k.Logger(ctx).Error("failed to unmarshal scope spec key and value",
"key error", kErr, "value error", vErr, "key (base64)", k64)
retval.ScopeSpecifications = append(retval.ScopeSpecifications, &types.ScopeSpecificationWrapper{})
}
return nil // Still want to move on to the next.
})
if err != nil {
return &retval, status.Error(codes.Unavailable, err.Error())
}
retval.Pagination = pageRes
return &retval, nil
}
// ContractSpecification returns a specific contract specification by id.
func (k Keeper) ContractSpecification(c context.Context, req *types.ContractSpecificationRequest) (*types.ContractSpecificationResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "ContractSpecification")
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.ContractSpecificationResponse{Request: req}
if len(req.SpecificationId) == 0 {
return &retval, status.Error(codes.InvalidArgument, "specification id cannot be empty")
}
specAddr, addrErr := ParseContractSpecID(req.SpecificationId)
if addrErr != nil {
return &retval, status.Errorf(codes.InvalidArgument, "invalid specification id: %s", addrErr.Error())
}
ctx := sdk.UnwrapSDKContext(c)
spec, found := k.GetContractSpecification(ctx, specAddr)
if found {
retval.ContractSpecification = types.WrapContractSpec(&spec)
} else {
retval.ContractSpecification = types.WrapContractSpecNotFound(specAddr)
}
if req.IncludeRecordSpecs {
recSpecs, err := k.GetRecordSpecificationsForContractSpecificationID(ctx, specAddr)
if err != nil {
return &retval, status.Errorf(codes.Unavailable, "error getting record specifications for contract spec %s: %s",
specAddr, err.Error())
}
retval.RecordSpecifications = types.WrapRecordSpecs(recSpecs)
}
return &retval, nil
}
// ContractSpecificationsAll returns all contract specifications (limited by pagination).
func (k Keeper) ContractSpecificationsAll(c context.Context, req *types.ContractSpecificationsAllRequest) (*types.ContractSpecificationsAllResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "ContractSpecificationsAll")
retval := types.ContractSpecificationsAllResponse{Request: req}
pageRequest := getPageRequest(req)
ctx := sdk.UnwrapSDKContext(c)
kvStore := ctx.KVStore(k.storeKey)
prefixStore := prefix.NewStore(kvStore, types.ContractSpecificationKeyPrefix)
pageRes, err := query.Paginate(prefixStore, pageRequest, func(key, value []byte) error {
var contractSpec types.ContractSpecification
vErr := contractSpec.Unmarshal(value)
if vErr == nil {
retval.ContractSpecifications = append(retval.ContractSpecifications, types.WrapContractSpec(&contractSpec))
return nil
}
// Something's wrong. Let's do what we can to give indications of it.
var addr types.MetadataAddress
kErr := addr.Unmarshal(key)
if kErr == nil {
k.Logger(ctx).Error("failed to unmarshal contract spec", "address", addr, "error", vErr)
retval.ContractSpecifications = append(retval.ContractSpecifications, types.WrapContractSpecNotFound(addr))
} else {
k64 := b64.StdEncoding.EncodeToString(key)
k.Logger(ctx).Error("failed to unmarshal contract spec key and value",
"key error", kErr, "value error", vErr, "key (base64)", k64)
retval.ContractSpecifications = append(retval.ContractSpecifications, &types.ContractSpecificationWrapper{})
}
return nil // Still want to move on to the next.
})
if err != nil {
return &retval, status.Error(codes.Unavailable, err.Error())
}
retval.Pagination = pageRes
return &retval, nil
}
// RecordSpecificationsForContractSpecification returns the record specifications associated with a contract specification.
func (k Keeper) RecordSpecificationsForContractSpecification(
c context.Context,
req *types.RecordSpecificationsForContractSpecificationRequest,
) (*types.RecordSpecificationsForContractSpecificationResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "RecordSpecificationsForContractSpecification")
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.RecordSpecificationsForContractSpecificationResponse{Request: req}
if len(req.SpecificationId) == 0 {
return &retval, status.Error(codes.InvalidArgument, "contract specification id cannot be empty")
}
contractSpecAddr, cSpecAddrErr := ParseContractSpecID(req.SpecificationId)
if cSpecAddrErr != nil {
return &retval, status.Errorf(codes.InvalidArgument, "invalid specification id: %s", cSpecAddrErr.Error())
}
contractSpecUUID, cSpecUUIDErr := contractSpecAddr.ContractSpecUUID()
if cSpecUUIDErr != nil {
return &retval, status.Errorf(codes.InvalidArgument, "could not extract contract spec uuid: %s", cSpecUUIDErr.Error())
}
retval.ContractSpecificationAddr = contractSpecAddr.String()
retval.ContractSpecificationUuid = contractSpecUUID.String()
ctx := sdk.UnwrapSDKContext(c)
recSpecs, err := k.GetRecordSpecificationsForContractSpecificationID(ctx, contractSpecAddr)
if err != nil {
return &retval, status.Errorf(codes.Unavailable, "error getting record specifications for contract spec %s: %s",
contractSpecAddr, err.Error())
}
retval.RecordSpecifications = types.WrapRecordSpecs(recSpecs)
return &retval, err
}
// RecordSpecification returns a specific record specification.
func (k Keeper) RecordSpecification(c context.Context, req *types.RecordSpecificationRequest) (*types.RecordSpecificationResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "RecordSpecification")
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.RecordSpecificationResponse{Request: req}
if len(req.SpecificationId) == 0 {
return &retval, status.Error(codes.InvalidArgument, "specification id cannot be empty")
}
recSpecAddr, recSpecAddrErr := ParseRecordSpecID(req.SpecificationId, req.Name)
if recSpecAddrErr != nil {
return &retval, status.Errorf(codes.InvalidArgument, "invalid input: %s", recSpecAddrErr.Error())
}
ctx := sdk.UnwrapSDKContext(c)
spec, found := k.GetRecordSpecification(ctx, recSpecAddr)
if found {
retval.RecordSpecification = types.WrapRecordSpec(&spec)
} else {
retval.RecordSpecification = types.WrapRecordSpecNotFound(recSpecAddr)
}
return &retval, nil
}
// RecordSpecificationsAll returns all record specifications (limited by pagination).
func (k Keeper) RecordSpecificationsAll(c context.Context, req *types.RecordSpecificationsAllRequest) (*types.RecordSpecificationsAllResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "RecordSpecificationsAll")
retval := types.RecordSpecificationsAllResponse{Request: req}
pageRequest := getPageRequest(req)
ctx := sdk.UnwrapSDKContext(c)
kvStore := ctx.KVStore(k.storeKey)
prefixStore := prefix.NewStore(kvStore, types.RecordSpecificationKeyPrefix)
pageRes, err := query.Paginate(prefixStore, pageRequest, func(key, value []byte) error {
var recordSpec types.RecordSpecification
vErr := recordSpec.Unmarshal(value)
if vErr == nil {
retval.RecordSpecifications = append(retval.RecordSpecifications, types.WrapRecordSpec(&recordSpec))
return nil
}
// Something's wrong. Let's do what we can to give indications of it.
var addr types.MetadataAddress
kErr := addr.Unmarshal(key)
if kErr == nil {
k.Logger(ctx).Error("failed to unmarshal record spec", "address", addr, "error", vErr)
retval.RecordSpecifications = append(retval.RecordSpecifications, types.WrapRecordSpecNotFound(addr))
} else {
k64 := b64.StdEncoding.EncodeToString(key)
k.Logger(ctx).Error("failed to unmarshal record spec key and value",
"key error", kErr, "value error", vErr, "key (base64)", k64)
retval.RecordSpecifications = append(retval.RecordSpecifications, &types.RecordSpecificationWrapper{})
}
return nil // Still want to move on to the next.
})
if err != nil {
return &retval, status.Error(codes.Unavailable, err.Error())
}
retval.Pagination = pageRes
return &retval, nil
}
func (k Keeper) OSLocatorParams(c context.Context, request *types.OSLocatorParamsRequest) (*types.OSLocatorParamsResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "OSLocatorParams")
ctx := sdk.UnwrapSDKContext(c)
var params types.OSLocatorParams
k.paramSpace.GetParamSet(ctx, ¶ms)
return &types.OSLocatorParamsResponse{Params: params, Request: request}, nil
}
func (k Keeper) OSLocator(c context.Context, request *types.OSLocatorRequest) (*types.OSLocatorResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "OSLocator")
if request == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.OSLocatorResponse{Request: request}
ctx := sdk.UnwrapSDKContext(c)
accAddr, err := sdk.AccAddressFromBech32(request.Owner)
if err != nil {
return &retval, types.ErrInvalidAddress
}
record, exists := k.GetOsLocatorRecord(ctx, accAddr)
if !exists {
return &retval, types.ErrAddressNotBound
}
retval.Locator = &record
return &retval, nil
}
func (k Keeper) OSLocatorsByURI(ctx context.Context, request *types.OSLocatorsByURIRequest) (*types.OSLocatorsByURIResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "OSLocatorsByURI")
retval := types.OSLocatorsByURIResponse{Request: request}
if request == nil {
return &retval, status.Error(codes.InvalidArgument, "empty request")
}
var sDec []byte
// rest request send in base64 encoded uri, using a URL-compatible base64 format.
if IsBase64(request.Uri) {
sDec, _ = b64.StdEncoding.DecodeString(request.Uri)
} else {
sDec = []byte(request.Uri)
}
uri, err := url.Parse(string(sDec))
if err != nil {
return &retval, err
}
uriStr := uri.String()
osLocatorStore := prefix.NewStore(sdk.UnwrapSDKContext(ctx).KVStore(k.storeKey), types.OSLocatorAddressKeyPrefix)
retval.Pagination, err = query.FilteredPaginate(osLocatorStore, request.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) {
record := types.ObjectStoreLocator{}
if rerr := k.cdc.Unmarshal(value, &record); rerr != nil {
return false, rerr
}
if record.LocatorUri != uriStr {
return false, nil
}
if accumulate {
retval.Locators = append(retval.Locators, record)
}
return true, nil
})
if err != nil {
return &retval, err
}
if len(retval.Locators) == 0 {
return &retval, types.ErrNoRecordsFound
}
return &retval, nil
}
func (k Keeper) OSLocatorsByScope(ctx context.Context, request *types.OSLocatorsByScopeRequest) (*types.OSLocatorsByScopeResponse, error) {
defer telemetry.MeasureSince(time.Now(), types.ModuleName, "query", "OSLocatorsByScope")
if request == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
retval := types.OSLocatorsByScopeResponse{Request: request}
ctxSDK := sdk.UnwrapSDKContext(ctx)
if request.ScopeId == "" {
return &retval, status.Error(codes.InvalidArgument, "scope id cannot be empty")
}
locators, err := k.GetOSLocatorByScope(ctxSDK, request.ScopeId)
if err != nil {
return &retval, status.Error(codes.InvalidArgument, err.Error())
}
retval.Locators = locators