Skip to content

Commit d7633bc

Browse files
committed
move zbase32 to base32 file
1 parent 1a4ac9f commit d7633bc

File tree

5 files changed

+155
-247
lines changed

5 files changed

+155
-247
lines changed

fuzz/src/zbase32.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,19 @@
77
// You may not use this file except in accordance with one or both of these
88
// licenses.
99

10-
use lightning::util::zbase32;
10+
use lightning::util::base32;
1111

1212
use crate::utils::test_logger;
1313

1414
#[inline]
1515
pub fn do_test(data: &[u8]) {
16-
let res = zbase32::encode(data);
17-
assert_eq!(&zbase32::decode(&res).unwrap()[..], data);
16+
let res = base32::Alphabet::ZBase32.encode(data);
17+
assert_eq!(&base32::Alphabet::ZBase32.decode(&res).unwrap()[..], data);
1818

1919
if let Ok(s) = std::str::from_utf8(data) {
20-
if let Ok(decoded) = zbase32::decode(s) {
21-
assert_eq!(&zbase32::encode(&decoded), &s.to_ascii_lowercase());
20+
let res = base32::Alphabet::ZBase32.decode(s);
21+
if let Ok(decoded) = res {
22+
assert_eq!(&base32::Alphabet::ZBase32.encode(&decoded), &s.to_ascii_lowercase());
2223
}
2324
}
2425
}

lightning/src/util/base32.rs

+57-2
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,31 @@ use crate::prelude::*;
1212
/// RFC4648 encoding table
1313
const RFC4648_ALPHABET: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
1414

15+
/// Zbase encoding alphabet
16+
const ZBASE_ALPHABET: &'static [u8] = b"ybndrfg8ejkmcpqxot1uwisza345h769";
17+
1518
/// RFC4648 decoding table
1619
const RFC4648_INV_ALPHABET: [i8; 43] = [
1720
-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,
1821
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
1922
];
2023

24+
/// Zbase decoding table
25+
const ZBASE_INV_ALPHABET: [i8; 43] = [
26+
-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,
27+
21, 9, 10, -1, 11, 2, 16, 13, 14, 4, 22, 17, 19, -1, 20, 15, 0, 23,
28+
];
29+
2130
/// Alphabet used for encoding and decoding.
2231
#[derive(Copy, Clone)]
2332
pub enum Alphabet {
2433
/// RFC4648 encoding.
2534
RFC4648 {
2635
/// Whether to use padding.
2736
padding: bool
28-
}
37+
},
38+
/// Zbase32 encoding.
39+
ZBase32
2940
}
3041

3142
impl Alphabet {
@@ -45,7 +56,10 @@ impl Alphabet {
4556
return String::from_utf8(ret).expect("Invalid UTF-8");
4657
}
4758
ret
48-
}
59+
},
60+
Self::ZBase32 => {
61+
Self::encode_data(data, ZBASE_ALPHABET)
62+
},
4963
};
5064
ret.truncate(output_length);
5165

