-
Notifications
You must be signed in to change notification settings - Fork 36
/
scope.go
553 lines (498 loc) · 18.4 KB
/
scope.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
package keeper
import (
"fmt"
"github.com/gogo/protobuf/proto"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/provenance-io/provenance/x/metadata/types"
)
// IterateScopes processes all stored scopes with the given handler.
func (k Keeper) IterateScopes(ctx sdk.Context, handler func(types.Scope) (stop bool)) error {
store := ctx.KVStore(k.storeKey)
it := sdk.KVStorePrefixIterator(store, types.ScopeKeyPrefix)
defer it.Close()
for ; it.Valid(); it.Next() {
var scope types.Scope
k.cdc.MustUnmarshal(it.Value(), &scope)
if handler(scope) {
break
}
}
return nil
}
// IterateScopesForAddress processes scopes associated with the provided address with the given handler.
func (k Keeper) IterateScopesForAddress(ctx sdk.Context, address sdk.AccAddress, handler func(scopeID types.MetadataAddress) (stop bool)) error {
store := ctx.KVStore(k.storeKey)
prefix := types.GetAddressScopeCacheIteratorPrefix(address)
it := sdk.KVStorePrefixIterator(store, prefix)
defer it.Close()
for ; it.Valid(); it.Next() {
var scopeID types.MetadataAddress
if err := scopeID.Unmarshal(it.Key()[len(prefix):]); err != nil {
return err
}
if handler(scopeID) {
break
}
}
return nil
}
// IterateScopesForScopeSpec processes scopes associated with the provided scope specification id with the given handler.
func (k Keeper) IterateScopesForScopeSpec(ctx sdk.Context, scopeSpecID types.MetadataAddress,
handler func(scopeID types.MetadataAddress) (stop bool),
) error {
store := ctx.KVStore(k.storeKey)
prefix := types.GetScopeSpecScopeCacheIteratorPrefix(scopeSpecID)
it := sdk.KVStorePrefixIterator(store, prefix)
defer it.Close()
for ; it.Valid(); it.Next() {
var scopeID types.MetadataAddress
if err := scopeID.Unmarshal(it.Key()[len(prefix):]); err != nil {
return err
}
if handler(scopeID) {
break
}
}
return nil
}
// GetScope returns the scope with the given id.
func (k Keeper) GetScope(ctx sdk.Context, id types.MetadataAddress) (scope types.Scope, found bool) {
if !id.IsScopeAddress() {
return scope, false
}
store := ctx.KVStore(k.storeKey)
b := store.Get(id.Bytes())
if b == nil {
return types.Scope{}, false
}
k.cdc.MustUnmarshal(b, &scope)
return scope, true
}
// SetScope stores a scope in the module kv store.
func (k Keeper) SetScope(ctx sdk.Context, scope types.Scope) {
store := ctx.KVStore(k.storeKey)
b := k.cdc.MustMarshal(&scope)
var oldScope *types.Scope
var event proto.Message = types.NewEventScopeCreated(scope.ScopeId)
action := types.TLAction_Created
if store.Has(scope.ScopeId) {
event = types.NewEventScopeUpdated(scope.ScopeId)
action = types.TLAction_Updated
if oldScopeBytes := store.Get(scope.ScopeId); oldScopeBytes != nil {
oldScope = &types.Scope{}
if err := k.cdc.Unmarshal(oldScopeBytes, oldScope); err != nil {
k.Logger(ctx).Error("could not unmarshal old scope", "err", err, "scopeId", scope.ScopeId.String(), "oldScopeBytes", oldScopeBytes)
oldScope = nil
}
}
}
store.Set(scope.ScopeId, b)
k.indexScope(ctx, &scope, oldScope)
k.EmitEvent(ctx, event)
defer types.GetIncObjFunc(types.TLType_Scope, action)
}
// RemoveScope removes a scope from the module kv store along with all its records and sessions.
func (k Keeper) RemoveScope(ctx sdk.Context, id types.MetadataAddress) {
if !id.IsScopeAddress() {
panic(fmt.Errorf("invalid address, address must be for a scope"))
}
// iterate and remove all records, groups
store := ctx.KVStore(k.storeKey)
scope, found := k.GetScope(ctx, id)
if !found {
return
}
// Remove all records
prefix, err := id.ScopeRecordIteratorPrefix()
if err != nil {
panic(err)
}
iter := sdk.KVStorePrefixIterator(store, prefix)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
k.RemoveRecord(ctx, iter.Key())
}
// Sessions will be removed as the last record in each is deleted.
k.indexScope(ctx, nil, &scope)
store.Delete(id)
k.EmitEvent(ctx, types.NewEventScopeDeleted(scope.ScopeId))
defer types.GetIncObjFunc(types.TLType_Scope, types.TLAction_Deleted)
}
// scopeIndexValues is a struct containing the values used to index a scope.
type scopeIndexValues struct {
ScopeID types.MetadataAddress
Addresses []string
ValueOwner string
SpecificationID types.MetadataAddress
}
// getScopeIndexValues extracts the values used to index a scope.
func getScopeIndexValues(scope *types.Scope) *scopeIndexValues {
if scope == nil {
return nil
}
rv := scopeIndexValues{
ScopeID: scope.ScopeId,
ValueOwner: scope.ValueOwnerAddress,
SpecificationID: scope.SpecificationId,
}
rv.Addresses = append(rv.Addresses, scope.DataAccess...)
for _, p := range scope.Owners {
rv.Addresses = appendIfNew(rv.Addresses, p.Address)
}
if len(scope.ValueOwnerAddress) > 0 {
rv.Addresses = appendIfNew(rv.Addresses, scope.ValueOwnerAddress)
}
return &rv
}
// appendIfNew appends a string to a string slice if it's not already in the string slice.
func appendIfNew(vals []string, val string) []string {
for _, v := range vals {
if v == val {
return vals
}
}
return append(vals, val)
}
// getMissingScopeIndexValues extracts the index values in the required set that are not in the found set.
func getMissingScopeIndexValues(required, found *scopeIndexValues) scopeIndexValues {
rv := scopeIndexValues{}
if required == nil {
return rv
}
if found == nil {
return *required
}
rv.ScopeID = required.ScopeID
rv.Addresses = findMissing(required.Addresses, found.Addresses)
if required.ValueOwner != found.ValueOwner {
rv.ValueOwner = required.ValueOwner
}
if !required.SpecificationID.Equals(found.SpecificationID) {
rv.SpecificationID = required.SpecificationID
}
return rv
}
// IndexKeys creates all of the index key byte arrays that this scopeIndexValues represents.
func (v scopeIndexValues) IndexKeys() [][]byte {
rv := make([][]byte, 0)
if v.ScopeID.Empty() {
return rv
}
for _, addrStr := range v.Addresses {
if addr, err := sdk.AccAddressFromBech32(addrStr); err == nil {
rv = append(rv, types.GetAddressScopeCacheKey(addr, v.ScopeID))
}
}
if len(v.ValueOwner) > 0 {
if addr, err := sdk.AccAddressFromBech32(v.ValueOwner); err == nil {
rv = append(rv, types.GetValueOwnerScopeCacheKey(addr, v.ScopeID))
}
}
if !v.SpecificationID.Empty() {
rv = append(rv, types.GetScopeSpecScopeCacheKey(v.SpecificationID, v.ScopeID))
}
return rv
}
// indexScope updates the index entries for a scope.
//
// When adding a new scope: indexScope(ctx, scope, nil)
//
// When deleting a scope: indexScope(ctx, nil, scope)
//
// When updating a scope: indexScope(ctx, newScope, oldScope)
//
// If both newScope and oldScope are not nil, it is assumed that they have the same ScopeId.
// Failure to meet this assumption will result in strange and bad behavior.
func (k Keeper) indexScope(ctx sdk.Context, newScope, oldScope *types.Scope) {
if newScope == nil && oldScope == nil {
return
}
newScopeIndexValues := getScopeIndexValues(newScope)
oldScopeIndexValues := getScopeIndexValues(oldScope)
toAdd := getMissingScopeIndexValues(newScopeIndexValues, oldScopeIndexValues)
toRemove := getMissingScopeIndexValues(oldScopeIndexValues, newScopeIndexValues)
store := ctx.KVStore(k.storeKey)
for _, indexKey := range toAdd.IndexKeys() {
store.Set(indexKey, []byte{0x01})
}
for _, indexKey := range toRemove.IndexKeys() {
store.Delete(indexKey)
}
}
// ValidateWriteScope checks the current scope and the proposed scope to determine if the proposed changes are valid
// based on the existing state
func (k Keeper) ValidateWriteScope(
ctx sdk.Context,
existing *types.Scope,
msg *types.MsgWriteScopeRequest,
) error {
proposed := msg.Scope
if err := proposed.ValidateBasic(); err != nil {
return err
}
// IDs must match
if existing != nil {
if !proposed.ScopeId.Equals(existing.ScopeId) {
return fmt.Errorf("cannot update scope identifier. expected %s, got %s", existing.ScopeId, proposed.ScopeId)
}
}
if err := proposed.SpecificationId.Validate(); err != nil {
return fmt.Errorf("invalid specification id: %w", err)
}
if !proposed.SpecificationId.IsScopeSpecificationAddress() {
return fmt.Errorf("invalid specification id: is not scope specification id: %s", proposed.SpecificationId)
}
scopeSpec, found := k.GetScopeSpecification(ctx, proposed.SpecificationId)
if !found {
return fmt.Errorf("scope specification %s not found", proposed.SpecificationId)
}
// Existing owners are not required to sign when the ONLY change is from one value owner to another.
// If the value owner wasn't previously set, and is being set now, existing owners must sign.
// If anything else is changing, the existing owners must sign.
existingValueOwner := ""
onlyChangeIsValueOwner := false
if existing != nil && len(existing.ValueOwnerAddress) > 0 {
existingValueOwner = existing.ValueOwnerAddress
// Make a copy of proposed scope and set its value owner to the existing one. If it then
// equals the existing scope, then the only change in proposed is to the value owner field.
proposedCopy := proposed
proposedCopy.ValueOwnerAddress = existing.ValueOwnerAddress
onlyChangeIsValueOwner = existing.Equals(proposedCopy)
}
var err error
var validatedParties []*PartyDetails
if err = validateRolesPresent(proposed.Owners, scopeSpec.PartiesInvolved); err != nil {
return err
}
if err = k.validateProvenanceRole(ctx, BuildPartyDetails(nil, proposed.Owners)); err != nil {
return err
}
if !onlyChangeIsValueOwner {
// Make sure everyone has signed.
if (existing != nil && !existing.RequirePartyRollup) || (existing == nil && !proposed.RequirePartyRollup) {
// Old:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all existing owners must sign.
// - Value owner signer restrictions are applied.
if existing != nil && !existing.Equals(proposed) {
if validatedParties, err = k.validateAllRequiredSigned(ctx, existing.GetAllOwnerAddresses(), msg); err != nil {
return err
}
}
} else {
// New:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all required=false existing owners must be signers.
// - If not new, all roles required by the scope spec must have a signer and
// associated party from the existing scope.
// - Value owner signer restrictions are applied.
// Note: This means that a scope can be initially written without consideration for signers and roles.
if existing != nil {
if validatedParties, err = k.validateAllRequiredPartiesSigned(ctx, existing.Owners, existing.Owners, scopeSpec.PartiesInvolved, msg); err != nil {
return err
}
}
}
}
usedSigners, err := k.ValidateScopeValueOwnerUpdate(ctx, existingValueOwner, proposed.ValueOwnerAddress, validatedParties, msg)
if err != nil {
return err
}
if err = k.validateSmartContractSigners(ctx, usedSigners, msg); err != nil {
return err
}
return nil
}
// ValidateDeleteScope checks the current scope and the proposed removal scope to determine if the proposed remove is valid
// based on the existing state
func (k Keeper) ValidateDeleteScope(ctx sdk.Context, msg *types.MsgDeleteScopeRequest) error {
scope, found := k.GetScope(ctx, msg.ScopeId)
if !found {
return fmt.Errorf("scope not found with id %s", msg.ScopeId)
}
var err error
var validatedParties []*PartyDetails
// Make sure everyone has signed.
if !scope.RequirePartyRollup {
// Old:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all existing owners must sign.
// - Value owner signer restrictions are applied.
// We don't care about the first one here.
if validatedParties, err = k.validateAllRequiredSigned(ctx, scope.GetAllOwnerAddresses(), msg); err != nil {
return err
}
} else {
// New:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all required=false existing owners must be signers.
// - If not new, all roles required by the scope spec must have a signer and
// associated party from the existing scope.
// - Value owner signer restrictions are applied.
// We don't care about that first one, and only care about the roles one if the spec exists.
scopeSpec, found := k.GetScopeSpecification(ctx, scope.SpecificationId)
if !found {
if validatedParties, err = k.validateAllRequiredSigned(ctx, types.GetRequiredPartyAddresses(scope.Owners), msg); err != nil {
return err
}
} else {
if validatedParties, err = k.validateAllRequiredPartiesSigned(ctx, scope.Owners, scope.Owners, scopeSpec.PartiesInvolved, msg); err != nil {
return err
}
}
}
usedSigners, err := k.ValidateScopeValueOwnerUpdate(ctx, scope.ValueOwnerAddress, "", validatedParties, msg)
if err != nil {
return err
}
if err = k.validateSmartContractSigners(ctx, usedSigners, msg); err != nil {
return err
}
return nil
}
// ValidateAddScopeDataAccess checks the current scope and the proposed
func (k Keeper) ValidateAddScopeDataAccess(
ctx sdk.Context,
existing types.Scope,
msg *types.MsgAddScopeDataAccessRequest,
) error {
if len(msg.DataAccess) < 1 {
return fmt.Errorf("data access list cannot be empty")
}
for _, da := range msg.DataAccess {
_, err := sdk.AccAddressFromBech32(da)
if err != nil {
return fmt.Errorf("failed to decode data access address %s : %w", da, err)
}
for _, eda := range existing.DataAccess {
if da == eda {
return fmt.Errorf("address already exists for data access %s", eda)
}
}
}
// Make sure everyone has signed.
if !existing.RequirePartyRollup {
// Old:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all existing owners must sign.
// - Value owner signer restrictions are applied.
// We don't care about the first one here since owners aren't changing.
// We don't care about the value owner check either since it's not changing.
if err := k.ValidateSignersWithoutParties(ctx, existing.GetAllOwnerAddresses(), msg); err != nil {
return err
}
} else {
// New:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all required=false existing owners must be signers.
// - If not new, all roles required by the scope spec must have a signer and
// associated party from the existing scope.
// - Value owner signer restrictions are applied.
// We don't care about the first one here since owners aren't changing.
// We don't care about the value owner check either since it's not changing.
scopeSpec, found := k.GetScopeSpecification(ctx, existing.SpecificationId)
if !found {
return fmt.Errorf("scope specification %s not found", existing.SpecificationId)
}
if err := k.ValidateSignersWithParties(ctx, existing.Owners, existing.Owners, scopeSpec.PartiesInvolved, msg); err != nil {
return err
}
}
return nil
}
// ValidateDeleteScopeDataAccess checks the current scope data access and the proposed removed items
func (k Keeper) ValidateDeleteScopeDataAccess(
ctx sdk.Context,
existing types.Scope,
msg *types.MsgDeleteScopeDataAccessRequest,
) error {
if len(msg.DataAccess) < 1 {
return fmt.Errorf("data access list cannot be empty")
}
dataAccessLoop:
for _, da := range msg.DataAccess {
for _, eda := range existing.DataAccess {
if da == eda {
continue dataAccessLoop
}
}
return fmt.Errorf("address does not exist in scope data access: %s", da)
}
// Make sure everyone has signed.
if !existing.RequirePartyRollup {
// Old:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all existing owners must sign.
// - Value owner signer restrictions are applied.
// We don't care about the first one here since owners aren't changing.
// We don't care about the value owner check either since it's not changing.
if err := k.ValidateSignersWithoutParties(ctx, existing.GetAllOwnerAddresses(), msg); err != nil {
return err
}
} else {
// New:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all required=false existing owners must be signers.
// - If not new, all roles required by the scope spec must have a signer and
// associated party from the existing scope.
// - Value owner signer restrictions are applied.
// We don't care about the first one here since owners aren't changing.
// We don't care about the value owner check either since it's not changing.
scopeSpec, found := k.GetScopeSpecification(ctx, existing.SpecificationId)
if !found {
return fmt.Errorf("scope specification %s not found", existing.SpecificationId)
}
if err := k.ValidateSignersWithParties(ctx, existing.Owners, existing.Owners, scopeSpec.PartiesInvolved, msg); err != nil {
return err
}
}
return nil
}
// ValidateUpdateScopeOwners checks the current scopes owners and the proposed update
func (k Keeper) ValidateUpdateScopeOwners(
ctx sdk.Context,
existing,
proposed types.Scope,
msg types.MetadataMsg,
) error {
if err := proposed.ValidateOwnersBasic(); err != nil {
return err
}
scopeSpec, found := k.GetScopeSpecification(ctx, proposed.SpecificationId)
if !found {
return fmt.Errorf("scope specification %s not found", proposed.SpecificationId)
}
if err := validateRolesPresent(proposed.Owners, scopeSpec.PartiesInvolved); err != nil {
return err
}
if err := k.validateProvenanceRole(ctx, BuildPartyDetails(nil, proposed.Owners)); err != nil {
return err
}
// Make sure everyone has signed.
if !existing.RequirePartyRollup {
// Old:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all existing owners must sign.
// - Value owner signer restrictions are applied.
// The value owner isn't changing so we don't care about that one.
if err := k.ValidateSignersWithoutParties(ctx, existing.GetAllOwnerAddresses(), msg); err != nil {
return err
}
} else {
// New:
// - All roles required by the scope spec must have a party in the owners.
// - If not new, all required=false existing owners must be signers.
// - If not new, all roles required by the scope spec must have a signer and
// associated party from the existing scope.
// - Value owner signer restrictions are applied.
// The value owner isn't changing so we don't care about that one.
validatedParties, err := k.validateAllRequiredPartiesSigned(ctx, existing.Owners, existing.Owners, scopeSpec.PartiesInvolved, msg)
if err != nil {
return err
}
if err = k.validateSmartContractSigners(ctx, GetAllSigners(validatedParties), msg); err != nil {
return err
}
}
return nil
}