Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ bip21 = { version = "0.5", features = ["std"], default-features = false, optiona

base64 = { version = "0.22.1", default-features = false, features = ["std"] }
getrandom = { version = "0.3", default-features = false }
chrono = { version = "0.4", default-features = false, features = ["clock"] }
tokio = { version = "1.39", default-features = false, features = [ "rt-multi-thread", "time", "sync", "macros", "net" ] }
tokio-util = { version = "0.7.10", default-features = false, features = ["rt"] }
esplora-client = { version = "0.12", default-features = false, features = ["tokio", "async-https-rustls"], optional = true }
Expand Down
49 changes: 21 additions & 28 deletions src/liquidity/client/lsps2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1340,11 +1340,19 @@ mod tests {
use super::*;
use std::future::poll_fn;
use std::task::Poll;
use std::time::{SystemTime, UNIX_EPOCH};

use lightning_liquidity::lsps0::ser::LSPSDateTime;

use crate::builder::NodeBuilder;
use crate::entropy::NodeEntropy;
use crate::io::test_utils::InMemoryStore;

fn datetime_from_now(offset: Duration) -> LSPSDateTime {
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
LSPSDateTime::new_from_duration_since_epoch(now + offset)
}

fn rejection_test_node() -> (crate::Node, PublicKey) {
test_node_with_fee_limit(None)
}
Expand Down Expand Up @@ -1381,10 +1389,7 @@ mod tests {
let params = LSPS2OpeningFeeParams {
min_fee_msat: 1,
proportional: 1,
valid_until: (chrono::Utc::now() + chrono::Duration::days(2))
.to_rfc3339()
.parse()
.unwrap(),
valid_until: datetime_from_now(Duration::from_secs(2 * 24 * 60 * 60)),
min_lifetime: 1,
max_client_to_self_delay: 1,
min_payment_size_msat: 1,
Expand Down Expand Up @@ -1450,11 +1455,9 @@ mod tests {
let params = |valid_until: u64| LSPS2OpeningFeeParams {
min_fee_msat: 1,
proportional: 1,
valid_until: chrono::DateTime::from_timestamp(valid_until as i64, 0)
.unwrap()
.to_rfc3339()
.parse()
.unwrap(),
valid_until: LSPSDateTime::new_from_duration_since_epoch(Duration::from_secs(
valid_until,
)),
min_lifetime: 1,
max_client_to_self_delay: 1,
min_payment_size_msat: 1,
Expand Down Expand Up @@ -1588,11 +1591,9 @@ mod tests {
params: LSPS2OpeningFeeParams {
min_fee_msat: 1,
proportional: 1,
valid_until: chrono::DateTime::from_timestamp(valid_until as i64, 0)
.unwrap()
.to_rfc3339()
.parse()
.unwrap(),
valid_until: LSPSDateTime::new_from_duration_since_epoch(Duration::from_secs(
valid_until,
)),
min_lifetime: 1,
max_client_to_self_delay: 1,
min_payment_size_msat: 1,
Expand Down Expand Up @@ -1768,11 +1769,9 @@ mod tests {
params: LSPS2OpeningFeeParams {
min_fee_msat: 1,
proportional: 1,
valid_until: chrono::DateTime::from_timestamp(valid_until as i64, 0)
.unwrap()
.to_rfc3339()
.parse()
.unwrap(),
valid_until: LSPSDateTime::new_from_duration_since_epoch(Duration::from_secs(
valid_until,
)),
min_lifetime: 1,
max_client_to_self_delay: 1,
min_payment_size_msat: 1,
Expand Down Expand Up @@ -1898,11 +1897,10 @@ mod tests {

#[test]
fn opening_params_must_cover_invoice_lifetime() {
let valid_until = chrono::Utc::now() + chrono::Duration::hours(3);
let mut params = LSPS2OpeningFeeParams {
min_fee_msat: 1,
proportional: 1,
valid_until: valid_until.to_rfc3339().parse().unwrap(),
valid_until: datetime_from_now(Duration::from_secs(3 * 60 * 60)),
min_lifetime: 1,
max_client_to_self_delay: 1,
min_payment_size_msat: 1,
Expand All @@ -1915,9 +1913,7 @@ mod tests {
assert!(!opening_fee_params_valid_for(&params, u64::MAX));

let invoice_lifetime_secs = 2 * 60 * 60;
let valid_until =
chrono::Utc::now() + chrono::Duration::seconds(invoice_lifetime_secs as i64 + 1);
params.valid_until = valid_until.to_rfc3339().parse().unwrap();
params.valid_until = datetime_from_now(Duration::from_secs(invoice_lifetime_secs + 1));
assert!(
!opening_fee_params_valid_for(&params, invoice_lifetime_secs),
"opening parameters leave no time for the buy round trip"
Expand Down Expand Up @@ -1953,10 +1949,7 @@ mod tests {
LSPS2OpeningFeeParams {
min_fee_msat: 1_500,
proportional: 0,
valid_until: (chrono::Utc::now() + chrono::Duration::days(2))
.to_rfc3339()
.parse()
.unwrap(),
valid_until: datetime_from_now(Duration::from_secs(2 * 24 * 60 * 60)),
min_lifetime: 1,
max_client_to_self_delay: 1,
min_payment_size_msat: 1,
Expand Down
10 changes: 7 additions & 3 deletions src/liquidity/service/lsps2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@

use std::ops::Deref;
use std::sync::{Arc, RwLock, Weak};
use std::time::Duration;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use bitcoin::secp256k1::PublicKey;
use bitcoin::Transaction;
use chrono::Utc;
use lightning::events::HTLCHandlingFailureType;
use lightning::ln::channelmanager::InterceptId;
use lightning::ln::types::ChannelId;
Expand Down Expand Up @@ -343,7 +342,12 @@ where
}
}

let valid_until = LSPSDateTime(Utc::now() + LSPS2_GETINFO_REQUEST_EXPIRY);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock to be ahead of the unix epoch");
let valid_until = LSPSDateTime::new_from_duration_since_epoch(
now + LSPS2_GETINFO_REQUEST_EXPIRY,
);
let opening_fee_params = LSPS2RawOpeningFeeParams {
min_fee_msat: service_config.min_channel_opening_fee_msat,
proportional: service_config.channel_opening_fee_ppm,
Expand Down
57 changes: 55 additions & 2 deletions src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use bitcoin::secp256k1::PublicKey;
use chrono::Utc;
use lightning::ln::types::ChannelId;
use lightning::types::payment::PaymentHash;
pub use lightning::util::logger::Level as LogLevel;
Expand All @@ -26,6 +26,41 @@ use log::{Level as LogFacadeLevel, Record as LogFacadeRecord};

use crate::io::utils::create_dir_all_private;

/// Displays a duration since the Unix epoch as a `YYYY-MM-DD hh:mm:ss.mmm` UTC timestamp.
struct UtcTimestamp(Duration);

impl fmt::Display for UtcTimestamp {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let secs = self.0.as_secs();
let secs_of_day = secs % 86_400;

// Converts the day count to a proleptic Gregorian date, counting years from March 1st so
// that the leap day falls at the end of the year.
let days = secs / 86_400 + 719_468;
let era = days / 146_097;
let day_of_era = days % 146_097;
let year_of_era =
(day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let shifted_month = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 };
let year = year_of_era + era * 400 + u64::from(month <= 2);

write!(
f,
"{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}",
year,
month,
day,
secs_of_day / 3_600,
secs_of_day % 3_600 / 60,
secs_of_day % 60,
self.0.subsec_millis(),
)
}
}

fn open_log_file(file_path: &str) -> std::io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
options.create(true).append(true);
Expand Down Expand Up @@ -210,9 +245,11 @@ impl LogWriter for Writer {
return;
}

let since_epoch =
SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
let log = format!(
"{} {:<5} [{}:{}] {}{}\n",
Utc::now().format("%Y-%m-%d %H:%M:%S%.3f"),
UtcTimestamp(since_epoch),
record.level.to_string(),
record.module_path,
record.line,
Expand Down Expand Up @@ -324,6 +361,22 @@ mod tests {
#[cfg(unix)]
use crate::io::test_utils::random_storage_path;

#[test]
fn formats_utc_timestamps() {
for (secs, millis, expected) in [
(0, 0, "1970-01-01 00:00:00.000"),
(951782399, 999, "2000-02-28 23:59:59.999"),
(951782400, 0, "2000-02-29 00:00:00.000"),
(1709251199, 7, "2024-02-29 23:59:59.007"),
(1709251200, 0, "2024-03-01 00:00:00.000"),
(1794960000, 123, "2026-11-18 00:00:00.123"),
(4102444799, 50, "2099-12-31 23:59:59.050"),
] {
let since_epoch = Duration::from_secs(secs) + Duration::from_millis(millis);
assert_eq!(UtcTimestamp(since_epoch).to_string(), expected);
}
}

#[cfg(unix)]
#[test]
fn creates_private_log_file() {
Expand Down
37 changes: 34 additions & 3 deletions tests/common/logging.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

use chrono::Utc;
use ldk_node::logger::{LogContext, LogLevel, LogRecord, LogWriter};
#[cfg(not(feature = "uniffi"))]
use log::Record as LogFacadeRecord;
Expand All @@ -19,6 +19,37 @@ impl Default for TestLogWriter {
}
}

/// Returns the current UTC time formatted as `YYYY-MM-DD hh:mm:ss.mmm`.
fn utc_timestamp_now() -> String {
let since_epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let secs = since_epoch.as_secs();
let secs_of_day = secs % 86_400;

// Converts the day count to a proleptic Gregorian date, counting years from March 1st so
// that the leap day falls at the end of the year.
let days = secs / 86_400 + 719_468;
let era = days / 146_097;
let day_of_era = days % 146_097;
let year_of_era =
(day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let shifted_month = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 };
let year = year_of_era + era * 400 + u64::from(month <= 2);

format!(
"{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}",
year,
month,
day,
secs_of_day / 3_600,
secs_of_day % 3_600 / 60,
secs_of_day % 60,
since_epoch.subsec_millis(),
)
}

pub(crate) struct MockLogFacadeLogger {
logs: Arc<Mutex<Vec<String>>>,
}
Expand All @@ -41,7 +72,7 @@ impl LogFacadeLog for MockLogFacadeLogger {
fn log(&self, record: &log::Record) {
let message = format!(
"{} {:<5} [{}:{}] {}",
Utc::now().format("%Y-%m-%d %H:%M:%S"),
&utc_timestamp_now()[.."YYYY-MM-DD hh:mm:ss".len()],
record.level().to_string(),
record.module_path().unwrap(),
record.line().unwrap(),
Expand Down Expand Up @@ -158,7 +189,7 @@ impl LogWriter for MultiNodeLogger {
let log = format!(
"[{}] {} {:<5} [{}:{}] {}{}\n",
self.node_id,
Utc::now().format("%Y-%m-%d %H:%M:%S%.3f"),
utc_timestamp_now(),
record.level.to_string(),
record.module_path,
record.line,
Expand Down
Loading