From 8dbb80604d95ae51d8ee87b21cf7e0880e90486a Mon Sep 17 00:00:00 2001 From: Paolo Barbolini Date: Tue, 9 Apr 2024 09:29:23 +0200 Subject: [PATCH] Fix broken CRC handling Signed-off-by: Paolo Barbolini --- src/crc.rs | 26 ++++++++++++++++++++++++-- src/lib.rs | 23 +++++++++-------------- 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/crc.rs b/src/crc.rs index 07d8bd2..2f501a8 100644 --- a/src/crc.rs +++ b/src/crc.rs @@ -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) { @@ -54,7 +54,29 @@ pub(crate) fn extract_crc(data: &mut Vec) -> Result { ) })?; - 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)); + } +} diff --git a/src/lib.rs b/src/lib.rs index d4b2937..2c27f1f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -452,7 +452,7 @@ 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 { @@ -460,20 +460,15 @@ mod tests { } } - /* - * 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() {