Skip to content

Commit

Permalink
Fix broken CRC handling
Browse files Browse the repository at this point in the history
Signed-off-by: Paolo Barbolini <[email protected]>
  • Loading branch information
paolobarbolini authored and brooksmtownsend committed Apr 10, 2024
1 parent 333844d commit 8dbb806
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 16 deletions.
26 changes: 24 additions & 2 deletions src/crc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub(crate) fn crc16(data: &[u8]) -> u16 {
}

pub(crate) fn valid_checksum(data: &[u8], expected: u16) -> bool {
crc16(data) != expected
crc16(data) == expected
}

pub(crate) fn push_crc(data: &mut Vec<u8>) {
Expand All @@ -54,7 +54,29 @@ pub(crate) fn extract_crc(data: &mut Vec<u8>) -> Result<u16> {
)
})?;

let crc = u16::from_le_bytes(data[..2].try_into().unwrap());
let crc = u16::from_le_bytes(data[data_len..].try_into().unwrap());
data.truncate(data_len);
Ok(crc)
}

#[cfg(test)]
mod tests {
use super::{crc16, extract_crc, push_crc, valid_checksum};

#[test]
fn e2e() {
let mut raw_data = rand::random::<[u8; 32]>();
let data_crc = crc16(&raw_data);

let mut data = raw_data.to_vec();
push_crc(&mut data);

let crc = extract_crc(&mut data).unwrap();
assert_eq!(raw_data, data.as_slice());
assert_eq!(data_crc, crc);
assert!(valid_checksum(&raw_data, data_crc));

raw_data[17] = raw_data[17].wrapping_sub(1);
assert!(!valid_checksum(&raw_data, data_crc));
}
}
23 changes: 9 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -452,28 +452,23 @@ mod tests {

#[test]
fn from_seed_rejects_bad_prefix() {
let seed = "FAAPN4W3EG6KCJGUQTKTJ5GSB5NHK5CHAJL4DBGFUM3HHROI4XUEP4OBK4";
let seed = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
let pair = KeyPair::from_seed(seed);
assert!(pair.is_err());
if let Err(e) = pair {
assert_eq!(e.kind(), ErrorKind::InvalidPrefix);
}
}

/*
* TODO - uncomment this test when I can figure out how to encode a bad checksum
* without first triggering a base32 decoding failure :)
#[test]
fn from_seed_rejects_bad_checksum() {
let seed = "SAAPN4W3EG6KCJGUQTKTJ5GSB5NHK5CHAJL4DBGFUM3HHROI4XUEP4OBK4";
let pair = KeyPair::from_seed(seed);
assert!(pair.is_err());
if let Err(e) = pair {
assert_eq!(e.kind(), ErrorKind::ChecksumFailure);
}
#[test]
fn from_seed_rejects_bad_checksum() {
let seed = "FAAPN4W3EG6KCJGUQTKTJ5GSB5NHK5CHAJL4DBGFUM3HHROI4XUEP4OBK4";
let pair = KeyPair::from_seed(seed);
assert!(pair.is_err());
if let Err(e) = pair {
assert_eq!(e.kind(), ErrorKind::ChecksumFailure);
}
*/
}

#[test]
fn from_seed_rejects_bad_length() {
Expand Down

0 comments on commit 8dbb806

Please sign in to comment.