Access control with OpenZeppelin in Blockchain / Solidity - Time & Space Complexity
When using OpenZeppelin's access control, we want to know how the cost of checking permissions grows as more roles or users are added.
We ask: How does the time to verify access change with input size?
Analyze the time complexity of the following Solidity code using OpenZeppelin's AccessControl.
contract MyContract is AccessControl {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
function restrictedAction() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Access denied");
// action code here
}
}
This code checks if the caller has the ADMIN_ROLE before allowing an action.
Look at what repeats when checking access.
- Primary operation: Checking if an address has a role in a mapping.
- How many times: Once per call to
restrictedAction.
The check looks up a role in a mapping, which stays fast even if many users or roles exist.
| Input Size (number of roles/users) | Approx. Operations |
|---|---|
| 10 | 1 lookup |
| 100 | 1 lookup |
| 1000 | 1 lookup |
Pattern observation: The time to check access stays about the same no matter how many roles or users there are.
Time Complexity: O(1)
This means checking access takes the same amount of time regardless of how many roles or users exist.
[X] Wrong: "Checking access gets slower as more users or roles are added."
[OK] Correct: The role check uses a direct mapping lookup, which is constant time no matter the size.
Understanding how access control checks scale helps you design secure and efficient smart contracts, a key skill in blockchain development.
What if the contract checked multiple roles in a loop? How would the time complexity change?