Forbid negative len

This commit is contained in:
Ludo Galabru
2020-08-06 22:35:28 -04:00
parent dc6b52da39
commit 3d4a57d42e
3 changed files with 45 additions and 0 deletions

View File

@@ -15,6 +15,7 @@ pub enum CheckErrors {
MemoryBalanceExceeded(u64, u64),
ValueTooLarge,
ValueOutOfBounds,
TypeSignatureTooDeep,
ExpectedName,
@@ -290,6 +291,7 @@ impl DiagnosableError for CheckErrors {
CheckErrors::BadSyntaxExpectedListOfPairs => "bad syntax: function expects a list of pairs to bind names, e.g., ((name-0 a) (name-1 b) ...)".into(),
CheckErrors::UnknownTypeName(name) => format!("failed to parse type: '{}'", name),
CheckErrors::ValueTooLarge => format!("created a type which was greater than maximum allowed value size"),
CheckErrors::ValueOutOfBounds => format!("created a type which value size was out of defined bounds"),
CheckErrors::TypeSignatureTooDeep => "created a type which was deeper than maximum allowed type depth".into(),
CheckErrors::ExpectedName => format!("expected a name argument to this function"),
CheckErrors::NoSuperType(a, b) => format!("unable to create a supertype for the two types: '{}' and '{}'", a, b),

View File

@@ -1798,3 +1798,42 @@ fn test_string_utf8_concat() {
assert_eq!(expected, &format!("{}", type_check_helper(&good_test).unwrap()));
}
}
#[test]
fn test_buff_negative_len() {
let contract_src =
"(define-private (func (x (buff -12))) (len x))
(func 0x00)";
let res = mem_type_check(&contract_src).unwrap_err();
assert!(match &res.err {
&CheckErrors::BadSyntaxBinding => true,
_ => false
});
}
#[test]
fn test_string_ascii_negative_len() {
let contract_src =
"(define-private (func (x (string-ascii -12))) (len x))
(func \"\")";
let res = mem_type_check(&contract_src).unwrap_err();
assert!(match &res.err {
&CheckErrors::BadSyntaxBinding => true,
_ => false
});
}
#[test]
fn test_string_utf8_negative_len() {
let contract_src =
"(define-private (func (x (string-utf8 -12))) (len x))
(func u\"\")";
let res = mem_type_check(&contract_src).unwrap_err();
assert!(match &res.err {
&CheckErrors::BadSyntaxBinding => true,
_ => false
});
}

View File

@@ -212,6 +212,8 @@ impl TryFrom<i128> for BufferLength {
fn try_from(data: i128) -> Result<BufferLength> {
if data > (MAX_VALUE_SIZE as i128) {
Err(CheckErrors::ValueTooLarge)
} else if data < 0 {
Err(CheckErrors::ValueOutOfBounds)
} else {
Ok(BufferLength(data as u32))
}
@@ -257,6 +259,8 @@ impl TryFrom<i128> for StringUTF8Length {
fn try_from(data: i128) -> Result<StringUTF8Length> {
if data * 4 > (MAX_VALUE_SIZE as i128) {
Err(CheckErrors::ValueTooLarge)
} else if data < 0 {
Err(CheckErrors::ValueOutOfBounds)
} else {
Ok(StringUTF8Length(data as u32))
}