Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion rust/tw_evm/src/abi/param_type/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,31 @@ use crate::abi::{AbiError, AbiErrorKind, AbiResult};
use std::str::FromStr;
use tw_coin_entry::error::prelude::*;

const MAX_RECURSION_DEPTH: usize = 20;

pub struct Reader;

impl Reader {
/// Doesn't accept tuple types with specified parameters, e.g `(uint32, address)`.
pub fn parse_type<T: TypeConstructor>(s: &str) -> AbiResult<T> {
Self::parse_type_step(s, 0)
}

/// Doesn't accept tuple types with specified parameters, e.g `(uint32, address)`.
pub fn parse_type_step<T: TypeConstructor>(s: &str, current_depth: usize) -> AbiResult<T> {
if current_depth > MAX_RECURSION_DEPTH {
return AbiError::err(AbiErrorKind::Error_invalid_param_type)
.with_context(|| format!("Max recursion depth exceeded: {MAX_RECURSION_DEPTH}"));
}

// Array
if let Some(remaining) = s.strip_suffix(']') {
let Some((element_type_str, len_str)) = remaining.rsplit_once('[') else {
return AbiError::err(AbiErrorKind::Error_invalid_param_type)
.with_context(|| format!("Invalid array type: {s}"));
};

let element_type = Reader::parse_type::<T>(element_type_str)
let element_type = Reader::parse_type_step::<T>(element_type_str, current_depth + 1)
.with_context(|| format!("Error parsing inner array type: {element_type_str}"))?;
if let Some(len) = parse_len(len_str)
.with_context(|| format!("Error parsing fixed_array length: {len_str}"))?
Expand Down Expand Up @@ -113,3 +125,25 @@ fn parse_usize(usize_str: &str) -> AbiResult<Option<usize>> {
.tw_err(AbiErrorKind::Error_invalid_param_type)
.with_context(|| format!("Expected a decimal string: {usize_str}"))
}

#[cfg(test)]
mod tests {
use super::*;
use crate::abi::param_type::ParamType;

#[test]
fn test_parse_type_recursion() {
let depth = MAX_RECURSION_DEPTH;
let mut ty = "uint256".to_string();

// Append exactly MAX_RECURSION_DEPTH array brackets that must be allowed.
for _ in 0..depth {
ty.push_str("[]");
}
ParamType::try_from_type_short(&ty).expect("Should parse within recursion limit");

// Append one more array bracket to exceed the limit.
ty.push_str("[]");
ParamType::try_from_type_short(&ty).expect_err("Recursion limit exceeded");
}
}
Loading