lines
  • Rust Security

Rust Security: Integer Over/Underflow

rust-security-header-1mb

Integer Overflow

Integer overflow occurs when the result of an arithmetic operation is larger than the maximum value that can be represented by the integer type. In Rust, this can happen when using the +, -, *, or / operators, as well as some other operations like shift_left and rotate_left. By default, Rust does not check for integer overflow, and will simply wrap around to the lowest possible value if an overflow occurs. For example:

let x: u8 = 255;
let y: u8 = 1;
let z = x + y;
println!("{} + {} = {}", x, y, z); // Output: "255 + 1 = 0" 
In this example, the z variable should have a value of 256, but because a u8 can only represent values from 0 to 255, the result wraps around to 0. This can lead to unexpected behavior and potential vulnerabilities if not handled properly.


Integer Underflow

Integer underflow occurs when the result of an arithmetic operation is smaller than the minimum value that can be represented by the integer type. In Rust, this can happen when using the - or / operators. Like integer overflow, Rust does not check for integer underflow by default, and will simply wrap around to the highest possible value if an underflow occurs. For example:

let x: i8 = -128; 
let y: i8 = 1; 
let z = x - y; 
println!("{} - {} = {}", x, y, z); // Output: "-128 - 1 = 127" 
In this example, the z variable should have a value of -129, but because an i8 can only represent values from -128 to 127, the result wraps around to 127. This can also lead to unexpected behavior and potential vulnerabilities if not handled properly.


Handling Integer Overflow and Underflow

To handle integer overflow and underflow in Rust, you can use the safe math(checked_*) functions provided by the num_traits crate. These functions return a None value if an overflow or underflow occurs, allowing you to handle the error explicitly. For example, here's how you can use the checked_add function to handle integer overflow:

use std::num::Wrapping;
use std::num::checked_add;
let x: u8 = 255; 
let y: u8 = 1; 
match checked_add(x, y)
 {
 Some(z) => println!("{} + {} = {}", x, y, z),
  None => println!("Overflow occurred"), 
}

Let us help you safely launch your NFT project