Skip to main content

quai_primitives/
encoding.rs

1//! Bounded byte encodings and explicit 256-bit signed representations.
2use crate::SignedUnits;
3use base64::Engine;
4use ruint::aliases::{U256, U512};
5use thiserror::Error;
6/// Maximum general byte utility input/output, excluding hexadecimal expansion.
7pub const MAX_ENCODING_BYTES: usize = 1_048_576;
8/// Base58 uses quadratic radix conversion and therefore has a smaller input cap.
9pub const MAX_BASE58_BYTES: usize = 4096;
10/// Invalid encoding, width or arithmetic input; errors never retain input content.
11#[derive(Clone, Copy, Debug, Eq, PartialEq, Error)]
12#[non_exhaustive]
13pub enum EncodingError {
14    /// Input violates the canonical encoding or strict UTF-8 requirements.
15    #[error("invalid byte encoding")]
16    Invalid,
17    /// Requested padding/slice/width does not fit the input or integer.
18    #[error("invalid byte or integer bounds")]
19    Bounds,
20    /// Input or output exceeds its documented resource bound.
21    #[error("encoding resource limit exceeded")]
22    TooLarge,
23}
24fn bounded(length: usize) -> Result<(), EncodingError> {
25    if length > MAX_ENCODING_BYTES {
26        Err(EncodingError::TooLarge)
27    } else {
28        Ok(())
29    }
30}
31/// Lowercase even-width hexadecimal with a `0x` prefix, preserving leading zeros.
32pub fn hexlify(bytes: &[u8]) -> Result<String, EncodingError> {
33    bounded(bytes.len())?;
34    const HEX: &[u8; 16] = b"0123456789abcdef";
35    let mut text = String::with_capacity(2 + bytes.len() * 2);
36    text.push_str("0x");
37    for byte in bytes {
38        text.push(HEX[(byte >> 4) as usize] as char);
39        text.push(HEX[(byte & 15) as usize] as char);
40    }
41    Ok(text)
42}
43/// Decode strict prefixed, even-width hexadecimal into owned bytes. A `0X`
44/// prefix, odd nibbles, whitespace and invalid digits are rejected.
45pub fn get_bytes(text: &str) -> Result<Vec<u8>, EncodingError> {
46    if text.len() > MAX_ENCODING_BYTES * 2 + 2 {
47        return Err(EncodingError::TooLarge);
48    }
49    let digits = text.strip_prefix("0x").ok_or(EncodingError::Invalid)?;
50    if !digits.len().is_multiple_of(2) || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
51        return Err(EncodingError::Invalid);
52    }
53    let nibble = |b: u8| {
54        if b.is_ascii_digit() {
55            b - b'0'
56        } else {
57            b.to_ascii_lowercase() - b'a' + 10
58        }
59    };
60    Ok(digits
61        .as_bytes()
62        .chunks_exact(2)
63        .map(|b| nibble(b[0]) * 16 + nibble(b[1]))
64        .collect())
65}
66/// Concatenate byte slices after bounding their total size before allocation.
67pub fn concat_bytes(parts: &[&[u8]]) -> Result<Vec<u8>, EncodingError> {
68    if parts.len() > 4096 {
69        return Err(EncodingError::TooLarge);
70    }
71    let size = parts
72        .iter()
73        .try_fold(0usize, |n, p| n.checked_add(p.len()))
74        .ok_or(EncodingError::TooLarge)?;
75    bounded(size)?;
76    let mut bytes = Vec::with_capacity(size);
77    for part in parts {
78        bytes.extend_from_slice(part);
79    }
80    Ok(bytes)
81}
82/// Checked borrowed byte slice; negative/JS-coerced indexes are not accepted.
83pub fn data_slice(bytes: &[u8], start: usize, end: usize) -> Result<&[u8], EncodingError> {
84    bytes.get(start..end).ok_or(EncodingError::Bounds)
85}
86/// Borrow the bytes after all leading zero bytes. All-zero input returns empty.
87pub fn strip_zeros_left(bytes: &[u8]) -> &[u8] {
88    &bytes[bytes.iter().position(|b| *b != 0).unwrap_or(bytes.len())..]
89}
90fn pad(bytes: &[u8], length: usize, left: bool) -> Result<Vec<u8>, EncodingError> {
91    bounded(length)?;
92    if bytes.len() > length {
93        return Err(EncodingError::Bounds);
94    }
95    let mut result = vec![0; length];
96    let start = if left { length - bytes.len() } else { 0 };
97    result[start..start + bytes.len()].copy_from_slice(bytes);
98    Ok(result)
99}
100/// Left-pad an integer byte representation with zero bytes, without truncation.
101pub fn zero_pad_value(bytes: &[u8], length: usize) -> Result<Vec<u8>, EncodingError> {
102    pad(bytes, length, true)
103}
104/// Right-pad a fixed-byte representation with zero bytes, without truncation.
105pub fn zero_pad_bytes(bytes: &[u8], length: usize) -> Result<Vec<u8>, EncodingError> {
106    pad(bytes, length, false)
107}
108/// Standard padded RFC 4648 Base64 encoding.
109pub fn encode_base64(bytes: &[u8]) -> Result<String, EncodingError> {
110    bounded(bytes.len())?;
111    Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
112}
113/// Strict standard padded Base64; URL alphabet, whitespace, missing padding and
114/// nonzero trailing bits are rejected rather than accepting Node Buffer coercions.
115pub fn decode_base64(text: &str) -> Result<Vec<u8>, EncodingError> {
116    if text.len() > MAX_ENCODING_BYTES.div_ceil(3) * 4 {
117        return Err(EncodingError::TooLarge);
118    }
119    let bytes = base64::engine::general_purpose::STANDARD
120        .decode(text)
121        .map_err(|_| EncodingError::Invalid)?;
122    bounded(bytes.len())?;
123    Ok(bytes)
124}
125/// Bitcoin-alphabet Base58, preserving each leading zero byte as `1`.
126pub fn encode_base58(bytes: &[u8]) -> Result<String, EncodingError> {
127    if bytes.len() > MAX_BASE58_BYTES {
128        return Err(EncodingError::TooLarge);
129    }
130    Ok(bs58::encode(bytes).into_string())
131}
132/// Base58 to bytes, preserving leading zeros. This is preferable for key material.
133pub fn decode_base58_bytes(text: &str) -> Result<Vec<u8>, EncodingError> {
134    if text.len() > MAX_BASE58_BYTES * 138 / 100 + 1 {
135        return Err(EncodingError::TooLarge);
136    }
137    // Bound decoded allocation independently of leading-zero expansion.
138    let mut output = vec![0; MAX_BASE58_BYTES];
139    let size = bs58::decode(text)
140        .onto(output.as_mut_slice())
141        .map_err(|e| match e {
142            bs58::decode::Error::BufferTooSmall => EncodingError::TooLarge,
143            _ => EncodingError::Invalid,
144        })?;
145    output.truncate(size);
146    Ok(output)
147}
148/// Numeric Base58 decode, matching JS zero stripping within an explicit U256 range.
149pub fn decode_base58(text: &str) -> Result<U256, EncodingError> {
150    let bytes = decode_base58_bytes(text)?;
151    let bytes = strip_zeros_left(&bytes);
152    if bytes.len() > 32 {
153        return Err(EncodingError::Bounds);
154    }
155    Ok(U256::from_be_slice(bytes))
156}
157/// Encode at most 31 UTF-8 bytes plus null termination into an ABI bytes32 word.
158pub fn encode_bytes32(text: &str) -> Result<[u8; 32], EncodingError> {
159    if text.len() > 31 {
160        return Err(EncodingError::Bounds);
161    }
162    let mut bytes = [0; 32];
163    bytes[..text.len()].copy_from_slice(text.as_bytes());
164    Ok(bytes)
165}
166/// Decode strict UTF-8 after stripping trailing zero padding. Internal null bytes
167/// are preserved; the final word byte must be zero, matching the pinned JS helper.
168pub fn decode_bytes32(bytes: &[u8; 32]) -> Result<&str, EncodingError> {
169    if bytes[31] != 0 {
170        return Err(EncodingError::Invalid);
171    }
172    let end = bytes.iter().rposition(|b| *b != 0).map_or(0, |i| i + 1);
173    std::str::from_utf8(&bytes[..end]).map_err(|_| EncodingError::Invalid)
174}
175/// Keep the lowest `bits` bits, with the full supported range 0..=256.
176pub fn mask(value: U256, bits: u16) -> Result<U256, EncodingError> {
177    match bits {
178        0 => Ok(U256::ZERO),
179        256 => Ok(value),
180        1..=255 => Ok(value & ((U256::from(1) << bits as usize) - U256::from(1))),
181        _ => Err(EncodingError::Bounds),
182    }
183}
184/// Convert a checked signed value to its two's-complement representation at 1..=256 bits.
185pub fn to_twos(value: SignedUnits, bits: u16) -> Result<U256, EncodingError> {
186    if !(1..=256).contains(&bits) {
187        return Err(EncodingError::Bounds);
188    }
189    let magnitude = U256::checked_from_limbs_slice(value.magnitude().as_limbs())
190        .ok_or(EncodingError::Bounds)?;
191    let limit = U256::from(1) << (bits as usize - 1);
192    if magnitude > limit || (!value.is_negative() && magnitude == limit) {
193        return Err(EncodingError::Bounds);
194    }
195    if value.is_negative() {
196        mask((!magnitude).wrapping_add(U256::from(1)), bits)
197    } else {
198        Ok(magnitude)
199    }
200}
201/// Interpret an unsigned bit pattern as signed two's complement at 1..=256 bits.
202/// Bits outside the selected width are rejected instead of silently truncated.
203pub fn from_twos(value: U256, bits: u16) -> Result<SignedUnits, EncodingError> {
204    if !(1..=256).contains(&bits) || mask(value, bits)? != value {
205        return Err(EncodingError::Bounds);
206    }
207    let negative = value.bit(bits as usize - 1);
208    let magnitude = if negative {
209        mask((!value).wrapping_add(U256::from(1)), bits)?
210    } else {
211        value
212    };
213    SignedUnits::new(negative, U512::from(magnitude)).map_err(|_| EncodingError::Bounds)
214}