Move zbase32 implementation to base32 file

This commit is contained in:
jbesraa 2023-08-25 05:57:06 +03:00
parent d736ca8595
commit b2d3b94b17
5 changed files with 67 additions and 159 deletions

View file

@ -7,18 +7,19 @@
// You may not use this file except in accordance with one or both of these
// licenses.
use lightning::util::zbase32;
use lightning::util::base32;
use crate::utils::test_logger;
#[inline]
pub fn do_test(data: &[u8]) {
let res = zbase32::encode(data);
assert_eq!(&zbase32::decode(&res).unwrap()[..], data);
let res = base32::Alphabet::ZBase32.encode(data);
assert_eq!(&base32::Alphabet::ZBase32.decode(&res).unwrap()[..], data);
if let Ok(s) = std::str::from_utf8(data) {
if let Ok(decoded) = zbase32::decode(s) {
assert_eq!(&zbase32::encode(&decoded), &s.to_ascii_lowercase());
let res = base32::Alphabet::ZBase32.decode(s);
if let Ok(decoded) = res {
assert_eq!(&base32::Alphabet::ZBase32.encode(&decoded), &s.to_ascii_lowercase());
}
}
}

View file

@ -12,12 +12,21 @@ use crate::prelude::*;
/// RFC4648 encoding table
const RFC4648_ALPHABET: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/// Zbase encoding alphabet
const ZBASE_ALPHABET: &'static [u8] = b"ybndrfg8ejkmcpqxot1uwisza345h769";
/// RFC4648 decoding table
const RFC4648_INV_ALPHABET: [i8; 43] = [
-1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 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,
];
/// Zbase decoding table
const ZBASE_INV_ALPHABET: [i8; 43] = [
-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,
21, 9, 10, -1, 11, 2, 16, 13, 14, 4, 22, 17, 19, -1, 20, 15, 0, 23,
];
/// Alphabet used for encoding and decoding.
#[derive(Copy, Clone)]
pub enum Alphabet {
@ -25,7 +34,9 @@ pub enum Alphabet {
RFC4648 {
/// Whether to use padding.
padding: bool
}
},
/// Zbase32 encoding.
ZBase32
}
impl Alphabet {
@ -48,7 +59,10 @@ impl Alphabet {
return String::from_utf8(ret).expect("Invalid UTF-8");
}
ret
}
},
Self::ZBase32 => {
Self::encode_data(data, ZBASE_ALPHABET)
},
};
ret.truncate(output_length);
@ -73,6 +87,9 @@ impl Alphabet {
});
}
(&data[..unpadded_data_length], RFC4648_INV_ALPHABET)
},
Self::ZBase32 => {
(data, ZBASE_INV_ALPHABET)
}
};
// If the string has more characters than are required to alphabet_encode the number of bytes
@ -150,6 +167,44 @@ impl Alphabet {
mod tests {
use super::*;
const ZBASE32_TEST_DATA: &[(&str, &[u8])] = &[
("", &[]),
("yy", &[0x00]),
("oy", &[0x80]),
("tqrey", &[0x8b, 0x88, 0x80]),
("6n9hq", &[0xf0, 0xbf, 0xc7]),
("4t7ye", &[0xd4, 0x7a, 0x04]),
("6im5sdy", &[0xf5, 0x57, 0xbb, 0x0c]),
("ybndrfg8ejkmcpqxot1uwisza345h769", &[0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6,
0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56, 0xd7, 0xc6,
0x75, 0xbe, 0x77, 0xdf])
];
#[test]
fn test_zbase32_encode() {
for &(zbase32, data) in ZBASE32_TEST_DATA {
assert_eq!(Alphabet::ZBase32.encode(data), zbase32);
}
}
#[test]
fn test_zbase32_decode() {
for &(zbase32, data) in ZBASE32_TEST_DATA {
assert_eq!(Alphabet::ZBase32.decode(zbase32).unwrap(), data);
}
}
#[test]
fn test_decode_wrong() {
const WRONG_DATA: &[&str] = &["00", "l1", "?", "="];
for &data in WRONG_DATA {
match Alphabet::ZBase32.decode(data) {
Ok(_) => assert!(false, "Data shouldn't be decodable"),
Err(_) => assert!(true),
}
}
}
const RFC4648_NON_PADDED_TEST_VECTORS: &[(&[u8], &[u8])] = &[
(&[0xF8, 0x3E, 0x7F, 0x83, 0xE7], b"7A7H7A7H"),
(&[0x77, 0xC1, 0xF7, 0x7C, 0x1F], b"O7A7O7A7"),

View file

@ -21,7 +21,7 @@
//! <https://api.lightning.community/#signmessage>
use crate::prelude::*;
use crate::util::zbase32;
use crate::util::base32;
use bitcoin::hashes::{sha256d, Hash};
use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
use bitcoin::secp256k1::{Error, Message, PublicKey, Secp256k1, SecretKey};
@ -58,7 +58,7 @@ pub fn sign(msg: &[u8], sk: &SecretKey) -> Result<String, Error> {
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
let sig = secp_ctx.sign_ecdsa_recoverable(&Message::from_slice(&msg_hash)?, sk);
Ok(zbase32::encode(&sigrec_encode(sig)))
Ok(base32::Alphabet::ZBase32.encode(&sigrec_encode(sig)))
}
/// Recovers the PublicKey of the signer of the message given the message and the signature.
@ -66,7 +66,7 @@ pub fn recover_pk(msg: &[u8], sig: &str) -> Result<PublicKey, Error> {
let secp_ctx = Secp256k1::verification_only();
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
match zbase32::decode(&sig) {
match base32::Alphabet::ZBase32.decode(&sig) {
Ok(sig_rec) => {
match sigrec_decode(sig_rec) {
Ok(sig) => secp_ctx.recover_ecdsa(&Message::from_slice(&msg_hash)?, &sig),
@ -143,4 +143,4 @@ mod test {
assert!(verify(c[1].as_bytes(), c[2], &PublicKey::from_str(c[3]).unwrap()))
}
}
}
}

View file

@ -30,10 +30,6 @@ pub(crate) mod base32;
pub(crate) mod atomic_counter;
pub(crate) mod byte_utils;
pub(crate) mod chacha20;
#[cfg(fuzzing)]
pub mod zbase32;
#[cfg(not(fuzzing))]
pub(crate) mod zbase32;
#[cfg(not(fuzzing))]
pub(crate) mod poly1305;
pub(crate) mod chacha20poly1305rfc;

View file

@ -1,144 +0,0 @@
// This is a modification of base32 encoding to support the zbase32 alphabet.
// The original piece of software can be found at https://github.com/andreasots/base32
// The original portions of this software are Copyright (c) 2015 The base32 Developers
/* This file is licensed under either of
* Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) or
* MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
* at your option.
*/
use crate::prelude::*;
const ALPHABET: &'static [u8] = b"ybndrfg8ejkmcpqxot1uwisza345h769";
/// Encodes some bytes as a zbase32 string
pub fn encode(data: &[u8]) -> String {
let mut ret = Vec::with_capacity((data.len() + 4) / 5 * 8);
for chunk in data.chunks(5) {
let buf = {
let mut buf = [0u8; 5];
for (i, &b) in chunk.iter().enumerate() {
buf[i] = b;
}
buf
};
ret.push(ALPHABET[((buf[0] & 0xF8) >> 3) as usize]);
ret.push(ALPHABET[(((buf[0] & 0x07) << 2) | ((buf[1] & 0xC0) >> 6)) as usize]);
ret.push(ALPHABET[((buf[1] & 0x3E) >> 1) as usize]);
ret.push(ALPHABET[(((buf[1] & 0x01) << 4) | ((buf[2] & 0xF0) >> 4)) as usize]);
ret.push(ALPHABET[(((buf[2] & 0x0F) << 1) | (buf[3] >> 7)) as usize]);
ret.push(ALPHABET[((buf[3] & 0x7C) >> 2) as usize]);
ret.push(ALPHABET[(((buf[3] & 0x03) << 3) | ((buf[4] & 0xE0) >> 5)) as usize]);
ret.push(ALPHABET[(buf[4] & 0x1F) as usize]);
}
ret.truncate((data.len() * 8 + 4) / 5);
// Check that our capacity calculation doesn't under-shoot in fuzzing
#[cfg(fuzzing)]
assert_eq!(ret.capacity(), (data.len() + 4) / 5 * 8);
String::from_utf8(ret).unwrap()
}
// ASCII 0-Z
const INV_ALPHABET: [i8; 43] = [
-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,
21, 9, 10, -1, 11, 2, 16, 13, 14, 4, 22, 17, 19, -1, 20, 15, 0, 23,
];
/// Decodes a zbase32 string to the original bytes, failing if the string was not encoded by a
/// proper zbase32 encoder.
pub fn decode(data: &str) -> Result<Vec<u8>, ()> {
if !data.is_ascii() {
return Err(());
}
let data = data.as_bytes();
let output_length = data.len() * 5 / 8;
if data.len() > (output_length * 8 + 4) / 5 {
// If the string has more charachters than are required to encode the number of bytes
// decodable, treat the string as invalid.
return Err(());
}
let mut ret = Vec::with_capacity((data.len() + 7) / 8 * 5);
for chunk in data.chunks(8) {
let buf = {
let mut buf = [0u8; 8];
for (i, &c) in chunk.iter().enumerate() {
match INV_ALPHABET.get(c.to_ascii_uppercase().wrapping_sub(b'0') as usize) {
Some(&-1) | None => return Err(()),
Some(&value) => buf[i] = value as u8,
};
}
buf
};
ret.push((buf[0] << 3) | (buf[1] >> 2));
ret.push((buf[1] << 6) | (buf[2] << 1) | (buf[3] >> 4));
ret.push((buf[3] << 4) | (buf[4] >> 1));
ret.push((buf[4] << 7) | (buf[5] << 2) | (buf[6] >> 3));
ret.push((buf[6] << 5) | buf[7]);
}
for c in ret.drain(output_length..) {
if c != 0 {
// If the original string had any bits set at positions outside of the encoded data,
// treat the string as invalid.
return Err(());
}
}
// Check that our capacity calculation doesn't under-shoot in fuzzing
#[cfg(fuzzing)]
assert_eq!(ret.capacity(), (data.len() + 7) / 8 * 5);
Ok(ret)
}
#[cfg(test)]
mod tests {
use super::*;
const TEST_DATA: &[(&str, &[u8])] = &[
("", &[]),
("yy", &[0x00]),
("oy", &[0x80]),
("tqrey", &[0x8b, 0x88, 0x80]),
("6n9hq", &[0xf0, 0xbf, 0xc7]),
("4t7ye", &[0xd4, 0x7a, 0x04]),
("6im5sdy", &[0xf5, 0x57, 0xbb, 0x0c]),
("ybndrfg8ejkmcpqxot1uwisza345h769", &[0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6,
0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56, 0xd7, 0xc6,
0x75, 0xbe, 0x77, 0xdf])
];
#[test]
fn test_encode() {
for &(zbase32, data) in TEST_DATA {
assert_eq!(encode(data), zbase32);
}
}
#[test]
fn test_decode() {
for &(zbase32, data) in TEST_DATA {
assert_eq!(decode(zbase32).unwrap(), data);
}
}
#[test]
fn test_decode_wrong() {
const WRONG_DATA: &[&str] = &["00", "l1", "?", "="];
for &data in WRONG_DATA {
match decode(data) {
Ok(_) => assert!(false, "Data shouldn't be decodable"),
Err(_) => assert!(true),
}
}
}
}