1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
extern crate data_encoding;
extern crate reed_solomon;
mod error;
pub use error::HcidError;
mod util;
use util::{b32_correct, cap_decode, cap_encode_bin, char_upper};
pub type HcidResult<T> = Result<T, HcidError>;
pub fn with_hck0() -> HcidResult<HcidEncoding> {
HcidEncoding::new(HcidEncodingConfig {
key_byte_count: 32,
base_parity_byte_count: 4,
cap_parity_byte_count: 4,
prefix: vec![0x38, 0x94, 0x24],
prefix_cap: b"101".to_vec(),
cap_segment_char_count: 15,
encoded_char_count: 63,
})
}
pub fn with_hca0() -> HcidResult<HcidEncoding> {
HcidEncoding::new(HcidEncodingConfig {
key_byte_count: 32,
base_parity_byte_count: 4,
cap_parity_byte_count: 4,
prefix: vec![0x38, 0x80, 0x24],
prefix_cap: b"101".to_vec(),
cap_segment_char_count: 15,
encoded_char_count: 63,
})
}
pub fn with_hcs0() -> HcidResult<HcidEncoding> {
HcidEncoding::new(HcidEncodingConfig {
key_byte_count: 32,
base_parity_byte_count: 4,
cap_parity_byte_count: 4,
prefix: vec![0x38, 0xa2, 0x24],
prefix_cap: b"101".to_vec(),
cap_segment_char_count: 15,
encoded_char_count: 63,
})
}
pub struct HcidEncodingConfig {
pub key_byte_count: usize,
pub base_parity_byte_count: usize,
pub cap_parity_byte_count: usize,
pub prefix: Vec<u8>,
pub prefix_cap: Vec<u8>,
pub cap_segment_char_count: usize,
pub encoded_char_count: usize,
}
pub struct HcidEncoding {
b32: data_encoding::Encoding,
config: HcidEncodingConfig,
rs_enc: reed_solomon::Encoder,
rs_dec: reed_solomon::Decoder,
}
impl HcidEncoding {
pub fn new(config: HcidEncodingConfig) -> HcidResult<Self> {
let mut spec = data_encoding::Specification::new();
spec.symbols.push_str("ABCDEFGHIJKMNOPQRSTUVWXYZ3456789");
let b32 = spec.encoding()?;
let rs_enc = reed_solomon::Encoder::new(
config.base_parity_byte_count + config.cap_parity_byte_count,
);
let rs_dec = reed_solomon::Decoder::new(
config.base_parity_byte_count + config.cap_parity_byte_count,
);
Ok(Self {
b32,
config,
rs_enc,
rs_dec,
})
}
pub fn encode(&self, data: &[u8]) -> HcidResult<String> {
if data.len() != self.config.key_byte_count {
return Err(HcidError(String::from(format!(
"BadDataLen:{},Expected:{}",
data.len(),
self.config.key_byte_count
))));
}
let full_parity = self.rs_enc.encode(data);
let cap_bytes = &full_parity[full_parity.len() - self.config.cap_parity_byte_count..];
let mut base = self.config.prefix.clone();
base.extend_from_slice(
&full_parity[0..full_parity.len() - self.config.cap_parity_byte_count],
);
let mut base32 = self.b32.encode(&base).into_bytes();
if base32.len() != self.config.encoded_char_count {
return Err(HcidError(String::from(format!(
"InternalGeneratedBadLen:{},Expected:{}",
base32.len(),
self.config.encoded_char_count
))));
}
cap_encode_bin(
&mut base32[0..self.config.prefix_cap.len()],
&self.config.prefix_cap,
3,
)?;
for i in 0..cap_bytes.len() {
let seg_start = self.config.prefix_cap.len() + (i * self.config.cap_segment_char_count);
let seg = &mut base32[seg_start..seg_start + self.config.cap_segment_char_count];
let bin = format!("{:08b}", cap_bytes[i]).into_bytes();
cap_encode_bin(seg, &bin, 8)?;
}
unsafe {
Ok(String::from_utf8_unchecked(base32))
}
}
pub fn decode(&self, data: &str) -> HcidResult<Vec<u8>> {
let (data, erasures) = self.pre_decode(data)?;
if erasures.len() > ( self.config.base_parity_byte_count + self.config.cap_parity_byte_count ) / 2 {
return Err(HcidError(String::from("TooManyErrors")));
}
if self.pre_is_corrupt(&data, &erasures)? {
Ok(
self.rs_dec.correct(&data, Some(&erasures[..]))?[0..self.config.key_byte_count]
.to_vec(),
)
} else {
Ok(data[0..self.config.key_byte_count].to_vec())
}
}
pub fn is_corrupt(&self, data: &str) -> HcidResult<bool> {
let (data, erasures) = match self.pre_decode(data) {
Ok(v) => v,
Err(_) => return Ok(true),
};
match self.pre_is_corrupt(&data, &erasures) {
Ok(v) => Ok(v),
Err(_) => Ok(true),
}
}
fn pre_is_corrupt(&self, data: &[u8], erasures: &[u8]) -> HcidResult<bool> {
if erasures.len() > 0 {
return Ok(true);
}
Ok(self.rs_dec.is_corrupted(&data))
}
fn pre_decode(&self, data: &str) -> HcidResult<(Vec<u8>, Vec<u8>)> {
if data.len() != self.config.encoded_char_count {
return Err(HcidError(String::from(format!(
"BadIdLen:{},Expected:{}",
data.len(),
self.config.encoded_char_count
))));
}
let key_base_byte_size = self.config.key_byte_count + self.config.base_parity_byte_count;
let mut byte_erasures = vec![b'0'; key_base_byte_size + self.config.cap_parity_byte_count];
let mut char_erasures = vec![b'0'; data.len()];
let mut data = b32_correct(data.as_bytes(), &mut char_erasures);
let mut cap_bytes: Vec<u8> = Vec::new();
let mut all_zro = true;
let mut all_one = true;
for i in 0..self.config.cap_parity_byte_count {
let char_idx = self.config.prefix_cap.len() + (i * self.config.cap_segment_char_count);
match cap_decode(
char_idx,
&data[char_idx..char_idx + self.config.cap_segment_char_count],
&char_erasures
)? {
None => {
byte_erasures[key_base_byte_size + i] = b'1';
cap_bytes.push(0)
}
Some(parity) => {
if all_zro && parity != 0x00_u8 {
all_zro = false
}
if all_one && parity != 0xFF_u8 {
all_one = false
}
cap_bytes.push(parity)
}
}
}
if all_zro || all_one {
for i in 0..self.config.cap_parity_byte_count {
byte_erasures[key_base_byte_size + i] = b'1';
}
}
for c in data.iter_mut() {
char_upper(c);
}
let mut data = self.b32.decode(&data)?;
if &data[0..self.config.prefix.len()] != self.config.prefix.as_slice() {
return Err(HcidError(String::from("PrefixMismatch")));
}
data.drain(0..self.config.prefix.len());
data.append(&mut cap_bytes);
for i in self.config.prefix_cap.len()..char_erasures.len() {
let c = char_erasures[i];
if c == b'1' {
byte_erasures[( i * 5 + 0 ) / 8 - self.config.prefix.len()] = b'1';
byte_erasures[( i * 5 + 4 ) / 8 - self.config.prefix.len()] = b'1';
}
}
let mut erasures: Vec<u8> = Vec::new();
for i in 0..byte_erasures.len() {
if byte_erasures[i] == b'1' {
data[i] = 0;
erasures.push(i as u8);
}
}
Ok((data, erasures))
}
}
#[cfg(test)]
mod tests {
use data_encoding::HEXLOWER_PERMISSIVE as hex;
use super::*;
static TEST_HEX_1: &'static str =
"0c71db50d35d760b0ea2002ff20147c7c3a8e8030d35ef28ed1adaec9e329aba";
static TEST_ID_1: &'static str =
"HcKciDds5OiogymxbnHKEabQ8iavqs8dwdVaGdJW76Vp4gx47tQDfGW4OWc9w5i";
#[test]
fn it_encodes_1() {
let enc = with_hck0().unwrap();
let input = hex.decode(TEST_HEX_1.as_bytes()).unwrap();
let id = enc.encode(&input).unwrap();
assert_eq!(TEST_ID_1, id);
}
#[test]
fn it_decodes_1() {
let enc = with_hck0().unwrap();
let data = hex.encode(&enc.decode(TEST_ID_1).unwrap());
assert_eq!(TEST_HEX_1, data);
}
}