quai_primitives/
encoding.rs1use crate::SignedUnits;
3use base64::Engine;
4use ruint::aliases::{U256, U512};
5use thiserror::Error;
6pub const MAX_ENCODING_BYTES: usize = 1_048_576;
8pub const MAX_BASE58_BYTES: usize = 4096;
10#[derive(Clone, Copy, Debug, Eq, PartialEq, Error)]
12#[non_exhaustive]
13pub enum EncodingError {
14 #[error("invalid byte encoding")]
16 Invalid,
17 #[error("invalid byte or integer bounds")]
19 Bounds,
20 #[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}
31pub 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}
43pub 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}
66pub 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}
82pub fn data_slice(bytes: &[u8], start: usize, end: usize) -> Result<&[u8], EncodingError> {
84 bytes.get(start..end).ok_or(EncodingError::Bounds)
85}
86pub 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}
100pub fn zero_pad_value(bytes: &[u8], length: usize) -> Result<Vec<u8>, EncodingError> {
102 pad(bytes, length, true)
103}
104pub fn zero_pad_bytes(bytes: &[u8], length: usize) -> Result<Vec<u8>, EncodingError> {
106 pad(bytes, length, false)
107}
108pub fn encode_base64(bytes: &[u8]) -> Result<String, EncodingError> {
110 bounded(bytes.len())?;
111 Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
112}
113pub 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}
125pub 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}
132pub 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 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}
148pub 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}
157pub 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}
166pub 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}
175pub 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}
184pub 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}
201pub 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}