Make deserialize error if input bytes not consumed

- Adjust tests in encodable.rs to account for this change
This commit is contained in:
Carl Dong 2018-08-14 16:13:52 -07:00
parent bf9c749b0c
commit 70203831d6
2 changed files with 13 additions and 5 deletions

View File

@ -468,11 +468,11 @@ mod tests {
#[test]
fn deserialize_int_test() {
// bool
assert_eq!(deserialize(&[58u8, 0]).ok(), Some(true));
assert!((deserialize(&[58u8, 0]) as Result<bool, _>).is_err());
assert_eq!(deserialize(&[58u8]).ok(), Some(true));
assert_eq!(deserialize(&[1u8]).ok(), Some(true));
assert_eq!(deserialize(&[0u8]).ok(), Some(false));
assert_eq!(deserialize(&[0u8, 1]).ok(), Some(false));
assert!((deserialize(&[0u8, 1]) as Result<bool, _>).is_err());
// u8
assert_eq!(deserialize(&[58u8]).ok(), Some(58u8));
@ -510,7 +510,7 @@ mod tests {
#[test]
fn deserialize_vec_test() {
assert_eq!(deserialize(&[3u8, 2, 3, 4]).ok(), Some(vec![2u8, 3, 4]));
assert_eq!(deserialize(&[4u8, 2, 3, 4, 5, 6]).ok(), Some(vec![2u8, 3, 4, 5]));
assert!((deserialize(&[4u8, 2, 3, 4, 5, 6]) as Result<Vec<u8>, _>).is_err());
// found by cargo fuzz
assert!(deserialize::<Vec<u64>>(&[0xff,0xff,0xff,0xff,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0x6b,0xa,0xa,0x3a]).is_err());
}

View File

@ -57,12 +57,20 @@ pub fn serialize_hex<T: ?Sized>(data: &T) -> Result<String, util::Error>
Ok(hex_encode(serial))
}
/// Deserialize an object from a vector
/// Deserialize an object from a vector, will error if said deserialization
/// doesn't consume the entire vector.
pub fn deserialize<'a, T>(data: &'a [u8]) -> Result<T, util::Error>
where T: ConsensusDecodable<RawDecoder<Cursor<&'a [u8]>>>
{
let mut decoder = RawDecoder::new(Cursor::new(data));
ConsensusDecodable::consensus_decode(&mut decoder)
let rv = ConsensusDecodable::consensus_decode(&mut decoder)?;
// Fail if data is not consumed entirely.
if decoder.into_inner().position() == data.len() as u64 {
Ok(rv)
} else {
Err(util::Error::ParseFailed)
}
}
/// An encoder for raw binary data