Access control patterns in Blockchain / Solidity - Time & Space Complexity
When we control who can do what in a blockchain, we use access control patterns. It's important to know how the cost of checking permissions grows as more users or roles are added.
We want to find out how the time to check access changes when the number of users or roles increases.
Analyze the time complexity of the following access control check in a smart contract.
mapping(address => bool) public admins;
function isAdmin(address user) public view returns (bool) {
return admins[user];
}
function addAdmin(address user) public {
require(admins[msg.sender], "Not authorized");
admins[user] = true;
}
This code checks if a user is an admin by looking up a mapping, and allows existing admins to add new admins.
Look for repeated actions that affect time cost.
- Primary operation: Accessing the mapping to check if a user is an admin.
- How many times: Each time the function is called, the mapping is accessed once.
The time to check if a user is an admin stays about the same no matter how many admins exist.
| Input Size (number of admins) | Approx. Operations |
|---|---|
| 10 | 1 mapping lookup |
| 100 | 1 mapping lookup |
| 1000 | 1 mapping lookup |
Pattern observation: The operation count stays constant even as the number of admins grows.
Time Complexity: O(1)
This means checking access takes the same amount of time no matter how many users or roles there are.
[X] Wrong: "Checking if a user is an admin takes longer as more admins are added."
[OK] Correct: The mapping lookup is direct and does not depend on the number of admins, so the time stays constant.
Understanding how access control checks scale helps you design efficient smart contracts that stay fast as they grow. This skill shows you can think about real-world blockchain performance.
"What if we stored admins in a list instead of a mapping? How would the time complexity change?"