In my previous post, I demonstrated how an unbounded loop could lead to a 9.8M Gas DoS on Starknet. Today, I’m sharing the follow-up: how I mitigated this vulnerability and fixed a critical logic flaw—Duplicate Token Registration.
🛡️ The Second Vulnerability: Identity Crisis
While testing the Gas DoS, I realized the contract lacked a basic check: it didn't verify if a token was already registered. An attacker could spam the same token address 500 times, inflating the loop size with zero effort and minimal cost.
🛠️ The Fix: Implementing a Registration Map
To solve this, I introduced a Map to track unique assets. In Cairo, using a LegacyMap (or the modern Map) is the most gas-efficient way to handle identity checks.
Updated Contract Logic:
Rust
[storage]
struct Storage {
btc_tokens: Map,
btc_tokens_count: u32,
token_registered: Map, // New tracking map
}
fn add_btc_token(ref self: ContractState, token: ContractAddress) {
// 1. Validation: Prevent duplicate entries
let is_registered = self.token_registered.read(token);
assert(!is_registered, 'Token already registered');
// 2. State update
let count = self.btc_tokens_count.read();
self.btc_tokens.write(count, token);
self.btc_tokens_count.write(count + 1);
// 3. Mark as registered
self.token_registered.write(token, true);
}
✅ Verification with Snforge
Security is nothing without proof. I used snforge to write a specialized test case that expects a panic when a duplicate is added.
Rust
[test]
[should_panic(expected: ('Token already registered', ))]
fn test_duplicate_token_registration() {
// ... setup ...
dispatcher.add_btc_token(token_address);
dispatcher.add_btc_token(token_address); // This must fail
}
Results:
All 4/4 security tests passed.
The "Gas Bomb" can no longer be created using duplicate addresses.
Codebase refactored to modern Cairo syntax (removing core:: internal calls).
🧠 Key Takeaway for Auditors
When auditing loops, always look for the entry point. Preventing the "inflation" of data at the storage level is just as important as optimizing the loop itself.
Check out the full PoC and the fix on my GitHub: https://github.com/rdin777/starknet-staking_audit1

Top comments (0)