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

Chore: Replace Hex Encoding/Decoding #4465

Draft
wants to merge 3 commits into
base: next
Choose a base branch
from
Draft
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
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions stacks-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ path = "./src/libcommon.rs"

[dependencies]
rand = { workspace = true }
faster-hex = "0.9.0"
serde = "1"
serde_derive = "1"
serde_stacker = "0.1"
Expand Down
31 changes: 6 additions & 25 deletions stacks-common/src/util/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use std::char::from_digit;
use std::fmt::Write;
use std::{fmt, mem};

use crate::util::faster_hex::{hex_decode, hex_string};
use ripemd::Ripemd160;
use serde::de::{Deserialize, Error as de_Error};
use serde::ser::Error as ser_Error;
Expand Down Expand Up @@ -587,26 +588,10 @@ where
}
}

// borrowed from Andrew Poelstra's rust-bitcoin library
/// Convert a hexadecimal-encoded string to its corresponding bytes
pub fn hex_bytes(s: &str) -> Result<Vec<u8>, HexError> {
let mut v = vec![];
let mut iter = s.chars().pair();
// Do the parsing
iter.by_ref()
.try_fold((), |_, (f, s)| match (f.to_digit(16), s.to_digit(16)) {
(None, _) => Err(HexError::BadCharacter(f)),
(_, None) => Err(HexError::BadCharacter(s)),
(Some(f), Some(s)) => {
v.push((f * 0x10 + s) as u8);
Ok(())
}
})?;
// Check that there was no remainder
match iter.remainder() {
Some(_) => Err(HexError::BadLength(s.len())),
None => Ok(v),
}
pub fn hex_bytes(s: &str) -> Result<Vec<u8>, faster_hex::Error> {
let mut bytes = vec![0u8; s.len() / 2];
hex_decode(s.as_bytes(), &mut bytes)?;
Ok(bytes)
}

/// Convert a binary-encoded string to its corresponding bytes
Expand Down Expand Up @@ -634,11 +619,7 @@ pub fn bin_bytes(s: &str) -> Result<Vec<u8>, HexError> {

/// Convert a slice of u8 to a hex string
pub fn to_hex(s: &[u8]) -> String {
let mut r = String::with_capacity(s.len() * 2);
for b in s.iter() {
write!(r, "{:02x}", b).unwrap();
}
r
hex_string(s)
}

/// Convert a slice of u8 into a binary string
Expand Down
6 changes: 4 additions & 2 deletions stacks-common/src/util/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,13 +446,15 @@ macro_rules! impl_byte_array_newtype {
impl $thing {
/// Instantiates from a hex string
#[allow(dead_code)]
pub fn from_hex(hex_str: &str) -> Result<$thing, $crate::util::HexError> {
pub fn from_hex(hex_str: &str) -> Result<$thing, crate::util::faster_hex::Error> {
use $crate::util::hash::hex_bytes;
let _hex_len = $len * 2;
match (hex_str.len(), hex_bytes(hex_str)) {
(_hex_len, Ok(bytes)) => {
if bytes.len() != $len {
return Err($crate::util::HexError::BadLength(hex_str.len()));
return Err(crate::util::faster_hex::Error::InvalidLength(
hex_str.len(),
));
}
let mut ret = [0; $len];
ret.copy_from_slice(&bytes);
Expand Down
2 changes: 2 additions & 0 deletions stacks-common/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

pub extern crate faster_hex;

#[macro_use]
pub mod log;
#[macro_use]
Expand Down
6 changes: 6 additions & 0 deletions stackslib/src/blockstack_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,12 @@ impl From<stacks_common::util::HexError> for CliError {
}
}

impl From<stacks_common::util::faster_hex::Error> for CliError {
fn from(value: stacks_common::util::faster_hex::Error) -> Self {
CliError::Message(format!("Bad hex string supplied: {}", value))
}
}

impl From<clarity::vm::types::serialization::SerializationError> for CliError {
fn from(value: clarity::vm::types::serialization::SerializationError) -> Self {
CliError::Message(format!("Failed to deserialize: {}", value))
Expand Down