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
use super::*;
use frame_support::pallet_prelude::*;
//use frame_system::pallet_prelude::*;
use frame_support::{sp_io::hashing::blake2_256, sp_std::borrow::ToOwned};
use sp_runtime::sp_std::vec::Vec;

use crate::types::*;

impl<T: Config> RoleBasedAccessControl<T::AccountId> for Pallet<T> {
  /*---- Basic Insertion of individual storage maps ---*/
  /// Scope creation
  ///
  /// Creates a scope within a external pallet using the pallet index.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `scope_id`: The newly generated scope identifier.
  fn create_scope(pallet: IdOrVec, scope_id: ScopeId) -> DispatchResult {
    let pallet_id = pallet.to_id();
    <Scopes<T>>::try_mutate(pallet_id, |scopes| {
      ensure!(!scopes.contains(&scope_id), Error::<T>::ScopeAlreadyExists);
      scopes.try_push(scope_id).map_err(|_| Error::<T>::ExceedMaxScopesPerPallet)?;
      Ok(())
    })
  }

  /// Scope removal
  ///
  /// Removes a scope within a external pallet using the pallet index.
  /// Executing this function will delete all registered role users.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `scope_id`: The scope identifier to remove.
  fn remove_scope(pallet: IdOrVec, scope_id: ScopeId) -> DispatchResult {
    let pallet_id = pallet.to_id();
    // remove on scopes
    <Scopes<T>>::try_mutate_exists::<_, (), DispatchError, _>(pallet_id, |scopes_option| {
      let scopes = scopes_option.as_mut().ok_or(Error::<T>::ScopeNotFound)?;
      let s_pos = scopes.iter().position(|&s| s == scope_id).ok_or(Error::<T>::ScopeNotFound)?;
      scopes.remove(s_pos);
      if scopes.is_empty() {
        scopes_option.clone_from(&None);
      }
      Ok(())
    })?;
    let mut scope_users = <UsersByScope<T>>::iter_prefix((pallet_id, scope_id))
      .flat_map(|(_role, users)| users)
      .collect::<Vec<_>>();
    // exclude duplicate users
    scope_users.sort();
    scope_users.dedup();
    // remove on RolesByUser
    scope_users.iter().for_each(|user| {
      <RolesByUser<T>>::remove((user, pallet_id, scope_id));
    });
    // remove on users by scope
    let _ = <UsersByScope<T>>::clear_prefix((pallet_id, scope_id), 1000, None);

    Ok(())
  }

