Skip to content

Commit

Permalink
move zbase32 to base32 file
Browse files Browse the repository at this point in the history
  • Loading branch information
jbesraa committed Aug 26, 2023
1 parent 1a4ac9f commit d7633bc
Show file tree
Hide file tree
Showing 5 changed files with 155 additions and 247 deletions.
11 changes: 6 additions & 5 deletions fuzz/src/zbase32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}
}
Expand Down
59 changes: 57 additions & 2 deletions lightning/src/util/base32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,31 @@ 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 {
/// RFC4648 encoding.
RFC4648 {
/// Whether to use padding.
padding: bool
}
},
/// Zbase32 encoding.
ZBase32
}

impl Alphabet {
Expand All @@ -45,7 +56,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);

Expand All @@ -70,6 +84,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
Expand Down Expand Up @@ -148,6 +165,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"),
Expand Down
184 changes: 92 additions & 92 deletions lightning/src/util/message_signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
//!
//! Note this is not part of the specs, but follows lnd's signing and verifying protocol, which can is defined as follows:
//!
//! signature = zbase32(SigRec(sha256d(("Lightning Signed Message:" + msg)))
//! signature = base32::Alphabet::ZBase32(SigRec(sha256d(("Lightning Signed Message:" + msg)))
//! zbase32 from <https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt>
//! SigRec has first byte 31 + recovery id, followed by 64 byte sig.
//!
Expand All @@ -21,126 +21,126 @@
//! <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};

static LN_MESSAGE_PREFIX: &[u8] = b"Lightning Signed Message:";

fn sigrec_encode(sig_rec: RecoverableSignature) -> Vec<u8> {
let (rid, rsig) = sig_rec.serialize_compact();
let prefix = rid.to_i32() as u8 + 31;
let (rid, rsig) = sig_rec.serialize_compact();
let prefix = rid.to_i32() as u8 + 31;

[&[prefix], &rsig[..]].concat()
[&[prefix], &rsig[..]].concat()
}

fn sigrec_decode(sig_rec: Vec<u8>) -> Result<RecoverableSignature, Error> {
// Signature must be 64 + 1 bytes long (compact signature + recovery id)
if sig_rec.len() != 65 {
return Err(Error::InvalidSignature);
}

let rsig = &sig_rec[1..];
let rid = sig_rec[0] as i32 - 31;

match RecoveryId::from_i32(rid) {
Ok(x) => RecoverableSignature::from_compact(rsig, x),
Err(e) => Err(e)
}
// Signature must be 64 + 1 bytes long (compact signature + recovery id)
if sig_rec.len() != 65 {
return Err(Error::InvalidSignature);
}

let rsig = &sig_rec[1..];
let rid = sig_rec[0] as i32 - 31;

match RecoveryId::from_i32(rid) {
Ok(x) => RecoverableSignature::from_compact(rsig, x),
Err(e) => Err(e)
}
}

/// Creates a digital signature of a message given a SecretKey, like the node's secret.
/// A receiver knowing the PublicKey (e.g. the node's id) and the message can be sure that the signature was generated by the caller.
/// Signatures are EC recoverable, meaning that given the message and the signature the PublicKey of the signer can be extracted.
pub fn sign(msg: &[u8], sk: &SecretKey) -> Result<String, Error> {
let secp_ctx = Secp256k1::signing_only();
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
let secp_ctx = Secp256k1::signing_only();
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)))
let sig = secp_ctx.sign_ecdsa_recoverable(&Message::from_slice(&msg_hash)?, sk);
Ok(base32::Alphabet::ZBase32.encode(&sigrec_encode(sig)))
}

/// Recovers the PublicKey of the signer of the message given the message and the signature.
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) {
Ok(sig_rec) => {
match sigrec_decode(sig_rec) {
Ok(sig) => secp_ctx.recover_ecdsa(&Message::from_slice(&msg_hash)?, &sig),
Err(e) => Err(e)
}
},
Err(_) => Err(Error::InvalidSignature)
}
let secp_ctx = Secp256k1::verification_only();
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());

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),
Err(e) => Err(e)
}
},
Err(_) => Err(Error::InvalidSignature)
}
}

/// Verifies a message was signed by a PrivateKey that derives to a given PublicKey, given a message, a signature,
/// and the PublicKey.
pub fn verify(msg: &[u8], sig: &str, pk: &PublicKey) -> bool {
match recover_pk(msg, sig) {
Ok(x) => x == *pk,
Err(_) => false
}
match recover_pk(msg, sig) {
Ok(x) => x == *pk,
Err(_) => false
}
}

