Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix unchecked indexing in decode_hex #1218

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
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
30 changes: 26 additions & 4 deletions core-primitives/utils/src/hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,12 @@ pub fn hex_encode(data: &[u8]) -> String {

/// Helper method for decoding hex.
pub fn decode_hex<T: AsRef<[u8]>>(message: T) -> Result<Vec<u8>> {
let mut message = message.as_ref();
if message[..2] == [b'0', b'x'] {
message = &message[2..]
}
let message = message.as_ref();
let message = match message {
[b'0', b'x', hex_value @ ..] => hex_value,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, I actually never saw this pattern before!

_ => message,
};

let decoded_message = hex::decode(message).map_err(Error::Hex)?;
Ok(decoded_message)
}
Expand All @@ -80,6 +82,26 @@ mod tests {
assert_eq!(data, decoded_data);
}

#[test]
fn hex_encode_decode_works_empty_input() {
let data = String::new();

let hex_encoded_data = hex_encode(&data.encode());
let decoded_data =
String::decode(&mut decode_hex(hex_encoded_data).unwrap().as_slice()).unwrap();

assert_eq!(data, decoded_data);
}

#[test]
fn hex_encode_decode_works_empty_input_for_decode() {
let data = String::new();

let decoded_data = decode_hex(&data).unwrap();

assert!(decoded_data.is_empty());
}

#[test]
fn to_hex_from_hex_works() {
let data = "Hello World!".to_string();
Expand Down
2 changes: 1 addition & 1 deletion sidechain/consensus/common/src/is_descendant_of_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ where
// If the current hash is the head and the parent is the base, then we know that
// this current hash is the descendant of the parent. Otherwise we can set the
// head to the parent and find the lowest common ancestor between `head`
/// and `base` in the tree.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀

// and `base` in the tree.
if current_hash == head {
if current_parent_hash == base {
return Ok(true)
Expand Down