Skip to content

Commit 0990d54

Browse files
authored
Merge pull request #73 from kinode-dao/dr/add-dnswire_decode
feat: add dnswire_decode function to net lib
2 parents ba4ac9e + 55a49f0 commit 0990d54

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/net.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,3 +122,41 @@ where
122122
valid
123123
})
124124
}
125+
126+
/// take a DNSwire-formatted node ID from chain and convert it to a String
127+
pub fn dnswire_decode(wire_format_bytes: &[u8]) -> Result<String, DnsDecodeError> {
128+
let mut i = 0;
129+
let mut result = Vec::new();
130+
131+
while i < wire_format_bytes.len() {
132+
let len = wire_format_bytes[i] as usize;
133+
if len == 0 {
134+
break;
135+
}
136+
let end = i + len + 1;
137+
let mut span = match wire_format_bytes.get(i + 1..end) {
138+
Some(span) => span.to_vec(),
139+
None => return Err(DnsDecodeError::FormatError),
140+
};
141+
span.push('.' as u8);
142+
result.push(span);
143+
i = end;
144+
}
145+
146+
let flat: Vec<_> = result.into_iter().flatten().collect();
147+
148+
let name = String::from_utf8(flat).map_err(|e| DnsDecodeError::Utf8Error(e))?;
149+
150+
// Remove the trailing '.' if it exists (it should always exist)
151+
if name.ends_with('.') {
152+
Ok(name[0..name.len() - 1].to_string())
153+
} else {
154+
Ok(name)
155+
}
156+
}
157+
158+
#[derive(Clone, Debug)]
159+
pub enum DnsDecodeError {
160+
Utf8Error(std::string::FromUtf8Error),
161+
FormatError,
162+
}

0 commit comments

Comments
 (0)