use sha1::{Digest, Sha1};
pub const CID_MAX: usize = 36;
pub const GATE_CID_MAX: usize = 28;
pub const REVX_NAMESPACE: [u8; 16] = [
0x6b, 0x84, 0x65, 0xf2, 0x75, 0x2a, 0x56, 0x8d, 0xa9, 0x81, 0x77, 0x42, 0x91, 0x77, 0x75, 0xd0,
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdError(pub String);
impl core::fmt::Display for IdError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for IdError {}
fn sha1_hex(s: &str) -> String {
let d = Sha1::digest(s.as_bytes());
d.iter().map(|b| format!("{b:02x}")).collect()
}
fn coerce(raw: &str, max: usize, legal: impl Fn(char) -> bool) -> Result<String, IdError> {
let mut candidate: String = raw
.chars()
.map(|c| if legal(c) { c } else { '-' })
.collect();
if candidate.chars().count() > max {
let digest = sha1_hex(&candidate);
let head: String = candidate.chars().take(max - 7).collect();
candidate = format!("{head}-{}", &digest[..6]);
}
if candidate.is_empty() {
return Err(IdError("a client order id cannot be empty".into()));
}
Ok(candidate)
}
pub fn safe_cid(raw: &str) -> Result<String, IdError> {
coerce(raw, CID_MAX, |c| {
c.is_ascii_alphanumeric() || c == '_' || c == '-'
})
}
pub fn gate_cid(raw: &str) -> Result<String, IdError> {
let raw = raw.strip_prefix("t-").unwrap_or(raw);
coerce(raw, GATE_CID_MAX, |c| {
c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')
})
}
pub fn safe_gate_text(raw: &str) -> Result<String, IdError> {
Ok(format!("t-{}", gate_cid(raw)?))
}
pub fn safe_revx_cid(raw: &str) -> Result<String, IdError> {
if let Some(u) = parse_uuid(raw) {
return Ok(fmt_uuid(u));
}
if raw.is_empty() {
return Err(IdError("a client order id cannot be empty".into()));
}
Ok(fmt_uuid(uuid5(&REVX_NAMESPACE, raw)))
}
pub fn uuid5(namespace: &[u8; 16], name: &str) -> [u8; 16] {
let mut h = Sha1::new();
h.update(namespace);
h.update(name.as_bytes());
let d = h.finalize();
let mut u = [0u8; 16];
u.copy_from_slice(&d[..16]);
u[6] = (u[6] & 0x0f) | 0x50;
u[8] = (u[8] & 0x3f) | 0x80;
u
}
pub fn fmt_uuid(u: [u8; 16]) -> String {
let h: String = u.iter().map(|b| format!("{b:02x}")).collect();
format!(
"{}-{}-{}-{}-{}",
&h[..8],
&h[8..12],
&h[12..16],
&h[16..20],
&h[20..]
)
}
pub fn parse_uuid(raw: &str) -> Option<[u8; 16]> {
let s = raw.replace("urn:", "").replace("uuid:", "");
let s = s.trim_matches(|c| c == '{' || c == '}').replace('-', "");
if s.chars().count() != 32 {
return None;
}
let t = s.trim();
let (neg, digits) = match t.as_bytes().first() {
Some(b'+') => (false, &t[1..]),
Some(b'-') => (true, &t[1..]),
_ => (false, t),
};
if digits.is_empty()
|| digits.starts_with('_')
|| digits.ends_with('_')
|| digits.contains("__")
{
return None;
}
let clean = digits.replace('_', "");
if clean.is_empty() || !clean.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
let v = u128::from_str_radix(&clean, 16).ok()?;
if neg && v != 0 {
return None;
}
Some(v.to_be_bytes())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_namespace_is_a_valid_uuid5() {
assert_eq!(REVX_NAMESPACE[6] >> 4, 5);
assert_eq!(REVX_NAMESPACE[8] >> 6, 0b10);
}
#[test]
fn coercion_is_idempotent() {
let long = "csVERYLONGSYMBOLNAMEb944444r1u93041u93042";
let once = safe_cid(long).unwrap();
assert_eq!(once.len(), 36);
assert_eq!(safe_cid(&once).unwrap(), once);
let g = safe_gate_text(long).unwrap();
assert_eq!(safe_gate_text(&g).unwrap(), g);
let r = safe_revx_cid("csAAAb1r1").unwrap();
assert_eq!(safe_revx_cid(&r).unwrap(), r);
}
#[test]
fn an_empty_id_is_refused_everywhere() {
assert!(safe_cid("").is_err());
assert!(gate_cid("t-").is_err());
assert!(safe_revx_cid("").is_err());
}
}