mazze-addr 0.1.0

Mazze Address Encoder/Decoder
Documentation
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404

//
// Modification based on https://github.com/hlb8122/rust-bitcoincash-addr in MIT License.
// A copy of the original license is included in LICENSE.rust-bitcoincash-addr.

extern crate mazze_types;
#[macro_use]
extern crate lazy_static;
extern crate rustc_hex;

#[allow(dead_code)]
pub mod checksum;
pub mod consts;
pub mod errors;
#[cfg(test)]
mod tests;

use mazze_types::Address;
use checksum::polymod;
pub use consts::{AddressType, Network};
pub use errors::DecodingError;
use errors::*;

const BASE32_CHARS: &str = "abcdefghijklmnopqrstuvwxyz0123456789";
const EXCLUDE_CHARS: [char; 4] = ['o', 'i', 'l', 'q'];
lazy_static! {
    // Regular expression for application to match string. This regex isn't strict,
    // because our SDK will.
    // "(?i)[:=_-0123456789abcdefghijklmnopqrstuvwxyz]*"
    static ref REGEXP: String = format!{"(?i)[:=_-{}]*", BASE32_CHARS};

    // For encoding.
    static ref CHARSET: Vec<u8> =
        // Remove EXCLUDE_CHARS from charset.
        BASE32_CHARS.replace(&EXCLUDE_CHARS[..], "").into_bytes();

    // For decoding.
    static ref CHAR_INDEX: [Option<u8>; 128] = (|| {
        let mut index = [None; 128];
        assert_eq!(CHARSET.len(), consts::CHARSET_SIZE);
        for i in 0..consts::CHARSET_SIZE {
            let c = CHARSET[i] as usize;
            index[c] = Some(i as u8);
            // Support uppercase as well.
            let u = (c as u8 as char).to_ascii_uppercase() as u8 as usize;
            if u != c {
                index[u] = Some(i as u8);
            }
        }
        return index;
    }) ();
}

/// Struct containing the raw bytes and metadata of a Mazze address.
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct DecodedRawAddress {
    /// Base32 address. This is included for debugging purposes.
    pub input_base32_address: String,
    /// Address bytes
    pub parsed_address_bytes: Vec<u8>,
    /// The parsed address in H160 format.
    pub hex_address: Option<Address>,
    /// Network
    pub network: Network,
}

#[derive(Copy, Clone)]
pub enum EncodingOptions {
    Simple,
    QrCode,
}

// TODO: verbose level and address type.
pub fn mazze_addr_encode(
    raw: &[u8], network: Network, encoding_options: EncodingOptions,
) -> Result<String, EncodingError> {
    // Calculate version byte
    let length = raw.len();
    let version_byte = match length {
        20 => consts::SIZE_160,
        // Mazze does not have other hash sizes. We don't use the sizes below
        // but we kept these for unit tests.
        24 => consts::SIZE_192,
        28 => consts::SIZE_224,
        32 => consts::SIZE_256,
        40 => consts::SIZE_320,
        48 => consts::SIZE_384,
        56 => consts::SIZE_448,
        64 => consts::SIZE_512,
        _ => return Err(EncodingError::InvalidLength(length)),
    };

    // Get prefix
    let prefix = network.to_prefix()?;

    // Convert payload to 5 bit array
    let mut payload = Vec::with_capacity(1 + raw.len());
    payload.push(version_byte);
    payload.extend(raw);
    let payload_5_bits = convert_bits(&payload, 8, 5, true)
        .expect("no error is possible for encoding");

    // Construct payload string using CHARSET
    let payload_str: String = payload_5_bits
        .iter()
        .map(|b| CHARSET[*b as usize] as char)
        .collect();

    // Create checksum
    let expanded_prefix = expand_prefix(&prefix);
    let checksum_input =
        [&expanded_prefix[..], &payload_5_bits, &[0; 8][..]].concat();
    let checksum = polymod(&checksum_input);

    // Convert checksum to string
    let checksum_str: String = (0..8)
        .rev()
        .map(|i| CHARSET[((checksum >> (i * 5)) & 31) as usize] as char)
        .collect();

    // Concatenate all parts
    let mazze_base32_addr = match encoding_options {
        EncodingOptions::Simple => {
            [&prefix, ":", &payload_str, &checksum_str].concat()
        }
        EncodingOptions::QrCode => {
            let addr_type_str = AddressType::from_address(&raw)?.to_str();
            [
                &prefix,
                ":type.",
                addr_type_str,
                ":",
                &payload_str,
                &checksum_str,
            ]
            .concat()
            .to_uppercase()
        }
    };
    Ok(mazze_base32_addr)
}

