Skip to content

Commit

Permalink
parsing blobs as either hex, of comma-separated decimal lists
Browse files Browse the repository at this point in the history
  • Loading branch information
vbar committed Mar 18, 2024
1 parent 7e37172 commit 6c21352
Showing 1 changed file with 49 additions and 12 deletions.
61 changes: 49 additions & 12 deletions state-reconstruct-fetcher/src/types/v3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,18 +197,7 @@ async fn get_blob(
Ok(response) => match response.text().await {
Ok(text) => match get_blob_data(&text) {
Ok(data) => {
let plain = if let Some(p) = data.strip_prefix("0x") {
p
} else {
&data
};
match hex::decode(plain) {
Ok(bytes) => return Ok(bytes),
Err(e) => {
tracing::warn!("Cannot parse {}: {:?}", plain, e);
return Err(ParseError::BlobFormatError("not hex".to_string()));
}
}
return parse_blob_data(&data);
}
Err(e) => {
tracing::error!("failed parsing response of {url}");
Expand Down Expand Up @@ -258,3 +247,51 @@ fn get_blob_data(json_str: &str) -> Result<String, ParseError> {
Err(ParseError::BlobFormatError("not JSON".to_string()))
}
}

fn parse_blob_data(value_str: &str) -> Result<Vec<u8>, ParseError> {
if let Some(plain) = value_str.strip_prefix("0x") {
match hex::decode(plain) {
Ok(bytes) => Ok(bytes),
Err(e) => {
tracing::warn!("Cannot parse {}: {:?}", plain, e);
Err(ParseError::BlobFormatError("not hex".to_string()))
}
}
} else {
// assume comma-separated decimal bytes; arguably there's
// nothing stopping the server from using hexadecimals with a
// separator, but that format hadn't been seen yet
let mut a = Vec::new();
for s in value_str.split(',') {
match s.parse::<u8>() {
Ok(c) => {
a.push(c);
}
Err(e) => {
tracing::warn!("Cannot parse {} in {}: {:?}", s, value_str, e);
return Err(ParseError::BlobFormatError("not byte".to_string()));
}
}
}
Ok(a)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_parse_blob_data() {
let value_str = "87,104,179,182,167,219,86,210,29,26,191,244,13,65";

match parse_blob_data(value_str) {
Ok(a) => {
assert_eq!(a.len(), 14);
}
Err(e) => {
panic!("parsing failed: {:?}", e);
}
}
}
}

0 comments on commit 6c21352

Please sign in to comment.