@@ -70,6 +84,9 @@ impl Alphabet {
7084
});
7185
}
7286
(&data[..unpadded_data_length], RFC4648_INV_ALPHABET)
87+
},
88+
Self::ZBase32 => {
89+
(data, ZBASE_INV_ALPHABET)
7390
}
7491
};
7592
// If the string has more characters than are required to alphabet_encode the number of bytes
@@ -148,6 +165,44 @@ impl Alphabet {
148165
mod tests {
149166
use super::*;
150167

168+
const ZBASE32_TEST_DATA: &[(&str, &[u8])] = &[
169+
("", &[]),
170+
("yy", &[0x00]),
171+
("oy", &[0x80]),
172+
("tqrey", &[0x8b, 0x88, 0x80]),
173+
("6n9hq", &[0xf0, 0xbf, 0xc7]),
174+
("4t7ye", &[0xd4, 0x7a, 0x04]),
175+
("6im5sdy", &[0xf5, 0x57, 0xbb, 0x0c]),
176+
("ybndrfg8ejkmcpqxot1uwisza345h769", &[0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6,
177+
0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56, 0xd7, 0xc6,
178+
0x75, 0xbe, 0x77, 0xdf])
179+
];
180+
181+
#[test]
182+
fn test_zbase32_encode() {
183+
for &(zbase32, data) in ZBASE32_TEST_DATA {
184+
assert_eq!(Alphabet::ZBase32.encode(data), zbase32);
185+
}
186+
}
187+
188+
#[test]
189+
fn test_zbase32_decode() {
190+
for &(zbase32, data) in ZBASE32_TEST_DATA {
191+
assert_eq!(Alphabet::ZBase32.decode(zbase32).unwrap(), data);
192+
}
193+
}
194+
195+
#[test]
196+
fn test_decode_wrong() {
197+
const WRONG_DATA: &[&str] = &["00", "l1", "?", "="];
198+
for &data in WRONG_DATA {
199+
match Alphabet::ZBase32.decode(data) {
200+
Ok(_) => assert!(false, "Data shouldn't be decodable"),
201+
Err(_) => assert!(true),
202+
}
203+
}
204+
}
205+
151206
const RFC4648_NON_PADDED_TEST_VECTORS: &[(&[u8], &[u8])] = &[
152207
(&[0xF8, 0x3E, 0x7F, 0x83, 0xE7], b"7A7H7A7H"),
153208
(&[0x77, 0xC1, 0xF7, 0x7C, 0x1F], b"O7A7O7A7"),

lightning/src/util/message_signing.rs

+92-92
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
//!
1212
//! Note this is not part of the specs, but follows lnd's signing and verifying protocol, which can is defined as follows:
1313
//!
14-
//! signature = zbase32(SigRec(sha256d(("Lightning Signed Message:" + msg)))
14+
//! signature = base32::Alphabet::ZBase32(SigRec(sha256d(("Lightning Signed Message:" + msg)))
1515
//! zbase32 from <https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt>
1616
//! SigRec has first byte 31 + recovery id, followed by 64 byte sig.
1717
//!
@@ -21,126 +21,126 @@
2121
//! <https://api.lightning.community/#signmessage>
2222
2323
use crate::prelude::*;
24-
use crate::util::zbase32;
24+
use crate::util::base32;
2525
use bitcoin::hashes::{sha256d, Hash};
2626
use bitcoin::secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
2727
use bitcoin::secp256k1::{Error, Message, PublicKey, Secp256k1, SecretKey};
2828

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

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

35-
[&[prefix], &rsig[..]].concat()
35+
[&[prefix], &rsig[..]].concat()
3636
}
3737

3838
fn sigrec_decode(sig_rec: Vec<u8>) -> Result<RecoverableSignature, Error> {
39-
// Signature must be 64 + 1 bytes long (compact signature + recovery id)
40-
if sig_rec.len() != 65 {
41-
return Err(Error::InvalidSignature);
42-
}
43-
44-
let rsig = &sig_rec[1..];
45-
let rid = sig_rec[0] as i32 - 31;
46-
47-
match RecoveryId::from_i32(rid) {
48-
Ok(x) => RecoverableSignature::from_compact(rsig, x),
49-
Err(e) => Err(e)
50-
}
39+
// Signature must be 64 + 1 bytes long (compact signature + recovery id)
40+
if sig_rec.len() != 65 {
41+
return Err(Error::InvalidSignature);
42+
}
43+
44+
let rsig = &sig_rec[1..];
45+
let rid = sig_rec[0] as i32 - 31;
46+
47+
match RecoveryId::from_i32(rid) {
48+
Ok(x) => RecoverableSignature::from_compact(rsig, x),
49+
Err(e) => Err(e)
50+
}
5151
}
5252

5353
/// Creates a digital signature of a message given a SecretKey, like the node's secret.
5454
/// 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.
5555
/// Signatures are EC recoverable, meaning that given the message and the signature the PublicKey of the signer can be extracted.
5656
pub fn sign(msg: &[u8], sk: &SecretKey) -> Result<String, Error> {
57-
let secp_ctx = Secp256k1::signing_only();
58-
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
57+
let secp_ctx = Secp256k1::signing_only();
58+
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
5959

60-
let sig = secp_ctx.sign_ecdsa_recoverable(&Message::from_slice(&msg_hash)?, sk);
61-
Ok(zbase32::encode(&sigrec_encode(sig)))
60+
let sig = secp_ctx.sign_ecdsa_recoverable(&Message::from_slice(&msg_hash)?, sk);
61+
Ok(base32::Alphabet::ZBase32.encode(&sigrec_encode(sig)))
6262
}
6363

6464
/// Recovers the PublicKey of the signer of the message given the message and the signature.
6565
pub fn recover_pk(msg: &[u8], sig: &str) -> Result<PublicKey, Error> {
66-
let secp_ctx = Secp256k1::verification_only();
67-
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
68-
69-
match zbase32::decode(&sig) {
70-
Ok(sig_rec) => {
71-
match sigrec_decode(sig_rec) {
72-
Ok(sig) => secp_ctx.recover_ecdsa(&Message::from_slice(&msg_hash)?, &sig),
73-
Err(e) => Err(e)
74-
}
75-
},
76-
Err(_) => Err(Error::InvalidSignature)
77-
}
66+
let secp_ctx = Secp256k1::verification_only();
67+
let msg_hash = sha256d::Hash::hash(&[LN_MESSAGE_PREFIX, msg].concat());
68+
69+
match base32::Alphabet::ZBase32.decode(&sig) {
70+
Ok(sig_rec) => {
71+
match sigrec_decode(sig_rec) {
72+
Ok(sig) => secp_ctx.recover_ecdsa(&Message::from_slice(&msg_hash)?, &sig),
73+
Err(e) => Err(e)
74+
}
75+
},
76+
Err(_) => Err(Error::InvalidSignature)
77+
}
7878
}
7979

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

8989
#[cfg(test)]
9090
mod test {
91-
use core::str::FromStr;
92-
use crate::util::message_signing::{sign, recover_pk, verify};
93-
use bitcoin::secp256k1::ONE_KEY;
94-
use bitcoin::secp256k1::{PublicKey, Secp256k1};
95-
96-
#[test]
97-
fn test_sign() {
98-
let message = "test message";
99-
let zbase32_sig = sign(message.as_bytes(), &ONE_KEY);
100-
101-
assert_eq!(zbase32_sig.unwrap(), "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e")
102-
}
103-
104-
#[test]
105-
fn test_recover_pk() {
106-
let message = "test message";
107-
let sig = "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e";
108-
let pk = recover_pk(message.as_bytes(), sig);
109-
110-
assert_eq!(pk.unwrap(), PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY))
111-
}
112-
113-
#[test]
114-
fn test_verify() {
115-
let message = "another message";
116-
let sig = sign(message.as_bytes(), &ONE_KEY).unwrap();
117-
let pk = PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY);
118-
119-
assert!(verify(message.as_bytes(), &sig, &pk))
120-
}
121-
122-
#[test]
123-
fn test_verify_ground_truth_ish() {
124-
// There are no standard tests vectors for Sign/Verify, using the same tests vectors as c-lightning to see if they are compatible.
125-
// Taken from https://github.com/ElementsProject/lightning/blob/1275af6fbb02460c8eb2f00990bb0ef9179ce8f3/tests/test_misc.py#L1925-L1938
126-
127-
let corpus = [
128-
["@bitconner",
129-
"is this compatible?",
130-
"rbgfioj114mh48d8egqx8o9qxqw4fmhe8jbeeabdioxnjk8z3t1ma1hu1fiswpakgucwwzwo6ofycffbsqusqdimugbh41n1g698hr9t",
131-
"02b80cabdf82638aac86948e4c06e82064f547768dcef977677b9ea931ea75bab5"],
132-
["@duck1123",
133-
"hi",
134-
"rnrphcjswusbacjnmmmrynh9pqip7sy5cx695h6mfu64iac6qmcmsd8xnsyczwmpqp9shqkth3h4jmkgyqu5z47jfn1q7gpxtaqpx4xg",
135-
"02de60d194e1ca5947b59fe8e2efd6aadeabfb67f2e89e13ae1a799c1e08e4a43b"],
136-
["@jochemin",
137-
"hi",
138-
"ry8bbsopmduhxy3dr5d9ekfeabdpimfx95kagdem7914wtca79jwamtbw4rxh69hg7n6x9ty8cqk33knbxaqftgxsfsaeprxkn1k48p3",
139-
"022b8ece90ee891cbcdac0c1cc6af46b73c47212d8defbce80265ac81a6b794931"],
140-
];
141-
142-
for c in &corpus {
143-
assert!(verify(c[1].as_bytes(), c[2], &PublicKey::from_str(c[3]).unwrap()))
144-
}
145-
}
91+
use core::str::FromStr;
92+
use crate::util::message_signing::{sign, recover_pk, verify};
93+
use bitcoin::secp256k1::ONE_KEY;
94+
use bitcoin::secp256k1::{PublicKey, Secp256k1};
95+
96+
#[test]
97+
fn test_sign() {
98+
let message = "test message";
99+
let zbase32_sig = sign(message.as_bytes(), &ONE_KEY);
100+
101+
assert_eq!(zbase32_sig.unwrap(), "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e")
102+
}
103+
104+
#[test]
105+
fn test_recover_pk() {
106+
let message = "test message";
107+
let sig = "d9tibmnic9t5y41hg7hkakdcra94akas9ku3rmmj4ag9mritc8ok4p5qzefs78c9pqfhpuftqqzhydbdwfg7u6w6wdxcqpqn4sj4e73e";
108+
let pk = recover_pk(message.as_bytes(), sig);
109+
110+
assert_eq!(pk.unwrap(), PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY))
111+
}
112+
113+
#[test]
114+
fn test_verify() {
115+
let message = "another message";
116+
let sig = sign(message.as_bytes(), &ONE_KEY).unwrap();
117+
let pk = PublicKey::from_secret_key(&Secp256k1::signing_only(), &ONE_KEY);
118+
119+
assert!(verify(message.as_bytes(), &sig, &pk))
120+
}
121+
122+
#[test]
123+
fn test_verify_ground_truth_ish() {
124+
// There are no standard tests vectors for Sign/Verify, using the same tests vectors as c-lightning to see if they are compatible.
125+
// Taken from https://github.com/ElementsProject/lightning/blob/1275af6fbb02460c8eb2f00990bb0ef9179ce8f3/tests/test_misc.py#L1925-L1938
126+
127+
let corpus = [
128+
["@bitconner",
129+
"is this compatible?",
130+
"rbgfioj114mh48d8egqx8o9qxqw4fmhe8jbeeabdioxnjk8z3t1ma1hu1fiswpakgucwwzwo6ofycffbsqusqdimugbh41n1g698hr9t",
131+
"02b80cabdf82638aac86948e4c06e82064f547768dcef977677b9ea931ea75bab5"],
132+
["@duck1123",
133+
"hi",
134+
"rnrphcjswusbacjnmmmrynh9pqip7sy5cx695h6mfu64iac6qmcmsd8xnsyczwmpqp9shqkth3h4jmkgyqu5z47jfn1q7gpxtaqpx4xg",
135+
"02de60d194e1ca5947b59fe8e2efd6aadeabfb67f2e89e13ae1a799c1e08e4a43b"],
136+
["@jochemin",
137+
"hi",
138+
"ry8bbsopmduhxy3dr5d9ekfeabdpimfx95kagdem7914wtca79jwamtbw4rxh69hg7n6x9ty8cqk33knbxaqftgxsfsaeprxkn1k48p3",
139+
"022b8ece90ee891cbcdac0c1cc6af46b73c47212d8defbce80265ac81a6b794931"],
140+
];
141+
142+
for c in &corpus {
143+
assert!(verify(c[1].as_bytes(), c[2], &PublicKey::from_str(c[3]).unwrap()))
144+
}
145+
}
146146
}

lightning/src/util/mod.rs

-4
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,6 @@ pub(crate) mod base32;
3030
pub(crate) mod atomic_counter;
3131
pub(crate) mod byte_utils;
3232
pub(crate) mod chacha20;
33-
#[cfg(fuzzing)]
34-
pub mod zbase32;
35-
#[cfg(not(fuzzing))]
36-
pub(crate) mod zbase32;
3733
#[cfg(not(fuzzing))]
3834
pub(crate) mod poly1305;
3935
pub(crate) mod chacha20poly1305rfc;

0 commit comments

Comments
 (0)