pub fn mazze_addr_decode(
    addr_str: &str,
) -> Result<DecodedRawAddress, DecodingError> {
    // FIXME: add a unit test for addr_str in capital letters.
    let has_lowercase = addr_str.chars().any(|c| c.is_lowercase());
    let has_uppercase = addr_str.chars().any(|c| c.is_uppercase());
    if has_lowercase && has_uppercase {
        return Err(DecodingError::MixedCase);
    }
    let lowercase = addr_str.to_lowercase();

    // Delimit and extract prefix
    let parts: Vec<&str> = lowercase.split(':').collect();
    if parts.len() < 2 {
        return Err(DecodingError::NoPrefix);
    }
    let prefix = parts[0];
    // Match network
    let network = Network::from_prefix(prefix)?;

    let mut address_type = None;
    // Parse optional parts. We will ignore everything we can't understand.
    for option_str in &parts[1..parts.len() - 1] {
        let key_value: Vec<&str> = option_str.split('.').collect();
        if key_value.len() != 2 {
            return Err(DecodingError::InvalidOption(OptionError::ParseError(
                (*option_str).into(),
            )));
        }
        // Address type.
        if key_value[0] == "type" {
            address_type = Some(AddressType::parse(key_value[1])?);
        }
    }

    // Do some sanity checks on the payload string
    let payload_str = parts[parts.len() - 1];
    if payload_str.len() == 0 {
        return Err(DecodingError::InvalidLength(0));
    }
    let has_lowercase = payload_str.chars().any(|c| c.is_lowercase());
    let has_uppercase = payload_str.chars().any(|c| c.is_uppercase());
    if has_lowercase && has_uppercase {
        return Err(DecodingError::MixedCase);
    }

    // Decode payload to 5 bit array
    let payload_chars = payload_str.chars();
    let payload_5_bits: Result<Vec<u8>, DecodingError> = payload_chars
        .map(|c| {
            let i = c as usize;
            if let Some(Some(d)) = CHAR_INDEX.get(i) {
                Ok(*d as u8)
            } else {
                Err(DecodingError::InvalidChar(c))
            }
        })
        .collect();
    let payload_5_bits = payload_5_bits?;

    // Verify the checksum
    let checksum =
        polymod(&[&expand_prefix(prefix), &payload_5_bits[..]].concat());
    if checksum != 0 {
        // TODO: according to the spec it is possible to do correction based on
        // the checksum,  we shouldn't do it automatically but we could
        // include the corrected address in  the error.
        return Err(DecodingError::ChecksumFailed(checksum));
    }

    // Convert from 5 bit array to byte array
    let len_5_bit = payload_5_bits.len();
    let payload =
        convert_bits(&payload_5_bits[..(len_5_bit - 8)], 5, 8, false)?;

    // Verify the version byte
    let version = payload[0];

    // Check length
    let body = &payload[1..];
    let body_len = body.len();
    let version_size = version & consts::SIZE_MASK;
    if (version_size == consts::SIZE_160 && body_len != 20)
        // Mazze does not have other hash sizes. We don't use the sizes below
        // but we kept these for unit tests.
        || (version_size == consts::SIZE_192 && body_len != 24)
        || (version_size == consts::SIZE_224 && body_len != 28)
        || (version_size == consts::SIZE_256 && body_len != 32)
        || (version_size == consts::SIZE_320 && body_len != 40)
        || (version_size == consts::SIZE_384 && body_len != 48)
        || (version_size == consts::SIZE_448 && body_len != 56)
        || (version_size == consts::SIZE_512 && body_len != 64)
    {
        return Err(DecodingError::InvalidLength(body_len));
    }
    // Check reserved bits
    if version & consts::RESERVED_BITS_MASK != 0 {
        return Err(DecodingError::VersionNotRecognized(version));
    }

    let hex_address;
    // Check address type for parsed H160 address.
    if version_size == consts::SIZE_160 {
        hex_address = Some(Address::from_slice(body));
        match address_type {
            Some(expected) => {
                let got =
                    AddressType::from_address(hex_address.as_ref().unwrap())
                        .or(Err(()));
                if got.as_ref() != Ok(&expected) {
                    return Err(DecodingError::InvalidOption(
                        OptionError::AddressTypeMismatch { expected, got },
                    ));
                }
            }
            None => {}
        }
    } else {
        hex_address = None;
    }

    Ok(DecodedRawAddress {
        input_base32_address: addr_str.into(),
        parsed_address_bytes: body.to_vec(),
        hex_address,
        network,
    })
}

/// The checksum calculation includes the lower 5 bits of each character of the
/// prefix.
/// - e.g. "bit..." becomes 2,9,20,...
// Expand the address prefix for the checksum operation.
fn expand_prefix(prefix: &str) -> Vec<u8> {
    let mut ret: Vec<u8> = prefix.chars().map(|c| (c as u8) & 0x1f).collect();
    ret.push(0);
    ret
}

