Skip to content

Commit

Permalink
fix: make sure Multihashes are always valid
Browse files Browse the repository at this point in the history
When a Multihash is created, we make sure that the supplied code is supported,
hence part of the code table. Throw an error if a passed in multihash contains
an unsupported code.

Fixes #70.
  • Loading branch information
vmx committed Jul 16, 2020
1 parent 5072807 commit be17038
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/digests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,9 @@ impl<'a, T: TryFrom<u64>> MultihashRefGeneric<'a, T> {
return Err(DecodeError::BadInputLength);
}

let (_code, bytes) = varint_decode::u64(&input).map_err(|_| DecodeError::BadInputLength)?;
let (code, bytes) = varint_decode::u64(&input).map_err(|_| DecodeError::BadInputLength)?;
// Make sure it's a code that is part of the codec table
T::try_from(code).map_err(|_| DecodeError::UnknownCode)?;

let (hash_len, bytes) =
varint_decode::u64(&bytes).map_err(|_| DecodeError::BadInputLength)?;
Expand Down
8 changes: 8 additions & 0 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,14 @@ fn multihash_ref_errors() {
MultihashRef::from_slice(&[identity_code, identity_length, 1, 2, 3, 4]).is_err(),
"Should error on wrong hash length"
);

let unsupported_code = 0x04;
let hash_length = 3;
assert_eq!(
MultihashRef::from_slice(&[unsupported_code, hash_length, 1, 2, 3]),
Err(DecodeError::UnknownCode),
"Should error on codes that are not part of the code table"
);
}

#[test]
Expand Down

0 comments on commit be17038

Please sign in to comment.