|
| 1 | +# Namespace Storage Variable Collsion |
| 2 | + |
| 3 | +In Cairo, it is possible to use namespaces to scope functions under an identifier. However, storage variables are not scoped by these namespaces. If a developer accidentally uses the same variable name in two different namespaces, it could lead to a storage collision. |
| 4 | + |
| 5 | +# Example |
| 6 | + |
| 7 | +The following example has been copied from [here](https://gist.github.com/koloz193/18cb491167e844e9a28ac69825f68975). Suppose we have two different namespaces `A` and `B`, both with the same `balance` storage variable. In addition, both namespaces have respective functions `increase_balance()` and `get_balance()` to increment the storage variable and retrieve it respectively. When either `increase_balance_a` or `increase_balance_b()` is called, the expected behavior would be to have two seperate storage variables have their balance increased respectively. However, because storage variables are not scoped by namespaces, there will be one `balance` variable updated twice: |
| 8 | + |
| 9 | +```cairo |
| 10 | +%lang starknet |
| 11 | +
|
| 12 | +from starkware.cairo.common.cairo_builtins import HashBuiltin |
| 13 | +
|
| 14 | +from openzeppelin.a import A |
| 15 | +from openzeppelin.b import B |
| 16 | +
|
| 17 | +@external |
| 18 | +func increase_balance_a{ |
| 19 | + syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, |
| 20 | + range_check_ptr}(amount : felt): |
| 21 | + A.increase_balance(amount) |
| 22 | + return () |
| 23 | +end |
| 24 | +
|
| 25 | +@external |
| 26 | +func increase_balance_b{ |
| 27 | + syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, |
| 28 | + range_check_ptr}(amount : felt): |
| 29 | + B.increase_balance(amount) |
| 30 | + return () |
| 31 | +end |
| 32 | +
|
| 33 | +@view |
| 34 | +func get_balance_a{ |
| 35 | + syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, |
| 36 | + range_check_ptr}() -> (res : felt): |
| 37 | + let (res) = A.get_balance() |
| 38 | + return (res) |
| 39 | +end |
| 40 | +
|
| 41 | +@view |
| 42 | +func get_balance_b{ |
| 43 | + syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, |
| 44 | + range_check_ptr}() -> (res : felt): |
| 45 | + let (res) = B.get_balance() |
| 46 | + return (res) |
| 47 | +end |
| 48 | +``` |
| 49 | + |
| 50 | +# Mitigations |
| 51 | + |
| 52 | +Make sure to not use the same storage variable name in the namespace (or change the return value's name, see [here](https://github.com/crytic/amarna/issues/10)). Also use [Amarna](https://github.com/crytic/amarna) to uncover this issue, since it has a detector for storage variable collisions. |
0 commit comments