// This method assume that data is valid string of inbits.
// When pad is true, any remaining bits are padded and encoded into a new byte;
// when pad is false, any remaining bits are checked to be zero and discarded.
fn convert_bits(
    data: &[u8], inbits: u8, outbits: u8, pad: bool,
) -> Result<Vec<u8>, DecodingError> {
    assert!(inbits <= 8 && outbits <= 8);
    let num_bytes = (data.len() * inbits as usize + outbits as usize - 1)
        / outbits as usize;
    let mut ret = Vec::with_capacity(num_bytes);
    let mut acc: u16 = 0; // accumulator of bits
    let mut num: u8 = 0; // num bits in acc
    let groupmask = (1 << outbits) - 1;
    for d in data.iter() {
        // We push each input chunk into a 16-bit accumulator
        acc = (acc << inbits) | u16::from(*d);
        num += inbits;
        // Then we extract all the output groups we can
        while num >= outbits {
            // Store only the highest outbits.
            ret.push((acc >> (num - outbits)) as u8);
            // Clear the highest outbits.
            acc &= !(groupmask << (num - outbits));
            num -= outbits;
        }
    }
    if pad {
        // If there's some bits left, pad and add it
        if num > 0 {
            ret.push((acc << (outbits - num)) as u8);
        }
    } else {
        // FIXME: add unit tests for it.
        // If there's some bits left, figure out if we need to remove padding
        // and add it
        let padding = ((data.len() * inbits as usize) % outbits as usize) as u8;
        if num >= inbits || acc != 0 {
            return Err(DecodingError::InvalidPadding {
                from_bits: inbits,
                padding_bits: padding,
                padding: acc,
            });
        }
    }
    Ok(ret)
}

#[test]
fn test_expand_prefix() {
    assert_eq!(expand_prefix("mazze"), vec![0x03, 0x06, 0x18, 0x00]);

    assert_eq!(
        expand_prefix("mazzetest"),
        vec![0x03, 0x06, 0x18, 0x14, 0x05, 0x13, 0x14, 0x00]
    );

    assert_eq!(
        expand_prefix("net17"),
        vec![0x0e, 0x05, 0x14, 0x11, 0x17, 0x00]
    );
}

#[test]
fn test_convert_bits() {
    // 00000000 --> 0, 0, 0, 0, 0, 0, 0, 0
    assert_eq!(convert_bits(&[0], 8, 1, false), Ok(vec![0; 8]));

    // 00000000 --> 000, 000, 00_
    assert_eq!(convert_bits(&[0], 8, 3, false), Ok(vec![0, 0])); // 00_ is dropped
    assert_eq!(convert_bits(&[0], 8, 3, true), Ok(vec![0, 0, 0])); // 00_ becomes 000

    // 00000001 --> 000, 000, 01_
    assert!(convert_bits(&[1], 8, 3, false).is_err()); // 01_ != 0 (ignored incomplete chunk must be 0)
    assert_eq!(convert_bits(&[1], 8, 3, true), Ok(vec![0, 0, 2])); // 01_ becomes 010

    // 00000001 --> 0000000, 1______
    assert_eq!(convert_bits(&[1], 8, 7, true), Ok(vec![0, 64])); // 1______ becomes 1000000

    // 0, 0, 0, 0, 0, 0, 0, 0 --> 00000000
    assert_eq!(convert_bits(&[0; 8], 1, 8, false), Ok(vec![0]));

    // 000, 000, 010 -> 00000001, 0_______
    assert_eq!(convert_bits(&[0, 0, 2], 3, 8, false), Ok(vec![1])); // 0_______ is dropped
    assert_eq!(convert_bits(&[0, 0, 2], 3, 8, true), Ok(vec![1, 0])); // 0_______ becomes 00000000

    // 000, 000, 011 -> 00000001, 1_______
    assert!(convert_bits(&[0, 0, 3], 3, 8, false).is_err()); // 1_______ != 0 (ignored incomplete chunk must be 0)

    // 00000000, 00000001, 00000010, 00000011, 00000100 -->
    // 00000, 00000, 00000, 10000, 00100, 00000, 11000, 00100
    assert_eq!(
        convert_bits(&[0, 1, 2, 3, 4], 8, 5, false),
        Ok(vec![0, 0, 0, 16, 4, 0, 24, 4])
    );

    // 00000000, 00000001, 00000010 -->
    // 00000, 00000, 00000, 10000, 0010_
    assert!(convert_bits(&[0, 1, 2], 8, 5, false).is_err()); // 0010_ != 0 (ignored incomplete chunk must be 0)

    assert_eq!(
        convert_bits(&[0, 1, 2], 8, 5, true),
        Ok(vec![0, 0, 0, 16, 4])
    ); // 0010_ becomes 00100

    // 00000, 00000, 00000, 10000, 00100, 00000, 11000, 00100 -->
    // 00000000, 00000001, 00000010, 00000011, 00000100
    assert_eq!(
        convert_bits(&[0, 0, 0, 16, 4, 0, 24, 4], 5, 8, false),
        Ok(vec![0, 1, 2, 3, 4])
    );

    // 00000, 00000, 00000, 10000, 00100 -->
    // 00000000, 00000001, 00000010, 0_______
    assert_eq!(
        convert_bits(&[0, 0, 0, 16, 4], 5, 8, false),
        Ok(vec![0, 1, 2])
    ); // 0_______ is dropped

    assert_eq!(
        convert_bits(&[0, 0, 0, 16, 4], 5, 8, true),
        Ok(vec![0, 1, 2, 0])
    ); // 0_______ becomes 00000000
}