Use alloc for no_std builds
[rust-lightning] / lightning / src / util / zbase32.rs
1 // This is a modification of base32 encoding to support the zbase32 alphabet.
2 // The original piece of software can be found at https://github.com/andreasots/base32
3 // The original portions of this software are Copyright (c) 2015 The base32 Developers
4
5 /* This file is licensed under either of
6  *  Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) or
7  *  MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
8  * at your option.
9 */
10
11 use prelude::*;
12
13 const ALPHABET: &'static [u8] = b"ybndrfg8ejkmcpqxot1uwisza345h769";
14
15 /// Encodes some bytes as a zbase32 string
16 pub fn encode(data: &[u8]) -> String {
17         let mut ret = Vec::with_capacity((data.len() + 4) / 5 * 8);
18
19         for chunk in data.chunks(5) {
20                 let buf = {
21                         let mut buf = [0u8; 5];
22                         for (i, &b) in chunk.iter().enumerate() {
23                                 buf[i] = b;
24                         }
25                         buf
26                 };
27
28                 ret.push(ALPHABET[((buf[0] & 0xF8) >> 3) as usize]);
29                 ret.push(ALPHABET[(((buf[0] & 0x07) << 2) | ((buf[1] & 0xC0) >> 6)) as usize]);
30                 ret.push(ALPHABET[((buf[1] & 0x3E) >> 1) as usize]);
31                 ret.push(ALPHABET[(((buf[1] & 0x01) << 4) | ((buf[2] & 0xF0) >> 4)) as usize]);
32                 ret.push(ALPHABET[(((buf[2] & 0x0F) << 1) | (buf[3] >> 7)) as usize]);
33                 ret.push(ALPHABET[((buf[3] & 0x7C) >> 2) as usize]);
34                 ret.push(ALPHABET[(((buf[3] & 0x03) << 3) | ((buf[4] & 0xE0) >> 5)) as usize]);
35                 ret.push(ALPHABET[(buf[4] & 0x1F) as usize]);
36         }
37
38         ret.truncate((data.len() * 8 + 4) / 5);
39
40         // Check that our capacity calculation doesn't under-shoot in fuzzing
41         #[cfg(fuzzing)]
42         assert_eq!(ret.capacity(), (data.len() + 4) / 5 * 8);
43
44         String::from_utf8(ret).unwrap()
45 }
46
47 // ASCII 0-Z
48 const INV_ALPHABET: [i8; 43] = [
49         -1, 18, -1, 25, 26, 27, 30, 29, 7, 31, -1, -1, -1, -1, -1, -1, -1,  24, 1, 12, 3, 8, 5, 6, 28,
50         21, 9, 10, -1, 11, 2, 16, 13, 14, 4, 22, 17, 19, -1, 20, 15, 0, 23,
51 ];
52
53 /// Decodes a zbase32 string to the original bytes, failing if the string was not encoded by a
54 /// proper zbase32 encoder.
55 pub fn decode(data: &str) -> Result<Vec<u8>, ()> {
56         if !data.is_ascii() {
57                 return Err(());
58         }
59
60         let data = data.as_bytes();
61         let output_length = data.len() * 5 / 8;
62         if data.len() > (output_length * 8 + 4) / 5 {
63                 // If the string has more charachters than are required to encode the number of bytes
64                 // decodable, treat the string as invalid.
65                 return Err(());
66         }
67
68         let mut ret = Vec::with_capacity((data.len() + 7) / 8 * 5);
69
70         for chunk in data.chunks(8) {
71                 let buf = {
72                         let mut buf = [0u8; 8];
73                         for (i, &c) in chunk.iter().enumerate() {
74                                 match INV_ALPHABET.get(c.to_ascii_uppercase().wrapping_sub(b'0') as usize) {
75                                         Some(&-1) | None => return Err(()),
76                                         Some(&value) => buf[i] = value as u8,
77                                 };
78                         }
79                         buf
80                 };
81                 ret.push((buf[0] << 3) | (buf[1] >> 2));
82                 ret.push((buf[1] << 6) | (buf[2] << 1) | (buf[3] >> 4));
83                 ret.push((buf[3] << 4) | (buf[4] >> 1));
84                 ret.push((buf[4] << 7) | (buf[5] << 2) | (buf[6] >> 3));
85                 ret.push((buf[6] << 5) | buf[7]);
86         }
87         for c in ret.drain(output_length..) {
88                 if c != 0 {
89                         // If the original string had any bits set at positions outside of the encoded data,
90                         // treat the string as invalid.
91                         return Err(());
92                 }
93         }
94
95         // Check that our capacity calculation doesn't under-shoot in fuzzing
96         #[cfg(fuzzing)]
97         assert_eq!(ret.capacity(), (data.len() + 7) / 8 * 5);
98
99         Ok(ret)
100 }
101
102 #[cfg(test)]
103 mod tests {
104         use super::*;
105
106         const TEST_DATA: &[(&str, &[u8])] = &[
107                 ("",       &[]),
108                 ("yy",   &[0x00]),
109                 ("oy",   &[0x80]),
110                 ("tqrey",   &[0x8b, 0x88, 0x80]),
111                 ("6n9hq",  &[0xf0, 0xbf, 0xc7]),
112                 ("4t7ye",  &[0xd4, 0x7a, 0x04]),
113                 ("6im5sdy", &[0xf5, 0x57, 0xbb, 0x0c]),
114                 ("ybndrfg8ejkmcpqxot1uwisza345h769", &[0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6,
115                                                                                                         0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56, 0xd7, 0xc6,
116                                                                                                         0x75, 0xbe, 0x77, 0xdf])
117         ];
118
119         #[test]
120         fn test_encode() {
121                 for &(zbase32, data) in TEST_DATA {
122                         assert_eq!(encode(data), zbase32);
123                 }
124         }
125
126         #[test]
127         fn test_decode() {
128                 for &(zbase32, data) in TEST_DATA {
129                         assert_eq!(decode(zbase32).unwrap(), data);
130                 }
131         }
132
133         #[test]
134         fn test_decode_wrong() {
135                 const WRONG_DATA: &[&str] = &["00", "l1", "?", "="];
136
137                 for &data in WRONG_DATA {
138                         match decode(data) {
139                                 Ok(_) => assert!(false, "Data shouldn't be decodable"),
140                                 Err(_) => assert!(true),
141                         }
142                 }
143         }
144 }