  /// External pallet storage removal
  ///
  /// Removes all storage associated to a external pallet.
  ///
  /// Executing this function will delete all role lists and permissions linked
  /// to that pallet.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  fn remove_pallet_storage(pallet: IdOrVec) -> DispatchResult {
    let pallet_id_enum = pallet.to_id_enum();
    let pallet_id = pallet_id_enum.to_id();
    //remove all scopes
    let scopes = <Scopes<T>>::get(pallet_id);
    for scope in scopes {
      Self::remove_scope(pallet_id_enum.clone(), scope)?;
    }
    // remove all roles
    let pallet_roles = <PalletRoles<T>>::take(pallet_id);
    //check if there's other pallet that uses the roles, if not, remove them
    let all_pallet_roles =
      <PalletRoles<T>>::iter().map(|p| p.1.to_vec()).collect::<Vec<Vec<[u8; 32]>>>();
    let flatten_all_pallet_roles = all_pallet_roles.iter().flatten().collect::<Vec<&[u8; 32]>>();
    let filtered_roles = pallet_roles
      .iter()
      .filter(|pallet_role| !flatten_all_pallet_roles.contains(pallet_role));
    filtered_roles.for_each(|role| {
      <Roles<T>>::remove(role);
    });
    //remove all permissions
    let _ = <PermissionsByRole<T>>::clear_prefix(pallet_id, 1000, None);
    let _ = <Permissions<T>>::clear_prefix(pallet_id, 1000, None);
    Ok(())
  }

  /// Role creation and coupling with pallet.
  ///
  /// Creates the specified roles if needed and adds them to the pallet.
  /// Recommended first step to enable RBAC on a external pallet.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `roles`: A list of roles to create, encoded in bytes.
  fn create_and_set_roles(
    pallet: IdOrVec,
    roles: Vec<Vec<u8>>,
  ) -> Result<BoundedVec<RoleId, T::MaxRolesPerPallet>, DispatchError> {
    let mut role_ids = Vec::<[u8; 32]>::new();
    for role in roles {
      role_ids.push(Self::create_role(role.to_owned())?);
    }
    Self::set_multiple_pallet_roles(pallet.to_id_enum(), role_ids.clone())?;
    let bounded_ids = Self::bound(role_ids, Error::<T>::ExceedMaxRolesPerPallet)?;
    Self::deposit_event(Event::RolesStored(pallet.to_id(), bounded_ids.clone()));
    Ok(bounded_ids)
  }

  /// Role creation.
  ///
  /// Creates a role and returns its identifier, if its already created,
  /// the function will return the preexisting one.
  /// ### Parameters:
  /// - `role`: A role to create, encoded in bytes.
  fn create_role(role: Vec<u8>) -> Result<RoleId, DispatchError> {
    let role_id = role.using_encoded(blake2_256);
    // no "get_or_insert" method found
    let b_role = Self::bound::<_, T::RoleMaxLen>(role, Error::<T>::ExceedRoleMaxLen)?;
    ensure!(role_id == b_role.using_encoded(blake2_256), Error::<T>::NoneValue);
    if !<Roles<T>>::contains_key(role_id) {
      <Roles<T>>::insert(role_id, b_role)
    };
    Ok(role_id)
  }

  /// Role coupling with pallet.
  ///
  /// Assigns a previously created role to a pallet.
  ///
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `role_id`: The unique role identifier.
  fn set_role_to_pallet(pallet: IdOrVec, role_id: RoleId) -> DispatchResult {
    ensure!(<Roles<T>>::contains_key(role_id), Error::<T>::RoleNotFound);
    <PalletRoles<T>>::try_mutate(pallet.to_id(), |roles| {
      ensure!(!roles.contains(&role_id), Error::<T>::RoleAlreadyLinkedToPallet);
      roles.try_push(role_id).map_err(|_| Error::<T>::ExceedMaxRolesPerPallet)
    })?;
    Ok(())
  }

  /// Multiple role coupling with pallet.
  ///
  /// Assigns multiple, previously created roles to a pallet.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `roles`: A list of unique role identifiers.
  fn set_multiple_pallet_roles(pallet: IdOrVec, roles: Vec<RoleId>) -> DispatchResult {
    let pallet_id = pallet.to_id();
    // checks for duplicates:
    ensure!(Self::has_unique_elements(roles.clone()), Error::<T>::DuplicateRole);
    let pallet_roles = <PalletRoles<T>>::get(&pallet_id);
    for id in roles.clone() {
      ensure!(!pallet_roles.contains(&id), Error::<T>::RoleAlreadyLinkedToPallet);
    }
    <PalletRoles<T>>::try_mutate(pallet_id, |pallet_roles| {
      pallet_roles.try_extend(roles.into_iter())
    })
    .map_err(|_| Error::<T>::ExceedMaxRolesPerPallet)?;

    Ok(())
  }

  /// Role assignation to a user
  ///
  /// Assigns a role to a user in a scope context.
  /// ### Parameters:
  /// - `user`: The account which the role will be granted.
  /// - `pallet_id`: The unique pallet identifier.
  /// - `scope_id`: The scope in which the role will be granted.
  /// - `role_id`: The role identifier to grant for the user.
  fn assign_role_to_user(
    user: T::AccountId,
    pallet: IdOrVec,
    scope_id: &ScopeId,
    role_id: RoleId,
  ) -> DispatchResult {
    let pallet_id_enum = pallet.to_id_enum();
    let pallet_id = pallet_id_enum.to_id();
    Self::scope_exists(pallet_id_enum.clone(), scope_id)?;
    Self::is_role_linked_to_pallet(pallet_id_enum, &role_id)?;
    <RolesByUser<T>>::try_mutate((&user, pallet_id, scope_id), |roles| {
      ensure!(!roles.contains(&role_id), Error::<T>::UserAlreadyHasRole);
      roles.try_push(role_id).map_err(|_| Error::<T>::ExceedMaxRolesPerUser)
    })?;

    <UsersByScope<T>>::try_mutate((pallet_id, scope_id, role_id), |users| {
      ensure!(!users.contains(&user), Error::<T>::UserAlreadyHasRole);
      users.try_push(user.clone()).map_err(|_| Error::<T>::ExceedMaxUsersPerRole)
    })?;
    Self::deposit_event(Event::RoleAssignedToUser(pallet_id, scope_id.to_owned(), role_id, user));
    Ok(())
  }

  /// Role removal from the user.
  ///
  /// Removes the specified role from a user in a scope context. the user will no longer
  /// be able to enforce the removed role and its permissions.
  /// ### Parameters:
  /// - `user`: The account which the role will be removed.
  /// - `pallet_id`: The unique pallet identifier.
  /// - `scope_id`: The scope in which the role will be removed.
  /// - `role_id`: The role identifier to remove from the user.
  fn remove_role_from_user(
    user: T::AccountId,
    pallet: IdOrVec,
    scope_id: &ScopeId,
    role_id: RoleId,
  ) -> DispatchResult {
    let pallet_id = pallet.to_id();
    <RolesByUser<T>>::try_mutate_exists::<_, (), DispatchError, _>(
      (user.clone(), pallet_id, scope_id),
      |user_roles_option| {
        let user_roles = user_roles_option.as_mut().ok_or(Error::<T>::UserHasNoRoles)?;
        let r_pos =
          user_roles.iter().position(|&r| r == role_id).ok_or(Error::<T>::RoleNotFound)?;
        user_roles.remove(r_pos);
        if user_roles.is_empty() {
          user_roles_option.clone_from(&None)
        }
        Ok(())
      },
    )?;
    <UsersByScope<T>>::try_mutate_exists::<_, (), DispatchError, _>(
      (pallet_id, scope_id, role_id),
      |auth_users_option| {
        let auth_users = auth_users_option.as_mut().ok_or(Error::<T>::RoleHasNoUsers)?;
        let u_pos = auth_users.iter().position(|u| *u == user).ok_or(Error::<T>::UserNotFound)?;
        auth_users.remove(u_pos);
        if auth_users.is_empty() {
          auth_users_option.clone_from(&None);
        }
        Ok(())
      },
    )?;
    Self::deposit_event(Event::RoleRemovedFromUser(pallet_id, scope_id.to_owned(), role_id, user));
    Ok(())
  }

  /// Permission creation and coupling with a role.
  ///
  /// Creates the specified permissions if needed and assigns them to a role.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `role_id`: The role identifier to which the permissions will
  /// be linked to.
  /// - `permissions`: A list of permissions to create and link,
  /// encoded in bytes.
  fn create_and_set_permissions(
    pallet: IdOrVec,
    role_id: RoleId,
    permissions: Vec<Vec<u8>>,
  ) -> Result<BoundedVec<PermissionId, Self::MaxPermissionsPerRole>, DispatchError> {
    ensure!(Self::has_unique_elements(permissions.clone()), Error::<T>::DuplicatePermission);
    let pallet_id_enum = pallet.to_id_enum();
    Self::is_role_linked_to_pallet(pallet_id_enum.clone(), &role_id)?;
    let mut permission_ids = Vec::<[u8; 32]>::new();
    for permission in permissions {
      permission_ids.push(Self::create_permission(pallet_id_enum.clone(), permission.to_owned())?);
    }
    Self::set_multiple_permissions_to_role(pallet_id_enum, role_id, permission_ids.clone())?;
    let b_permissions = Self::bound(permission_ids, Error::<T>::ExceedMaxPermissionsPerRole)?;
    Self::deposit_event(Event::PermissionsCreatedAndSet(
      pallet.to_id(),
      role_id,
      b_permissions.clone(),
    ));
    Ok(b_permissions)
  }

  /// Permission creation
  ///
  /// Creates the specified permission in the specified pallet..
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `permission`: The permission to insert, encoded in bytes.
  fn create_permission(
    pallet: IdOrVec,
    permission: Vec<u8>,
  ) -> Result<PermissionId, DispatchError> {
    let permission_id = Self::to_id(permission.clone());
    let pallet_id = pallet.to_id();

    let b_permission =
      Self::bound::<_, T::PermissionMaxLen>(permission, Error::<T>::ExceedPermissionMaxLen)?;

    if !<Permissions<T>>::contains_key(pallet_id, permission_id) {
      <Permissions<T>>::insert(pallet_id, permission_id, b_permission);
    }
    Ok(permission_id)
  }

  /// Permission linking to role.
  ///
  /// Assigns a previously created permission to a role.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `role_id`: The role identifier to which the permission will be added.
  /// - `permission_id`: The permission to assign to the role.
  fn set_permission_to_role(
    pallet: IdOrVec,
    role_id: RoleId,
    permission_id: PermissionId,
  ) -> DispatchResult {
    let pallet_id_enum = pallet.to_id_enum();
    let pallet_id = pallet_id_enum.to_id();
    Self::is_role_linked_to_pallet(pallet_id_enum, &role_id)?;

    ensure!(
      <Permissions<T>>::contains_key(pallet_id, permission_id),
      Error::<T>::PermissionNotFound
    );

    <PermissionsByRole<T>>::try_mutate(pallet_id, role_id, |role_permissions| {
      ensure!(!role_permissions.contains(&permission_id), Error::<T>::DuplicatePermission);
      role_permissions
        .try_push(permission_id)
        .map_err(|_| Error::<T>::ExceedMaxPermissionsPerRole)
    })?;
    Ok(())
  }

  /// Multiple permissions assignation to a role
  ///
  /// Assigns multiple, previously created permissions
  /// to a role in a pallet context.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `role_id`: The role identifier to which the permissions will be added.
  /// - `permissions`: A list of permission identifiers to assign to the role.
  fn set_multiple_permissions_to_role(
    pallet: IdOrVec,
    role_id: RoleId,
    permissions: Vec<PermissionId>,
  ) -> DispatchResult {
    // checks for duplicates:
    ensure!(Self::has_unique_elements(permissions.clone()), Error::<T>::DuplicatePermission);
    let pallet_id_enum = pallet.to_id_enum();
    let pallet_id = pallet_id_enum.to_id();
    Self::is_role_linked_to_pallet(pallet_id_enum, &role_id)?;

    let role_permissions = <PermissionsByRole<T>>::get(&pallet_id, role_id);
    for id in permissions.clone() {
      ensure!(!role_permissions.contains(&id), Error::<T>::PermissionAlreadyLinkedToRole);
    }
    <PermissionsByRole<T>>::try_mutate(pallet_id, role_id, |role_permissions| {
      role_permissions.try_extend(permissions.into_iter())
    })
    .map_err(|_| Error::<T>::ExceedMaxPermissionsPerRole)?;
    Ok(())
  }

  /// Permission revocation from role
  ///
  /// Remove a permission linked to a role (in a pallet context).
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `role_id`: The role identifier to which the permissions will be removed from.
  /// - `permission_id`: The permission to deassign.
  fn do_revoke_permission_from_role(
    pallet: IdOrVec,
    role_id: RoleId,
    permission_id: PermissionId,
  ) -> DispatchResult {
    Self::permission_exists(pallet.clone(), &permission_id)?;
    Self::is_role_linked_to_pallet(pallet.clone(), &role_id)?;
    Self::is_permission_linked_to_role(pallet.clone(), &role_id, &permission_id)?;
    <PermissionsByRole<T>>::try_mutate::<_, _, _, DispatchError, _>(
      pallet.to_id(),
      role_id,
      |role_permissions| {
        let p_index = role_permissions
          .iter()
          .position(|&p| p == permission_id)
          .ok_or(Error::<T>::PermissionNotLinkedToRole)?;
        role_permissions.remove(p_index);
        Ok(())
      },
    )?;
    Self::deposit_event(Event::PermissionRevokedFromRole(pallet.to_id(), role_id, permission_id));
    Ok(())
  }

  /// Permission removal from pallet
  ///
  /// Use with caution. The permission will be deleted from all the roles and pallet.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `permission_id`: The permission to remove completely.
  fn do_remove_permission_from_pallet(pallet: IdOrVec, permission: PermissionId) -> DispatchResult {
    Self::permission_exists(pallet.clone(), &permission)?;
    let pallet_id = pallet.to_id();
    // find all the roles that have the permission
    let affected_roles: Vec<RoleId> = Self::get_roles_that_have_permission(pallet_id, &permission);
    // remove the permission from all affected roles
    affected_roles.iter().for_each(|role| {
      <PermissionsByRole<T>>::mutate(pallet_id, role, |permissions| {
        permissions.retain(|&p| p != permission)
      })
    });
    // remove the permission from the pallet
    <Permissions<T>>::remove(pallet_id, permission);
    Self::deposit_event(Event::PermissionRemovedFromPallet(
      pallet_id,
      permission,
      Self::bound(affected_roles, Error::<T>::ExceedMaxRolesPerPallet)?, // this bound should never fail
    ));
    Ok(())
  }

  /*---- Helper functions ----*/

  /// Authorization function
  ///
  /// Checks if the user has a role that includes the specified permission.
  /// ### Parameters:
  /// - `user`: The account to validate.
  /// - `pallet_id`: The unique pallet identifier.
  /// - `scope_id`: The scope context in which the permission will be validated.
  /// - `permission_id`: The permission the user must have.
  fn is_authorized(
    user: T::AccountId,
    pallet: IdOrVec,
    scope_id: &ScopeId,
    permission_id: &PermissionId,
  ) -> DispatchResult {
    let pallet_id_enum = pallet.to_id_enum();
    let pallet_id = pallet_id_enum.to_id();
    Self::scope_exists(pallet_id_enum.clone(), scope_id)?;
    Self::permission_exists(pallet_id_enum, permission_id)?;
    // get roles the user has in this scope
    let user_roles = <RolesByUser<T>>::get((user, pallet_id, scope_id));
    // determine if one of the roles has the requested permission
    let has_permission = user_roles
      .iter()
      .any(|r_id| <PermissionsByRole<T>>::get(pallet_id, r_id).contains(permission_id));
    ensure!(has_permission, Error::<T>::NotAuthorized);
    Ok(())
  }

  /// User role validation function
  ///
  /// Checks if the user has at least one of the specified roles.
  /// ### Parameters:
  /// - `user`: The account to validate.
  /// - `pallet_id`: The unique pallet identifier.
  /// - `scope_id`: The scope context in which the permission will be validated.
  /// - `role_ids`: A list of roles to validate.
  fn has_role(
    user: T::AccountId,
    pallet: IdOrVec,
    scope_id: &ScopeId,
    role_ids: Vec<RoleId>,
  ) -> DispatchResult {
    let pallet_id_enum = pallet.to_id_enum();
    Self::scope_exists(pallet_id_enum.clone(), scope_id)?;
    let user_roles = <RolesByUser<T>>::get((user, pallet_id_enum.to_id(), scope_id));
    ensure!(user_roles.iter().any(|r| role_ids.contains(r)), Error::<T>::NotAuthorized);
    Ok(())
  }
  /// User any-role validation function
  ///
  /// Checks if the user has at least one role in the given scope.
  /// ### Parameters:
  /// - `user`: The account to validate.
  /// - `pallet_id`: The unique pallet identifier.
  /// - `scope_id`: The scope context in which the role will be validated.
  fn does_user_have_any_role_in_scope(
    account: T::AccountId,
    pallet: IdOrVec,
    scope_id: &ScopeId,
  ) -> bool {
    let pallet_id = pallet.to_id();
    UsersByScope::<T>::iter_prefix((pallet_id, scope_id)).any(|(_, users)| users.contains(&account))
  }
  /// Scope validation
  ///
  /// Checks if the scope exists in that pallet.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `scope_id`: The scope to validate.
  fn scope_exists(pallet: IdOrVec, scope_id: &ScopeId) -> DispatchResult {
    ensure!(<Scopes<T>>::get(pallet.to_id()).contains(scope_id), Error::<T>::ScopeNotFound);
    Ok(())
  }

  /// Permission validation.
  ///
  /// Checks if the permission exists in a pallet context.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `permission_id`: The permission to validate.
  fn permission_exists(pallet: IdOrVec, permission_id: &PermissionId) -> DispatchResult {
    ensure!(
      <Permissions<T>>::contains_key(pallet.to_id(), permission_id),
      Error::<T>::PermissionNotFound
    );
    Ok(())
  }

  /// Role validation
  ///
  /// Checks if the role is linked to the pallet.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `role_id`: The role to validate
  fn is_role_linked_to_pallet(pallet: IdOrVec, role_id: &RoleId) -> DispatchResult {
    // The role exists, now  check if the role is assigned to that pallet
    <PalletRoles<T>>::get(pallet.to_id())
      .iter()
      .find(|pallet_role| *pallet_role == role_id)
      .ok_or(Error::<T>::RoleNotLinkedToPallet)?;
    Ok(())
  }

  /// Permission linking validation
  ///
  /// Checks if the permission is linked to the role in the pallet context.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `role_id`: The role which should have the permission.
  /// - `permission_id`: The permission which the role should have.
  fn is_permission_linked_to_role(
    pallet: IdOrVec,
    role_id: &RoleId,
    permission_id: &PermissionId,
  ) -> DispatchResult {
    let role_permissions = <PermissionsByRole<T>>::get(pallet.to_id(), role_id);
    ensure!(role_permissions.contains(permission_id), Error::<T>::PermissionNotLinkedToRole);
    Ok(())
  }

  /// Get roles that have a permission
  ///
  /// Returns all the roles within the pallet that have a permission
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `permission_id`: The permission which the roles should have.
  fn get_roles_that_have_permission(
    pallet_id: PalletId,
    permission_id: &PermissionId,
  ) -> Vec<RoleId> {
    <PermissionsByRole<T>>::iter_prefix(pallet_id)
      .filter_map(|(role, permissions)| permissions.contains(permission_id).then(|| role))
      .collect()
  }

  /// Role list length
  ///
  /// Returns the number of user that have the specified role in a scope context.
  /// ### Parameters:
  /// - `pallet_id`: The unique pallet identifier.
  /// - `scope_id`: The scope in which the users will be retrieved.
  /// - `role_id`: The role in which the number of users will be counted.
  fn get_role_users_len(pallet: IdOrVec, scope_id: &ScopeId, role_id: &RoleId) -> usize {
    <UsersByScope<T>>::get((pallet.to_id(), scope_id, role_id)).len()
  }

  fn to_id(v: Vec<u8>) -> [u8; 32] {
    v.using_encoded(blake2_256)
  }

  fn get_roles_by_user(user: T::AccountId, pallet: IdOrVec, scope_id: &ScopeId) -> Vec<RoleId> {
    <RolesByUser<T>>::get((user, pallet.to_id(), scope_id)).into()
  }

  type MaxRolesPerPallet = T::MaxRolesPerPallet;

  type MaxPermissionsPerRole = T::MaxPermissionsPerRole;

  type PermissionMaxLen = T::PermissionMaxLen;

  type RoleMaxLen = T::RoleMaxLen;
}

impl<T: Config> Pallet<T> {
  fn bound<E, Len: Get<u32>>(vec: Vec<E>, err: Error<T>) -> Result<BoundedVec<E, Len>, Error<T>> {
    BoundedVec::<E, Len>::try_from(vec).map_err(|_| err)
  }

  fn has_unique_elements<E: Ord + Clone>(vec: Vec<E>) -> bool {
    let mut filtered_vec = vec.clone();
    filtered_vec.sort();
    filtered_vec.dedup();
    vec.len() == filtered_vec.len()
  }
}