Skip to content

Commit

Permalink
error on extra input when deserializing Union[None] for some SSZ un…
Browse files Browse the repository at this point in the history
…ion type
  • Loading branch information
ralexstokes committed Jun 27, 2023
1 parent b872969 commit 39d1bb7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
10 changes: 9 additions & 1 deletion ssz-rs-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,15 @@ fn derive_deserialize_impl(data: &Data) -> TokenStream {
}
Fields::Unit => {
quote_spanned! { variant.span() =>
0 => Ok(Self::None),
0 => {
if encoding.len() != 1 {
return Err(DeserializeError::AdditionalInput {
provided: encoding.len(),
expected: 1,
})
}
Ok(Self::None)
},
}
}
_ => unreachable!(),
Expand Down
22 changes: 21 additions & 1 deletion ssz-rs/src/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::{
/// None,
/// Some(T),
/// }
/// The SSZ schema for this value would be `Union[None, T]`.
impl<T: SimpleSerialize> Sized for Option<T> {
fn is_variable_size() -> bool {
true
Expand Down Expand Up @@ -49,7 +50,15 @@ where

// SAFETY: index is safe because encoding is not empty; qed
match encoding[0] {
0 => Ok(None),
0 => {

Check warning on line 53 in ssz-rs/src/union.rs

View check run for this annotation

Codecov / codecov/patch

ssz-rs/src/union.rs#L53

Added line #L53 was not covered by tests
if encoding.len() != 1 {
return Err(DeserializeError::AdditionalInput {
provided: encoding.len(),
expected: 1,
})
}
Ok(None)

Check warning on line 60 in ssz-rs/src/union.rs

View check run for this annotation

Codecov / codecov/patch

ssz-rs/src/union.rs#L60

Added line #L60 was not covered by tests
}
1 => {
// SAFETY: index is safe because encoding is not empty; qed
let inner = T::deserialize(&encoding[1..])?;
Expand Down Expand Up @@ -170,6 +179,17 @@ mod tests {
assert_eq!(x, recovered);
}

#[test]
fn test_options_with_extra_input() {
let buffer = vec![0u8, 123, 234];
let result = Option::<u8>::deserialize(&buffer);
assert!(matches!(result, Err(DeserializeError::AdditionalInput { .. })));

let buffer = vec![0u8, 123, 234];
let result = AnotherOption::deserialize(&buffer);
assert!(matches!(result, Err(DeserializeError::AdditionalInput { .. })));
}

#[test]
fn test_another_option() {
let mut x = AnotherOption::A(12u8);
Expand Down

0 comments on commit 39d1bb7

Please sign in to comment.