2022-02-12 10:29:38 -05:00
|
|
|
//! Common utility functions
|
2022-12-21 14:44:50 -05:00
|
|
|
use bech32::FromBase32;
|
2022-02-12 10:29:38 -05:00
|
|
|
use std::time::SystemTime;
|
|
|
|
|
|
|
|
/// Seconds since 1970.
|
2023-01-22 10:49:49 -05:00
|
|
|
#[must_use] pub fn unix_time() -> u64 {
|
2022-02-12 10:29:38 -05:00
|
|
|
SystemTime::now()
|
|
|
|
.duration_since(SystemTime::UNIX_EPOCH)
|
|
|
|
.map(|x| x.as_secs())
|
|
|
|
.unwrap_or(0)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Check if a string contains only hex characters.
|
2023-01-22 10:49:49 -05:00
|
|
|
#[must_use] pub fn is_hex(s: &str) -> bool {
|
2022-02-12 10:29:38 -05:00
|
|
|
s.chars().all(|x| char::is_ascii_hexdigit(&x))
|
|
|
|
}
|
2022-08-17 19:34:11 -04:00
|
|
|
|
2022-12-21 14:44:50 -05:00
|
|
|
/// Check if string is a nip19 string
|
|
|
|
pub fn is_nip19(s: &str) -> bool {
|
|
|
|
s.starts_with("npub") || s.starts_with("note")
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn nip19_to_hex(s: &str) -> Result<String, bech32::Error> {
|
|
|
|
let (_hrp, data, _checksum) = bech32::decode(s)?;
|
|
|
|
let data = Vec::<u8>::from_base32(&data)?;
|
|
|
|
Ok(hex::encode(data))
|
|
|
|
}
|
|
|
|
|
2022-08-17 19:34:11 -04:00
|
|
|
/// Check if a string contains only lower-case hex chars.
|
2023-01-22 10:49:49 -05:00
|
|
|
#[must_use] pub fn is_lower_hex(s: &str) -> bool {
|
2022-08-17 19:34:11 -04:00
|
|
|
s.chars().all(|x| {
|
|
|
|
(char::is_ascii_lowercase(&x) || char::is_ascii_digit(&x)) && char::is_ascii_hexdigit(&x)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn lower_hex() {
|
|
|
|
let hexstr = "abcd0123";
|
|
|
|
assert_eq!(is_lower_hex(hexstr), true);
|
|
|
|
}
|
2022-12-21 14:44:50 -05:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn nip19() {
|
|
|
|
let hexkey = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
|
|
|
|
let nip19key = "npub180cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsyjh6w6";
|
|
|
|
assert_eq!(is_nip19(hexkey), false);
|
|
|
|
assert_eq!(is_nip19(nip19key), true);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn nip19_hex() {
|
|
|
|
let nip19key = "npub180cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsyjh6w6";
|
|
|
|
let expected = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
|
|
|
|
let got = nip19_to_hex(nip19key).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(expected, got);
|
|
|
|
}
|
2022-08-17 19:34:11 -04:00
|
|
|
}
|