Skip to content

restrict STR0_255 to printable ASCII #2500

Open

Description

@plebhash

as noted on stratum-mining/sv2-spec#252 (review)


Str0255 is a bare alias of the generic byte container, no byte validation:

pub type Str0255<'a> = Inner<'a, false, 1, 1, 255>;
pub type Str0255Owned = InnerOwned<false, 1, 1, 255>;

as_utf8_or_hex, the fallback @bit-aloo quoted (both the borrowed and owned impls):

impl Str0255<'_> {
/// Returns the value as a UTF-8 string if possible, otherwise as a hex string prefixed with 0x.
pub fn as_utf8_or_hex(&self) -> String {
match core::str::from_utf8(self.as_bytes()) {
Ok(s) => alloc::string::String::from(s),
Err(_) => format!("0x{}", bytes_to_hex(self.as_bytes())),
}
}
}
impl Str0255Owned {
/// Returns the value as a UTF-8 string if possible, otherwise as a hex string prefixed with 0x.
pub fn as_utf8_or_hex(&self) -> String {
match core::str::from_utf8(self.as_bytes()) {
Ok(s) => alloc::string::String::from(s),
Err(_) => format!("0x{}", bytes_to_hex(self.as_bytes())),
}

TryFrom<&str> accepts any &str, so non-ASCII passes on the sending side too:

impl<'a> TryFrom<&'a str> for Str0255<'a> {
type Error = crate::Error;
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
value.as_bytes().try_into()
}
}

Extension 0x0002 UserIdentity: raw Vec<u8>, from_bytes checks length only, and as_str / as_string_or_hex carry the UTF-8 fallback:

pub struct UserIdentity {
/// UserIdentity as raw UTF-8 bytes (max 32 bytes).
///
/// The TLV Value field contains these raw bytes directly.
pub(crate) user_identity: Vec<u8>,
}
impl UserIdentity {
/// Creates a new UserIdentity from a string.
pub fn new(user_identity: &str) -> Result<Self, &'static str> {
Self::from_bytes(user_identity.as_bytes())
}
/// Creates a UserIdentity directly from raw bytes.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, &'static str> {
if bytes.len() > MAX_USER_IDENTITY_LENGTH {
return Err("UserIdentity exceeds 32 bytes");
}
Ok(Self {
user_identity: bytes.to_vec(),
})
}
/// Returns the UserIdentity as a string slice (if valid UTF-8).
#[inline]
pub fn as_str(&self) -> Option<&str> {
core::str::from_utf8(&self.user_identity).ok()
}
/// Returns the UserIdentity as a String (if valid UTF-8) or hex representation.
pub fn as_string_or_hex(&self) -> String {
match core::str::from_utf8(&self.user_identity) {
Ok(s) => s.to_string(),
Err(_) => {
let mut hex = String::from("0x");
for byte in &self.user_identity {
use core::fmt::Write;
let _ = write!(&mut hex, "{:02x}", byte);
}
hex
}
}
}


blocked by stratum-mining/sv2-spec#252

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions