lightning_liquidity/utils/
mod.rs

1//! Utilities for LSPS5 service.
2
3use alloc::string::String;
4use core::{fmt::Write, ops::Deref};
5
6use lightning::sign::EntropySource;
7
8use crate::lsps0::ser::LSPSRequestId;
9
10#[allow(dead_code)]
11#[allow(unused_imports)]
12pub(crate) mod async_poll;
13pub mod time;
14
15/// Converts a human-readable string representation of a short channel ID (SCID)
16pub fn scid_from_human_readable_string(human_readable_scid: &str) -> Result<u64, ()> {
17	let mut parts = human_readable_scid.split('x');
18
19	let block: u64 = parts.next().ok_or(())?.parse().map_err(|_e| ())?;
20	let tx_index: u64 = parts.next().ok_or(())?.parse().map_err(|_e| ())?;
21	let vout_index: u64 = parts.next().ok_or(())?.parse().map_err(|_e| ())?;
22
23	Ok((block << 40) | (tx_index << 16) | vout_index)
24}
25
26pub(crate) fn generate_request_id<ES: Deref>(entropy_source: &ES) -> LSPSRequestId
27where
28	ES::Target: EntropySource,
29{
30	let bytes = entropy_source.get_secure_random_bytes();
31	LSPSRequestId(hex_str(&bytes[0..16]))
32}
33
34#[inline]
35/// Converts a byte slice to a hexadecimal string representation.
36pub fn hex_str(value: &[u8]) -> String {
37	let mut res = String::with_capacity(2 * value.len());
38	for v in value {
39		write!(&mut res, "{:02x}", v).expect("Unable to write");
40	}
41	res
42}
43
44#[cfg(test)]
45mod tests {
46	use super::*;
47	use lightning::util::scid_utils::{block_from_scid, tx_index_from_scid, vout_from_scid};
48
49	#[test]
50	fn parses_human_readable_scid_correctly() {
51		let block = 140;
52		let tx_index = 123;
53		let vout = 22;
54
55		let human_readable_scid = format!("{}x{}x{}", block, tx_index, vout);
56
57		let scid = scid_from_human_readable_string(&human_readable_scid).unwrap();
58
59		assert_eq!(block_from_scid(scid), block);
60		assert_eq!(tx_index_from_scid(scid), tx_index);
61		assert_eq!(vout_from_scid(scid), vout);
62	}
63}