Fix a number of bugs in zbase32 and add a fuzzer which caught them.
[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
4 /*
5 Copyright (c) 2015 The base32 Developers
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in all
15 copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 SOFTWARE.
24 */
25
26 const ALPHABET: &'static [u8] = b"ybndrfg8ejkmcpqxot1uwisza345h769";
27
28 /// Encodes some bytes as a zbase32 string
29 pub fn encode(data: &[u8]) -> String {
30     let mut ret = Vec::with_capacity((data.len() + 4) / 5 * 8);
31
32     for chunk in data.chunks(5) {
33         let buf = {
34             let mut buf = [0u8; 5];
35             for (i, &b) in chunk.iter().enumerate() {
36                 buf[i] = b;
37             }
38             buf
39         };
40
41         ret.push(ALPHABET[((buf[0] & 0xF8) >> 3) as usize]);
42         ret.push(ALPHABET[(((buf[0] & 0x07) << 2) | ((buf[1] & 0xC0) >> 6)) as usize]);
43         ret.push(ALPHABET[((buf[1] & 0x3E) >> 1) as usize]);
44         ret.push(ALPHABET[(((buf[1] & 0x01) << 4) | ((buf[2] & 0xF0) >> 4)) as usize]);
45         ret.push(ALPHABET[(((buf[2] & 0x0F) << 1) | (buf[3] >> 7)) as usize]);
46         ret.push(ALPHABET[((buf[3] & 0x7C) >> 2) as usize]);
47         ret.push(ALPHABET[(((buf[3] & 0x03) << 3) | ((buf[4] & 0xE0) >> 5)) as usize]);
48         ret.push(ALPHABET[(buf[4] & 0x1F) as usize]);
49     }
50
51     ret.truncate((data.len() * 8 + 4) / 5);
52
53     // Check that our capacity calculation doesn't under-shoot in fuzzing
54     #[cfg(fuzzing)]
55     assert_eq!(ret.capacity(), (data.len() + 4) / 5 * 8);
56
57     String::from_utf8(ret).unwrap()
58 }
59
60 // ASCII 0-Z
61 const INV_ALPHABET: [i8; 43] = [
62     -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,
63     21, 9, 10, -1, 11, 2, 16, 13, 14, 4, 22, 17, 19, -1, 20, 15, 0, 23,
64 ];
65
66 /// Decodes a zbase32 string to the original bytes, failing if the string was not encoded by a
67 /// proper zbase32 encoder.
68 pub fn decode(data: &str) -> Result<Vec<u8>, ()> {
69     if !data.is_ascii() {
70         return Err(());
71     }
72
73     let data = data.as_bytes();
74     let output_length = data.len() * 5 / 8;
75     if data.len() > (output_length * 8 + 4) / 5 {
76         // If the string has more charachters than are required to encode the number of bytes
77         // decodable, treat the string as invalid.
78         return Err(());
79     }
80
81     let mut ret = Vec::with_capacity((data.len() + 7) / 8 * 5);
82
83     for chunk in data.chunks(8) {
84         let buf = {
85             let mut buf = [0u8; 8];
86             for (i, &c) in chunk.iter().enumerate() {
87                 match INV_ALPHABET.get(c.to_ascii_uppercase().wrapping_sub(b'0') as usize) {
88                     Some(&-1) | None => return Err(()),
89                     Some(&value) => buf[i] = value as u8,
90                 };
91             }
92             buf
93         };
94         ret.push((buf[0] << 3) | (buf[1] >> 2));
95         ret.push((buf[1] << 6) | (buf[2] << 1) | (buf[3] >> 4));
96         ret.push((buf[3] << 4) | (buf[4] >> 1));
97         ret.push((buf[4] << 7) | (buf[5] << 2) | (buf[6] >> 3));
98         ret.push((buf[6] << 5) | buf[7]);
99     }
100     for c in ret.drain(output_length..) {
101         if c != 0 {
102             // If the original string had any bits set at positions outside of the encoded data,
103             // treat the string as invalid.
104             return Err(());
105         }
106     }
107
108     // Check that our capacity calculation doesn't under-shoot in fuzzing
109     #[cfg(fuzzing)]
110     assert_eq!(ret.capacity(), (data.len() + 7) / 8 * 5);
111
112     Ok(ret)
113 }
114
115 #[cfg(test)]
116 mod tests {
117     use super::*;
118
119     const TEST_DATA: &[(&str, &[u8])] = &[
120         ("",       &[]),
121         ("yy",     &[0x00]),
122         ("oy",     &[0x80]),
123         ("tqrey",   &[0x8b, 0x88, 0x80]),
124         ("6n9hq",  &[0xf0, 0xbf, 0xc7]),
125         ("4t7ye",  &[0xd4, 0x7a, 0x04]),
126         ("6im5sdy", &[0xf5, 0x57, 0xbb, 0x0c]),
127         ("ybndrfg8ejkmcpqxot1uwisza345h769", &[0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6,
128                                                     0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56, 0xd7, 0xc6,
129                                                     0x75, 0xbe, 0x77, 0xdf])
130     ];
131  
132
133     #[test]
134     fn test_encode() {
135         for &(zbase32, data) in TEST_DATA {
136             assert_eq!(encode(data), zbase32);
137         }
138     }
139
140     #[test]
141     fn test_decode() {
142         for &(zbase32, data) in TEST_DATA {
143             assert_eq!(decode(zbase32).unwrap(), data);
144         }
145     }
146
147     #[test]
148     fn test_decode_wrong() {
149         const WRONG_DATA: &[&str] = &["00", "l1", "?", "="];
150
151         for &data in WRONG_DATA {
152             match decode(data) {
153                 Ok(_) => assert!(false, "Data shouldn't be decodable"),
154                 Err(_) => assert!(true),
155             }
156         }
157     }
158 }