19a10cca3ea9d6ae09a42fb878d9f81e0da141ed
[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 pub fn encode(data: &[u8]) -> String {
29     let mut ret = Vec::with_capacity((data.len() + 3) / 4 * 5);
30
31     for chunk in data.chunks(5) {
32         let buf = {
33             let mut buf = [0u8; 5];
34             for (i, &b) in chunk.iter().enumerate() {
35                 buf[i] = b;
36             }
37             buf
38         };
39
40         ret.push(ALPHABET[((buf[0] & 0xF8) >> 3) as usize]);
41         ret.push(ALPHABET[(((buf[0] & 0x07) << 2) | ((buf[1] & 0xC0) >> 6)) as usize]);
42         ret.push(ALPHABET[((buf[1] & 0x3E) >> 1) as usize]);
43         ret.push(ALPHABET[(((buf[1] & 0x01) << 4) | ((buf[2] & 0xF0) >> 4)) as usize]);
44         ret.push(ALPHABET[(((buf[2] & 0x0F) << 1) | (buf[3] >> 7)) as usize]);
45         ret.push(ALPHABET[((buf[3] & 0x7C) >> 2) as usize]);
46         ret.push(ALPHABET[(((buf[3] & 0x03) << 3) | ((buf[4] & 0xE0) >> 5)) as usize]);
47         ret.push(ALPHABET[(buf[4] & 0x1F) as usize]);
48     }
49
50     if data.len() % 5 != 0 {
51         let len = ret.len();
52         let num_extra = 8 - (data.len() % 5 * 8 + 4) / 5;
53         ret.truncate(len - num_extra);
54     }
55
56     String::from_utf8(ret).unwrap()
57 }
58
59 // ASCII 0-Z
60 const INV_ALPHABET: [i8; 43] = [
61     -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,
62     21, 9, 10, -1, 11, 2, 16, 13, 14, 4, 22, 17, 19, -1, 20, 15, 0, 23,
63 ];
64
65 pub fn decode(data: &str) -> Result<Vec<u8>, &'static str> {
66     if !data.is_ascii() {
67         return Err("Data is not zbase32 encoded");
68     }
69
70     let data = data.as_bytes();
71     let output_length = data.len() * 5 / 8;
72     let mut ret = Vec::with_capacity((output_length + 4) / 5 * 5);
73
74     for chunk in data.chunks(8) {
75         let buf = {
76             let mut buf = [0u8; 8];
77             for (i, &c) in chunk.iter().enumerate() {
78                 match INV_ALPHABET.get(c.to_ascii_uppercase().wrapping_sub(b'0') as usize) {
79                     Some(&-1) | None => return Err("Data is not zbase32 encoded"),
80                     Some(&value) => buf[i] = value as u8,
81                 };
82             }
83             buf
84         };
85         ret.push((buf[0] << 3) | (buf[1] >> 2));
86         ret.push((buf[1] << 6) | (buf[2] << 1) | (buf[3] >> 4));
87         ret.push((buf[3] << 4) | (buf[4] >> 1));
88         ret.push((buf[4] << 7) | (buf[5] << 2) | (buf[6] >> 3));
89         ret.push((buf[6] << 5) | buf[7]);
90     }
91     ret.truncate(output_length);
92     Ok(ret)
93 }
94
95 mod tests {
96     use super::*;
97
98     const TEST_DATA: &[(&str, &[u8])] = &[
99         ("",       &[]),
100         ("yy",     &[0x00]),
101         ("oy",     &[0x80]),
102         ("tqrey",   &[0x8b, 0x88, 0x80]),
103         ("6n9hq",  &[0xf0, 0xbf, 0xc7]),
104         ("4t7ye",  &[0xd4, 0x7a, 0x04]),
105         ("6im5sdy", &[0xf5, 0x57, 0xbb, 0x0c]),
106         ("ybndrfg8ejkmcpqxot1uwisza345h769", &[0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6,
107                                                     0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56, 0xd7, 0xc6,
108                                                     0x75, 0xbe, 0x77, 0xdf])
109     ];
110  
111
112     #[test]
113     fn test_encode() {
114         for &(zbase32, data) in TEST_DATA {
115             assert_eq!(encode(data), zbase32);
116         }
117     }
118
119     #[test]
120     fn test_decode() {
121         for &(zbase32, data) in TEST_DATA {
122             assert_eq!(decode(zbase32).unwrap(), data);
123         }
124     }
125
126     #[test]
127     fn test_decode_wrong() {
128         let WRONG_DATA = &["00", "l1", "?", "="];
129
130         for &data in WRONG_DATA {
131             match decode(data) {
132                 Ok(_) => assert!(false, "Data shouldn't be decodable"),
133                 Err(_) => assert!(true),
134             }
135         }
136     }
137 }