Skip to main content

Iterators over indexing

Description

Iterating with hardcoded indexes is slower than using an iterator. Also, if the index is out of bounds, it will panic.

Exploit Scenario

Consider the following ink! contract:

    #[ink(message)]
pub fn bad_indexing(&self){
for i in 0..3 {
foo(self.value[i]);
}
}

The problem arises from the use of hardcoded indexes. If self.value has less than 4 elements, the contract will panic.

The vulnerable code example can be found here.

Remediation

Avoid the use of hardcoded indexes. Instead, use iter(), to_iter(), for ... in ... or range over 0..value.len()

The remediated code example can be found here.

References