#[cfg(test)]
mod test {
use core::str::FromStr;
use crate::util::message_signing::{sign, recover_pk, verify};
use bitcoin::secp256k1::ONE_KEY;
use bitcoin::secp256k1::{PublicKey, Secp256k1};

#[test]
fn test_sign() {
let message = "test message";
let zbase32_sig = sign(message.as_bytes(), &ONE_KEY);

assert_eq!(zbase32_sig.unwrap(), "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e")
}

#[test]
fn test_recover_pk() {
let message = "test message";
let sig = "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e";
let pk = recover_pk(message.as_bytes(), sig);

assert_eq!(pk.unwrap(), PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY))
}

#[test]
fn test_verify() {
let message = "another message";
let sig = sign(message.as_bytes(), &ONE_KEY).unwrap();
let pk = PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY);

assert!(verify(message.as_bytes(), &sig, &pk))
}

#[test]
fn test_verify_ground_truth_ish() {
// There are no standard tests vectors for Sign/Verify, using the same tests vectors as c-lightning to see if they are compatible.
// Taken from https://github.com/ElementsProject/lightning/blob/1275af6fbb02460c8eb2f00990bb0ef9179ce8f3/tests/test_misc.py#L1925-L1938

let corpus = [
["@bitconner",
"is this compatible?",
"rbgfioj114mh48d8egqx8o9qxqw4fmhe8jbeeabdioxnjk8z3t1ma1hu1fiswpakgucwwzwo6ofycffbsqusqdimugbh41n1g698hr9t",
"02b80cabdf82638aac86948e4c06e82064f547768dcef977677b9ea931ea75bab5"],
["@duck1123",
"hi",
"rnrphcjswusbacjnmmmrynh9pqip7sy5cx695h6mfu64iac6qmcmsd8xnsyczwmpqp9shqkth3h4jmkgyqu5z47jfn1q7gpxtaqpx4xg",
"02de60d194e1ca5947b59fe8e2efd6aadeabfb67f2e89e13ae1a799c1e08e4a43b"],
["@jochemin",
"hi",
"ry8bbsopmduhxy3dr5d9ekfeabdpimfx95kagdem7914wtca79jwamtbw4rxh69hg7n6x9ty8cqk33knbxaqftgxsfsaeprxkn1k48p3",
"022b8ece90ee891cbcdac0c1cc6af46b73c47212d8defbce80265ac81a6b794931"],
];

for c in &corpus {
assert!(verify(c[1].as_bytes(), c[2], &PublicKey::from_str(c[3]).unwrap()))
}
}
use core::str::FromStr;
use crate::util::message_signing::{sign, recover_pk, verify};
use bitcoin::secp256k1::ONE_KEY;
use bitcoin::secp256k1::{PublicKey, Secp256k1};

#[test]
fn test_sign() {
let message = "test message";
let zbase32_sig = sign(message.as_bytes(), &ONE_KEY);

assert_eq!(zbase32_sig.unwrap(), "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e")
}

#[test]
fn test_recover_pk() {
let message = "test message";
let sig = "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e";
let pk = recover_pk(message.as_bytes(), sig);

assert_eq!(pk.unwrap(), PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY))
}

#[test]
fn test_verify() {
let message = "another message";
let sig = sign(message.as_bytes(), &ONE_KEY).unwrap();
let pk = PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY);

assert!(verify(message.as_bytes(), &sig, &pk))
}

#[test]
fn test_verify_ground_truth_ish() {
// There are no standard tests vectors for Sign/Verify, using the same tests vectors as c-lightning to see if they are compatible.
// Taken from https://github.com/ElementsProject/lightning/blob/1275af6fbb02460c8eb2f00990bb0ef9179ce8f3/tests/test_misc.py#L1925-L1938

let corpus = [
["@bitconner",
"is this compatible?",
"rbgfioj114mh48d8egqx8o9qxqw4fmhe8jbeeabdioxnjk8z3t1ma1hu1fiswpakgucwwzwo6ofycffbsqusqdimugbh41n1g698hr9t",
"02b80cabdf82638aac86948e4c06e82064f547768dcef977677b9ea931ea75bab5"],
["@duck1123",
"hi",
"rnrphcjswusbacjnmmmrynh9pqip7sy5cx695h6mfu64iac6qmcmsd8xnsyczwmpqp9shqkth3h4jmkgyqu5z47jfn1q7gpxtaqpx4xg",
"02de60d194e1ca5947b59fe8e2efd6aadeabfb67f2e89e13ae1a799c1e08e4a43b"],
["@jochemin",
"hi",
"ry8bbsopmduhxy3dr5d9ekfeabdpimfx95kagdem7914wtca79jwamtbw4rxh69hg7n6x9ty8cqk33knbxaqftgxsfsaeprxkn1k48p3",
"022b8ece90ee891cbcdac0c1cc6af46b73c47212d8defbce80265ac81a6b794931"],
];

for c in &corpus {
assert!(verify(c[1].as_bytes(), c[2], &PublicKey::from_str(c[3]).unwrap()))
}
}
}
4 changes: 0 additions & 4 deletions lightning/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading

0 comments on commit d7633bc

Please sign in to comment.