From e5595ca1c293f420e540cedd4c1c29dc1bd262a1 Mon Sep 17 00:00:00 2001 From: kenbak wan Date: Sat, 21 Nov 2026 08:56:38 -0300 Subject: [PATCH 1/2] Upgrade sqlx to 0.9.1 and drop the RUSTSEC-2026-0459 ignore sqlx 0.9.1 allows libsqlite3-sys 0.40.0, which bundles SQLite 3.54.1 and fixes the WAL page-size disclosure, so the audit exemption is removed. Also bump actix-http 3.21.0 -> 3.22.0 for RUSTSEC-2026-0552/0553/0554 (chunked-trailer, chunk-extension and keep-alive header-timeout issues, published 2026-11-16). libsqlite3-sys keeps the same feature set (bundled, unlock_notify). New lock entries (libredox, objc2-*, etcetera) are not compiled for any target. --- .github/workflows/audit.yml | 8 +--- Cargo.lock | 75 ++++++++++++++++++++++++++----------- 2 files changed, 55 insertions(+), 28 deletions(-) diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml index cc15ede..a48532a 100644 --- a/.github/workflows/audit.yml +++ b/.github/workflows/audit.yml @@ -16,10 +16,4 @@ jobs: # optional MySQL RSA dependencies in Cargo.lock; atomic-polyfill is for # embedded AVR/ARM targets. Assert the deployment graph before exempting. - run: python3 scripts/check-dependency-exposure.py - # RUSTSEC-2026-0459 (bundled SQLite < 3.54 WAL page-size disclosure) is - # local-only: it needs a less-trusted party to write the DB/-wal pair the - # process opens. The API opens only its own database under its service - # user. Owner-approved 2026-11-14. sqlx 0.9.0 still caps libsqlite3-sys - # below 0.38; remove this ignore with sqlx 0.9.1, which allows - # libsqlite3-sys 0.39 (https://github.com/launchbadge/sqlx/pull/4517). - - run: cargo audit --deny unmaintained --deny unsound --ignore RUSTSEC-2023-0071 --ignore RUSTSEC-2023-0089 --ignore RUSTSEC-2026-0459 + - run: cargo audit --deny unmaintained --deny unsound --ignore RUSTSEC-2023-0071 --ignore RUSTSEC-2023-0089 diff --git a/Cargo.lock b/Cargo.lock index 7b3471c..94bbff4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -48,9 +48,9 @@ dependencies = [ [[package]] name = "actix-http" -version = "3.21.0" +version = "3.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3422032be73eeb15bafdb64086386385875b653eb418a80241d1f98473e86ea6" +checksum = "50f98f47b03911915aa3f0b856749aa3d3915033afabb295ab6ac5ff3b8bd5c1" dependencies = [ "actix-codec", "actix-service", @@ -1944,11 +1944,20 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + [[package]] name = "libsqlite3-sys" -version = "0.30.1" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" dependencies = [ "cc", "pkg-config", @@ -2210,6 +2219,24 @@ dependencies = [ "autocfg", ] +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", +] + [[package]] name = "oid-registry" version = "0.7.1" @@ -3044,9 +3071,9 @@ dependencies = [ [[package]] name = "sqlx" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "378620ccc25c62c89d8be1c819e76a88d59bdcc3304733330788948e619bfd71" +checksum = "edb1dddfbdfe5fb99dba0541a87b2edb8adbd59e45815db22d32d4fbbb8813dd" dependencies = [ "sqlx-core", "sqlx-macros", @@ -3057,9 +3084,9 @@ dependencies = [ [[package]] name = "sqlx-core" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb" +checksum = "c08f9787cc5aff062567dea2205f8ae37a617b04342633ab4f74944858ea6072" dependencies = [ "base64 0.22.1", "bytes", @@ -3081,7 +3108,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.1", "smallvec", "thiserror 2.0.20", "tokio", @@ -3093,9 +3120,9 @@ dependencies = [ [[package]] name = "sqlx-macros" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd2b84f2bc39a5705ef27ec785a11c934a41bbd4a24941e257927cddc26b60bf" +checksum = "bf62c58a1e7fd6031ee684eee21d07572f5aebe71c273a01ae4f04eeeba47c47" dependencies = [ "proc-macro2", "quote", @@ -3106,9 +3133,9 @@ dependencies = [ [[package]] name = "sqlx-macros-core" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb8d96de5fdc85a5c4ec813432b523ec637e80ba98f046555f75f7908ddac7c3" +checksum = "c1ff75c9d609ac84aa8a3e0d92b5c0c54bf541a7f70db492fb40c9a4bea792c8" dependencies = [ "cfg-if", "dotenvy", @@ -3119,7 +3146,7 @@ dependencies = [ "quote", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.1", "sqlx-core", "sqlx-mysql", "sqlx-postgres", @@ -3131,9 +3158,9 @@ dependencies = [ [[package]] name = "sqlx-mysql" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90b8020fe17c5f2c245bfa2505d7ef59c5604839527c740266ad2214acebea27" +checksum = "19eeb93b96eb10a3a59dfb436f3daf87d2fc41168ed9e9dc153ec8257dd6a761" dependencies = [ "bitflags", "byteorder", @@ -3159,9 +3186,9 @@ dependencies = [ [[package]] name = "sqlx-postgres" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e" +checksum = "b0e9e02f764a1fe640eeefc8eb33eeddd274204654ec9f2db8ff851a1dee2364" dependencies = [ "atoi", "base64 0.22.1", @@ -3196,9 +3223,9 @@ dependencies = [ [[package]] name = "sqlx-sqlite" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488e99c397a62007e4229aec669a179816339afc6d2620ca6fa420dbee2e982c" +checksum = "88b6b78a34ddcb1db4046d462db8f79cee811019d7297b99fca8fac5de26672e" dependencies = [ "atoi", "chrono", @@ -3325,7 +3352,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", "windows-sys 0.61.2", @@ -3971,6 +3998,12 @@ name = "whoami" version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +dependencies = [ + "libc", + "libredox", + "objc2-system-configuration", + "web-sys", +] [[package]] name = "winapi" From 431bec7038271aa62afb20bfa293a5db1765194c Mon Sep 17 00:00:00 2001 From: kenbak wan Date: Sat, 21 Nov 2026 09:19:38 -0300 Subject: [PATCH 2/2] Replace unmaintained chrono with time (RUSTSEC-2026-0543) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit chrono is flagged unmaintained and cargo audit --deny unmaintained fails on it. Timestamps are stored as TEXT and compared lexically in SQL, so a new src/timefmt.rs keeps every string byte-for-byte: - format_z: %Y-%m-%dT%H:%M:%SZ (whole seconds, UTC) - format_naive / format_naive_minutes: %Y-%m-%dT%H:%M[:%S] - to_rfc3339: chrono's AutoSi fraction with +00:00 - rfc3339_secs_z / rfc3339_millis_z: to_rfc3339_opts(Secs|Millis, true) - serialize_rfc3339_z: chrono's serde output for ZecRates.updated_at - parse_rfc3339 / parse_z / parse_naive: chrono's parser leniency for T/t/space separators, extra fraction digits, ±HH:MM offsets and one-digit fields in parse_from_str formats Golden tests were captured from chrono 0.4.45. Known differences: a leap second (:60) parses as the end of :59, and parse_from_str inputs with a leading space, a '+' year or a non-four-digit year are rejected. sqlx's unused chrono feature is dropped. chrono, iana-time-zone and their platform crates leave Cargo.lock. --- Cargo.lock | 88 +------ Cargo.toml | 4 +- src/api/admin.rs | 1 + src/api/auth.rs | 12 +- src/api/billing_routes.rs | 2 +- src/api/invoice_routes.rs | 12 +- src/api/luma.rs | 13 +- src/api/mod.rs | 7 +- src/api/passkey.rs | 23 +- src/api/pos.rs | 6 +- src/api/subscriptions.rs | 8 +- src/api/system.rs | 2 +- src/billing/fee_ledger.rs | 4 +- src/billing/mod.rs | 42 ++-- src/crosschain.rs | 31 +-- src/crosschain/fees.rs | 12 +- src/crosschain/signatures.rs | 5 +- src/crosschain/tests.rs | 51 ++-- src/email.rs | 3 +- src/events/mod.rs | 12 +- src/invoices/mod.rs | 42 ++-- src/invoices/pricing.rs | 10 +- src/main.rs | 1 + src/merchants/mod.rs | 18 +- src/scanner/mod.rs | 19 +- src/subscriptions/mod.rs | 125 ++++------ src/tickets/mod.rs | 3 +- src/timefmt.rs | 470 +++++++++++++++++++++++++++++++++++ src/webhooks/mod.rs | 18 +- 29 files changed, 703 insertions(+), 341 deletions(-) create mode 100644 src/timefmt.rs diff --git a/Cargo.lock b/Cargo.lock index 94bbff4..0fda175 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -342,15 +342,6 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - [[package]] name = "anyhow" version = "1.0.104" @@ -624,20 +615,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - [[package]] name = "cipher" version = "0.4.4" @@ -674,7 +651,6 @@ dependencies = [ "base64 0.22.1", "bech32", "bs58", - "chrono", "dotenvy", "ed25519-dalek", "futures", @@ -692,6 +668,7 @@ dependencies = [ "sqlx", "subtle", "thiserror 2.0.20", + "time", "tokio", "tokio-tungstenite", "tracing", @@ -1689,30 +1666,6 @@ dependencies = [ "windows-registry", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.3.0" @@ -3091,7 +3044,6 @@ dependencies = [ "base64 0.22.1", "bytes", "cfg-if", - "chrono", "crc", "crossbeam-queue", "either", @@ -3165,7 +3117,6 @@ dependencies = [ "bitflags", "byteorder", "bytes", - "chrono", "crc", "digest 0.11.3", "dotenvy", @@ -3194,7 +3145,6 @@ dependencies = [ "base64 0.22.1", "bitflags", "byteorder", - "chrono", "crc", "dotenvy", "etcetera", @@ -3228,7 +3178,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88b6b78a34ddcb1db4046d462db8f79cee811019d7297b99fca8fac5de26672e" dependencies = [ "atoi", - "chrono", "flume", "form_urlencoded", "futures-channel", @@ -4027,41 +3976,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "windows-link" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index f8ceca4..ff857ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ actix-governor = "0.7" tokio = { version = "1", features = ["full"] } # Database (SQLite for local dev, Postgres for production) -sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite-bundled", "sqlite-unlock-notify", "derive", "uuid", "chrono", "json"] } +sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite-bundled", "sqlite-unlock-notify", "derive", "uuid", "json"] } # Serialization serde = { version = "1", features = ["derive"] } @@ -64,7 +64,7 @@ qrcode = "0.14" image = { version = "0.25", default-features = false, features = ["png"] } # Time -chrono = { version = "0.4", features = ["serde"] } +time = "0.3" # UUID uuid = { version = "1", features = ["v4", "serde"] } diff --git a/src/api/admin.rs b/src/api/admin.rs index 217667c..256b44c 100644 --- a/src/api/admin.rs +++ b/src/api/admin.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; use actix_web::web; use hmac::{Hmac, Mac}; use serde::Deserialize; diff --git a/src/api/auth.rs b/src/api/auth.rs index 509b09d..dd3d9a9 100644 --- a/src/api/auth.rs +++ b/src/api/auth.rs @@ -1,6 +1,7 @@ +use crate::timefmt::TimestampExt; use actix_web::cookie::{Cookie, SameSite}; use actix_web::{web, HttpRequest, HttpResponse}; -use chrono::{Duration, Utc}; +use crate::timefmt::Duration; use serde::Deserialize; use sqlx::SqlitePool; use uuid::Uuid; @@ -48,9 +49,8 @@ pub async fn create_session( }; let session_id = Uuid::new_v4().to_string(); - let expires_at = (Utc::now() + Duration::hours(SESSION_HOURS)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let expires_at = (crate::timefmt::now() + Duration::hours(SESSION_HOURS)) + .format_z(); if let Err(e) = sqlx::query("INSERT INTO sessions (id, merchant_id, expires_at) VALUES (?, ?, ?)") @@ -67,7 +67,7 @@ pub async fn create_session( } // Track last token login timestamp - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); let _ = sqlx::query("UPDATE merchants SET last_token_login_at = ? WHERE id = ?") .bind(&now) .bind(&merchant.id) @@ -488,7 +488,7 @@ pub async fn retry_webhook( .json(serde_json::json!({"error": format!("Blocked: {reason}")})); } - let ts = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let ts = crate::timefmt::now().format_z(); let mut body: serde_json::Value = match serde_json::from_str(&payload) { Ok(v) => v, Err(_) => { diff --git a/src/api/billing_routes.rs b/src/api/billing_routes.rs index a05c5c7..60098ec 100644 --- a/src/api/billing_routes.rs +++ b/src/api/billing_routes.rs @@ -157,7 +157,7 @@ pub async fn billing_settle( zec_ngn: 0.0, zec_chf: 0.0, zec_inr: 0.0, - updated_at: chrono::Utc::now(), + updated_at: crate::timefmt::now(), }, }; diff --git a/src/api/invoice_routes.rs b/src/api/invoice_routes.rs index 9840031..743b0f8 100644 --- a/src/api/invoice_routes.rs +++ b/src/api/invoice_routes.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; use actix_web::web; use actix_web_lab::sse; use base64::Engine; @@ -509,9 +510,9 @@ pub async fn ledger_by_token( } if let Some(exp) = row.get::, _>("expires_at") { if let Ok(exp_dt) = - chrono::NaiveDateTime::parse_from_str(&exp, "%Y-%m-%dT%H:%M:%SZ") + crate::timefmt::parse_z(&exp) { - if exp_dt < chrono::Utc::now().naive_utc() { + if exp_dt < crate::timefmt::now() { return not_found(); } } @@ -607,9 +608,8 @@ pub async fn create_ledger_token( } let id = uuid::Uuid::new_v4().to_string(); - let expires_at = (chrono::Utc::now() + chrono::Duration::days(expires_days)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let expires_at = (crate::timefmt::now() + crate::timefmt::Duration::days(expires_days)) + .format_z(); let result = sqlx::query( "INSERT INTO ledger_tokens (id, merchant_id, label, expires_at) VALUES (?, ?, ?, ?)", @@ -647,7 +647,7 @@ pub async fn revoke_ledger_token( }; let token_id = path.into_inner(); - let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); let result = sqlx::query( "UPDATE ledger_tokens SET revoked_at = ? WHERE id = ? AND merchant_id = ? AND revoked_at IS NULL", diff --git a/src/api/luma.rs b/src/api/luma.rs index 1d6c6ec..231c0e2 100644 --- a/src/api/luma.rs +++ b/src/api/luma.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; use actix_web::{web, HttpRequest, HttpResponse}; use sqlx::SqlitePool; @@ -6,7 +7,7 @@ use crate::events::parse_event_datetime; /// Normalize a Luma ISO 8601 datetime (e.g. "2026-04-01T15:00:00.000Z") to "YYYY-MM-DDTHH:MM" fn normalize_luma_date(s: &str) -> Option { - parse_event_datetime(s).map(|dt| dt.format("%Y-%m-%dT%H:%M").to_string()) + parse_event_datetime(s).map(|dt| crate::timefmt::format_naive_minutes(dt)) } /// GET /api/luma/events -- list importable Luma events for the authenticated merchant @@ -54,7 +55,7 @@ pub async fn list_events( .into_iter() .collect(); - let now = chrono::Utc::now().naive_utc(); + let now = crate::timefmt::now(); let mut result = Vec::new(); for ev in events { @@ -65,7 +66,7 @@ pub async fn list_events( // Skip past events if let Some(ref start) = ev.start_at { if let Some(dt) = parse_event_datetime(start) { - if dt < now { + if dt.assume_utc() < now { continue; } } @@ -423,10 +424,10 @@ pub async fn sync_event( }; // Event date has passed → transition to 'past' status - let now = chrono::Utc::now().naive_utc(); + let now = crate::timefmt::now(); if let Some(ref start) = luma_event.start_at { if let Some(dt) = parse_event_datetime(start) { - if dt < now { + if dt.assume_utc() < now { tracing::info!(event_id = %event_id, "Luma event date has passed, marking as past"); sqlx::query( "UPDATE events SET status = 'past' WHERE id = ? AND status != 'cancelled'", @@ -548,7 +549,7 @@ pub async fn sync_event( .bind(&tt.name) .bind(tt.max_capacity) .bind(&tt.api_id) - .bind(chrono::Utc::now().to_rfc3339()) + .bind(crate::timefmt::now().to_rfc3339()) .execute(pool.get_ref()) .await .ok(); diff --git a/src/api/mod.rs b/src/api/mod.rs index 289603f..09a8220 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -527,11 +527,10 @@ async fn checkout( })); } if let Some(ref date_str) = event_date { - if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(date_str, "%Y-%m-%dT%H:%M:%S") - .or_else(|_| chrono::NaiveDateTime::parse_from_str(date_str, "%Y-%m-%dT%H:%M")) + if let Ok(dt) = crate::timefmt::parse_naive(date_str) { - let event_utc = dt.and_utc(); - if event_utc < chrono::Utc::now() { + let event_utc = dt.assume_utc(); + if event_utc < crate::timefmt::now() { let pool_bg = pool.clone(); let pid = product.id.clone(); tokio::spawn(async move { diff --git a/src/api/passkey.rs b/src/api/passkey.rs index 818d6f0..935f3f2 100644 --- a/src/api/passkey.rs +++ b/src/api/passkey.rs @@ -1,7 +1,8 @@ +use crate::timefmt::TimestampExt; use actix_web::{web, HttpRequest, HttpResponse}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine; -use chrono::{Duration, Utc}; +use crate::timefmt::Duration; use serde::Deserialize; use sqlx::SqlitePool; use uuid::Uuid; @@ -28,9 +29,8 @@ async fn store_challenge( state_json: &str, ) -> Result { let id = Uuid::new_v4().to_string(); - let expires_at = (Utc::now() + Duration::seconds(CHALLENGE_EXPIRY_SECS)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let expires_at = (crate::timefmt::now() + Duration::seconds(CHALLENGE_EXPIRY_SECS)) + .format_z(); sqlx::query( "INSERT INTO passkey_challenges (id, merchant_id, flow_type, state_json, expires_at) @@ -99,10 +99,10 @@ async fn check_reauth(pool: &SqlitePool, session_id: &str) -> bool { match row { Some(reauth_at) => { - if let Ok(ts) = chrono::NaiveDateTime::parse_from_str(&reauth_at, "%Y-%m-%dT%H:%M:%SZ") + if let Ok(ts) = crate::timefmt::parse_z(&reauth_at) { - let reauth_time = ts.and_utc(); - Utc::now().signed_duration_since(reauth_time).num_seconds() < REAUTH_WINDOW_SECS + let reauth_time = ts; + (crate::timefmt::now() - reauth_time).whole_seconds() < REAUTH_WINDOW_SECS } else { false } @@ -112,7 +112,7 @@ async fn check_reauth(pool: &SqlitePool, session_id: &str) -> bool { } async fn set_reauth(pool: &SqlitePool, session_id: &str) -> Result<(), sqlx::Error> { - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); sqlx::query("UPDATE sessions SET reauth_at = ? WHERE id = ?") .bind(&now) .bind(session_id) @@ -451,7 +451,7 @@ pub async fn login_complete( }; // Update counter and last_used_at - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); // Re-load and update the stored passkey with new counter if let Ok(Some(cred_json)) = sqlx::query_scalar::<_, String>( @@ -478,9 +478,8 @@ pub async fn login_complete( // Create session (same as token login) let session_id = Uuid::new_v4().to_string(); - let expires_at = (Utc::now() + chrono::Duration::hours(24)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let expires_at = (crate::timefmt::now() + crate::timefmt::Duration::hours(24)) + .format_z(); if let Err(e) = sqlx::query("INSERT INTO sessions (id, merchant_id, expires_at) VALUES (?, ?, ?)") diff --git a/src/api/pos.rs b/src/api/pos.rs index 888dc2d..6d72046 100644 --- a/src/api/pos.rs +++ b/src/api/pos.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; use actix_web::{web, HttpRequest, HttpResponse}; use serde::Deserialize; use sqlx::SqlitePool; @@ -161,9 +162,8 @@ pub async fn create_pos_session( // Create a POS-scoped session let session_id = uuid::Uuid::new_v4().to_string(); - let expires_at = (chrono::Utc::now() + chrono::Duration::hours(POS_SESSION_HOURS)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let expires_at = (crate::timefmt::now() + crate::timefmt::Duration::hours(POS_SESSION_HOURS)) + .format_z(); if let Err(e) = sqlx::query( "INSERT INTO sessions (id, merchant_id, expires_at, pos_scoped) VALUES (?, ?, ?, 1)", diff --git a/src/api/subscriptions.rs b/src/api/subscriptions.rs index 0e4ce67..308b902 100644 --- a/src/api/subscriptions.rs +++ b/src/api/subscriptions.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; use actix_web::{web, HttpRequest, HttpResponse}; use sqlx::SqlitePool; @@ -103,7 +104,7 @@ pub async fn status( match subscriptions::get_subscription(pool.get_ref(), &sub_id).await { Ok(Some(sub)) if sub.merchant_id == merchant.id => { - let is_active = sub.has_access_at(chrono::Utc::now()); + let is_active = sub.has_access_at(crate::timefmt::now()); HttpResponse::Ok().json(serde_json::json!({ "subscription_id": sub.id, @@ -267,9 +268,8 @@ pub async fn simulate_period_end( } // Fast-forward: set current_period_end to 1 hour ago - let past = (chrono::Utc::now() - chrono::Duration::hours(1)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let past = (crate::timefmt::now() - crate::timefmt::Duration::hours(1)) + .format_z(); if let Err(e) = sqlx::query("UPDATE subscriptions SET current_period_end = ? WHERE id = ?") .bind(&past) diff --git a/src/api/system.rs b/src/api/system.rs index 675ecdc..eeef937 100644 --- a/src/api/system.rs +++ b/src/api/system.rs @@ -68,7 +68,7 @@ pub async fn health( // 3. Price feed: check if rates are available and fresh let price_ok = match price_service.get_rates().await { Ok(rates) => { - let age_secs = (chrono::Utc::now() - rates.updated_at).num_seconds(); + let age_secs = (crate::timefmt::now() - rates.updated_at).whole_seconds(); if age_secs > 600 { degraded = true; checks.insert("price_feed".into(), serde_json::json!({ diff --git a/src/billing/fee_ledger.rs b/src/billing/fee_ledger.rs index c016b87..d9be626 100644 --- a/src/billing/fee_ledger.rs +++ b/src/billing/fee_ledger.rs @@ -1,4 +1,4 @@ -use chrono::Utc; +use crate::timefmt::TimestampExt; use sqlx::SqlitePool; use uuid::Uuid; @@ -30,7 +30,7 @@ pub async fn create_fee_entry( fee_rate_applied: f64, ) -> anyhow::Result<()> { let id = Uuid::new_v4().to_string(); - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); let fee_amount_zatoshis = crate::invoices::zec_to_zatoshis(fee_amount_zec)?; // The entry and aggregate must commit together. A duplicate scanner event diff --git a/src/billing/mod.rs b/src/billing/mod.rs index 8f3cf4a..459f6dd 100644 --- a/src/billing/mod.rs +++ b/src/billing/mod.rs @@ -1,8 +1,9 @@ +use crate::timefmt::TimestampExt; mod fee_ledger; mod status; mod types; -use chrono::{Duration, Utc}; +use crate::timefmt::Duration; use sqlx::SqlitePool; use uuid::Uuid; @@ -135,12 +136,11 @@ pub async fn ensure_billing_cycle( _ => config.billing_cycle_days_standard, }; - let now = Utc::now(); + let now = crate::timefmt::now(); let id = Uuid::new_v4().to_string(); - let period_start = now.format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let period_start = now.format_z(); let period_end = (now + Duration::days(cycle_days)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + .format_z(); let carried: i64 = sqlx::query_scalar( "SELECT COALESCE(SUM(outstanding_zatoshis), 0) FROM billing_cycles @@ -209,11 +209,10 @@ pub async fn create_settlement_invoice( ) -> anyhow::Result { let id = Uuid::new_v4().to_string(); let memo_code = format!("SETTLE-{}", &Uuid::new_v4().to_string()[..8].to_uppercase()); - let now = Utc::now(); + let now = crate::timefmt::now(); let expires_at = (now + Duration::days(7)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); - let created_at = now.format("%Y-%m-%dT%H:%M:%SZ").to_string(); + .format_z(); + let created_at = now.format_z(); let outstanding_zec = crate::invoices::zatoshis_to_zec(outstanding_zatoshis); let price_eur = outstanding_zec * zec_eur_rate; @@ -264,7 +263,7 @@ pub async fn process_billing_cycles( return Ok(()); } - let now_str = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now_str = crate::timefmt::now().format_z(); let enc_key = &config.encryption_key; // 1. Close expired open cycles @@ -298,9 +297,8 @@ pub async fn process_billing_cycles( "trusted" => 14, _ => 7, }; - let grace_until = (Utc::now() + Duration::days(grace_days)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let grace_until = (crate::timefmt::now() + Duration::days(grace_days)) + .format_z(); let settlement_id = create_settlement_invoice( pool, @@ -350,9 +348,8 @@ pub async fn process_billing_cycles( } // 1b. Grace period reminders (3 days before grace expires) - let reminder_threshold = (Utc::now() + Duration::days(3)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let reminder_threshold = (crate::timefmt::now() + Duration::days(3)) + .format_z(); let invoiced_cycles = sqlx::query_as::<_, BillingCycle>( "SELECT * FROM billing_cycles WHERE status = 'invoiced' AND grace_until <= ? AND grace_until > ?", ) @@ -368,9 +365,9 @@ pub async fn process_billing_cycles( { let days_left = { let grace_dt = - chrono::NaiveDateTime::parse_from_str(grace_until, "%Y-%m-%dT%H:%M:%SZ"); + crate::timefmt::parse_z(grace_until); match grace_dt { - Ok(dt) => (dt - Utc::now().naive_utc()).num_days().max(1), + Ok(dt) => (dt - crate::timefmt::now()).whole_days().max(1), Err(_) => 3, } }; @@ -450,10 +447,10 @@ pub async fn process_billing_cycles( if let Some(grace_until) = &cycle.grace_until { if let Ok(grace_dt) = - chrono::NaiveDateTime::parse_from_str(grace_until, "%Y-%m-%dT%H:%M:%SZ") + crate::timefmt::parse_z(grace_until) { let suspend_at = grace_dt + Duration::days(suspend_days); - if Utc::now().naive_utc() > suspend_at { + if crate::timefmt::now() > suspend_at { sqlx::query("UPDATE billing_cycles SET status = 'suspended' WHERE id = ?") .bind(&cycle.id) .execute(pool) @@ -513,9 +510,8 @@ pub async fn process_billing_cycles( } // 4b. Warn merchants whose discount expires in 7 days - let warning_threshold = (Utc::now() + Duration::days(7)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let warning_threshold = (crate::timefmt::now() + Duration::days(7)) + .format_z(); let warning_merchants: Vec<(String, Option)> = sqlx::query_as( "SELECT id, fee_discount_until FROM merchants WHERE fee_discount_until IS NOT NULL AND fee_discount_until > ? AND fee_discount_until <= ?", diff --git a/src/crosschain.rs b/src/crosschain.rs index e1be1da..5bde239 100644 --- a/src/crosschain.rs +++ b/src/crosschain.rs @@ -1,8 +1,9 @@ //! Invoice-bound 1Click payments. Provider status is informational: only the //! Zcash scanner may settle an invoice. Never retry an ambiguous quote creation. +use crate::timefmt::TimestampExt; use actix_web::{web, HttpResponse}; use anyhow::{bail, ensure, Context}; -use chrono::{Duration, Utc}; +use crate::timefmt::Duration; use futures::{stream, StreamExt}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -340,7 +341,7 @@ fn validate_invoice(inv: &crate::invoices::Invoice) -> anyhow::Result<()> { "Invoice is not available for a new payment" ); ensure!( - chrono::DateTime::parse_from_rfc3339(&inv.expires_at)? > Utc::now(), + crate::timefmt::parse_rfc3339(&inv.expires_at)? > crate::timefmt::now(), "Invoice has expired" ); let receiver = crate::invoices::matching::orchard_receiver(&inv.payment_address); @@ -375,7 +376,7 @@ fn quote_body( "refundTo": input.refund_address, "refundType": "ORIGIN_CHAIN", "depositType": "ORIGIN_CHAIN", "depositMode": "SIMPLE", "confidentiality": CONFIDENTIALITY, - "deadline": std::cmp::min(Utc::now() + Duration::minutes(minutes), chrono::DateTime::parse_from_rfc3339(&inv.expires_at)?.with_timezone(&Utc)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true), + "deadline": std::cmp::min(crate::timefmt::now() + Duration::minutes(minutes), crate::timefmt::parse_rfc3339(&inv.expires_at)?).rfc3339_secs_z(), "quoteWaitingTimeMs": 3000 })) } @@ -449,8 +450,8 @@ fn checked_quote( "Invalid deposit address" ); let deadline = q["deadline"].as_str().context("Missing quote deadline")?; - let until = chrono::DateTime::parse_from_rfc3339(deadline)?; - let requested = chrono::DateTime::parse_from_rfc3339( + let until = crate::timefmt::parse_rfc3339(deadline)?; + let requested = crate::timefmt::parse_rfc3339( body["deadline"] .as_str() .context("Missing requested deadline")?, @@ -458,21 +459,21 @@ fn checked_quote( // 1Click may extend committed ZEC quote lifetimes (currently by three // days). Keep our short funding window separate from provider recovery. ensure!( - until > Utc::now() && until <= requested + Duration::days(7), + until > crate::timefmt::now() && until <= requested + Duration::days(7), "Invalid quote deadline" ); let mut funding_until = until.min(requested); if !q["timeWhenInactive"].is_null() { - let inactive = chrono::DateTime::parse_from_rfc3339( + let inactive = crate::timefmt::parse_rfc3339( q["timeWhenInactive"] .as_str() .context("Invalid inactive time")?, )?; funding_until = funding_until.min(inactive); } - ensure!(funding_until > Utc::now(), "Quote is already inactive"); + ensure!(funding_until > crate::timefmt::now(), "Quote is already inactive"); payment_deadline = - json!(funding_until.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)); + json!(funding_until.rfc3339_millis_z()); } Ok(json!({ "asset": asset, "amountIn": q["amountIn"], "amountOut": q["amountOut"], @@ -696,7 +697,7 @@ pub async fn eligibility( } else { "UNKNOWN" }; - let value = json!({"state":state,"routes":routes,"hasUnknown":has_unknown,"checkedAt":Utc::now().to_rfc3339(),"validForSeconds":if has_unknown {5} else {30}}); + let value = json!({"state":state,"routes":routes,"hasUnknown":has_unknown,"checkedAt":crate::timefmt::now().to_rfc3339(),"validForSeconds":if has_unknown {5} else {30}}); *cached = Some((Instant::now(), value.clone())); HttpResponse::Ok() .insert_header(("Cache-Control", "no-store")) @@ -784,7 +785,7 @@ async fn reserve( if changed == 0 { return Ok(false); } - chrono::DateTime::parse_from_rfc3339(deadline)?; + crate::timefmt::parse_rfc3339(deadline)?; sqlx::query("UPDATE invoices SET exact_payment=1 WHERE id=?") .bind(id) .execute(&mut *tx) @@ -861,7 +862,7 @@ pub async fn create( let payload = crate::crypto::encrypt("e.to_string(), &config.encryption_key)?; let mut tx = pool.begin().await?; sqlx::query("UPDATE crosschain_attempts SET state='PENDING_DEPOSIT',payload=?,last_success=? WHERE invoice_id=?") - .bind(payload).bind(Utc::now().timestamp()).bind(&id).execute(&mut *tx).await?; + .bind(payload).bind(crate::timefmt::now().unix_timestamp()).bind(&id).execute(&mut *tx).await?; fees::bind_quote(&mut tx, &id, &response, &body).await?; tx.commit().await?; anyhow::Ok(json!({"state":"PENDING_DEPOSIT", "quote":quote, "stale":false, "canManage":true, "settlementVerified":false})) @@ -922,7 +923,7 @@ async fn read_attempt(pool: &SqlitePool, id: &str, key: &str) -> anyhow::Result< None => Value::Null, }; Ok( - json!({"state":state, "quote":quote, "stale":Utc::now().timestamp()-checked > 60, + json!({"state":state, "quote":quote, "stale":crate::timefmt::now().unix_timestamp()-checked > 60, "sendStarted": send_token.is_some(), "sentTxid": sent_txid, "settlementVerified":settlement_verified}), ) }) @@ -964,7 +965,7 @@ pub async fn status( .insert_header(("Cache-Control", "no-store")) .json(attempt); } - let now = Utc::now().timestamp(); + let now = crate::timefmt::now().unix_timestamp(); // Database lease bounds polling across browsers and API workers. let lease = sqlx::query( "UPDATE crosschain_attempts SET last_checked=? WHERE invoice_id=? AND last_checked < ?", @@ -1048,7 +1049,7 @@ pub async fn wallet_send( ensure!(a["state"] == "PENDING_DEPOSIT", "Payment already in progress"); ensure!(a["stale"] == false, "Payment status is unavailable. Wait for it to refresh before sending."); let deadline = a["quote"]["deadline"].as_str().context("No payment instructions")?; - ensure!(chrono::DateTime::parse_from_rfc3339(deadline)? > Utc::now(), "Quote expired"); + ensure!(crate::timefmt::parse_rfc3339(deadline)? > crate::timefmt::now(), "Quote expired"); let token = uuid::Uuid::new_v4().to_string(); let rows = sqlx::query("UPDATE crosschain_attempts SET send_token=? WHERE invoice_id=? AND send_token IS NULL AND state='PENDING_DEPOSIT' AND EXISTS (SELECT 1 FROM invoices WHERE id=? AND status='pending' AND received_zatoshis=0)") diff --git a/src/crosschain/fees.rs b/src/crosschain/fees.rs index 3b78074..a2b4896 100644 --- a/src/crosschain/fees.rs +++ b/src/crosschain/fees.rs @@ -404,8 +404,8 @@ async fn reconcile_status( let deadline_passed = q["providerDeadline"] .as_str() .or(q["deadline"].as_str()) - .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) - .is_some_and(|d| d < Utc::now()); + .and_then(|s| crate::timefmt::parse_rfc3339(s).ok()) + .is_some_and(|d| d < crate::timefmt::now()); if inv.status == "confirmed" && (data["status"] == "REFUNDED" || (data["status"] == "PENDING_DEPOSIT" && deadline_passed)) @@ -480,7 +480,7 @@ async fn reconcile_status( .execute(&mut *tx) .await?; sqlx::query("UPDATE crosschain_attempts SET state='SUCCESS',last_success=? WHERE invoice_id=?") - .bind(Utc::now().timestamp()) + .bind(crate::timefmt::now().unix_timestamp()) .bind(id) .execute(&mut *tx) .await?; @@ -691,7 +691,7 @@ pub fn start_worker(pool: SqlitePool, gateway: web::Data, key: String) if let Err(e) = crate::referrals::reconcile(&pool).await { tracing::error!(error=%e,"Referral reconciliation failed"); } - let now = Utc::now().timestamp(); + let now = crate::timefmt::now().unix_timestamp(); if now / 900 != last_alert { last_alert = now / 900; if let Ok(issues) = operations::issues(&pool).await { @@ -740,7 +740,7 @@ pub fn start_worker(pool: SqlitePool, gateway: web::Data, key: String) // Unverified/ambiguous attempts stay explicitly pending; // never turn a provider outage into a merchant bill. let _ = sqlx::query("UPDATE crosschain_fees SET failures=failures+1,next_check=?+MIN(3600,60*(1+failures)) WHERE invoice_id=? AND state NOT IN ('collected','direct','provider_handled')") - .bind(Utc::now().timestamp()).bind(&id).execute(&pool).await; + .bind(crate::timefmt::now().unix_timestamp()).bind(&id).execute(&pool).await; } } } @@ -962,7 +962,7 @@ mod tests { sqlx::query("INSERT INTO crosschain_fees(invoice_id,asset_id,recipient,total_bps,cipherpay_bps,failures) VALUES ('other','usdc','cipherscan.near',145,125,564)") .execute(&p).await.unwrap(); sqlx::query("UPDATE invoices SET status='expired' WHERE id='other'").execute(&p).await.unwrap(); - let now = Utc::now().timestamp(); + let now = crate::timefmt::now().unix_timestamp(); // The quoted attempt is still checked; the unquoted expired one is not. assert_eq!(due_fee_checks(&p, now).await.unwrap(), vec!["i".to_string()]); // The row is untouched and still surfaces for manual review. diff --git a/src/crosschain/signatures.rs b/src/crosschain/signatures.rs index 5eff927..b75c52a 100644 --- a/src/crosschain/signatures.rs +++ b/src/crosschain/signatures.rs @@ -51,7 +51,7 @@ pub(super) fn verify(response: &Value) -> anyhow::Result<()> { pub(super) fn verify_fresh(response: &Value) -> anyhow::Result<()> { verify(response)?; let timestamp = response["timestamp"].as_str().context("Missing quote timestamp")?; - let age = chrono::Utc::now().signed_duration_since(chrono::DateTime::parse_from_rfc3339(timestamp)?).num_seconds(); + let age = (crate::timefmt::now() - crate::timefmt::parse_rfc3339(timestamp)?).whole_seconds(); ensure!((-60..=300).contains(&age), "Stale quote signature"); Ok(()) } @@ -69,7 +69,8 @@ pub(super) fn verify_status(response: &Value) -> anyhow::Result<()> { #[cfg(test)] pub(super) fn signed(mut response: Value) -> Value { use ed25519_dalek::Signer; - response["timestamp"] = Value::String(chrono::Utc::now().to_rfc3339()); + use crate::timefmt::TimestampExt; + response["timestamp"] = Value::String(crate::timefmt::now().to_rfc3339()); let sig = ed25519_dalek::SigningKey::from_bytes(&[42;32]).sign(message(&response).unwrap().as_bytes()); response["signature"] = Value::String(format!("ed25519:{}",bs58::encode(sig.to_bytes()).into_string())); response diff --git a/src/crosschain/tests.rs b/src/crosschain/tests.rs index ca701c7..6329569 100644 --- a/src/crosschain/tests.rs +++ b/src/crosschain/tests.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; use super::*; use crate::repair_tests::{invoice, merchant, pool}; use zcash_address::unified::{Encoding, Fvk, Ufvk}; @@ -142,7 +143,7 @@ async fn confidential_gateway_never_retries_with_public_routing() { #[tokio::test] async fn reservation_is_durable_unique_and_requires_full_payment() { let (p, i) = fixture().await; - let deadline = (Utc::now() + Duration::minutes(30)).to_rfc3339(); + let deadline = (crate::timefmt::now() + Duration::minutes(30)).to_rfc3339(); let (a, b) = tokio::join!( reserve(&p, "i", &deadline, None), reserve(&p, "i", &deadline, None) @@ -175,7 +176,7 @@ async fn encrypted_attempt_survives_reload_without_changing_invoice_status() { reserve( &p, "i", - &(Utc::now() + Duration::minutes(30)).to_rfc3339(), + &(crate::timefmt::now() + Duration::minutes(30)).to_rfc3339(), None, ) .await @@ -233,7 +234,7 @@ async fn wallet_lock_requires_ownership_and_survives_reload() { let (p, _) = fixture().await; let mut config = crate::config::Config::from_env().unwrap(); config.encryption_key = "11".repeat(32); - let deadline = (Utc::now() + Duration::minutes(30)).to_rfc3339(); + let deadline = (crate::timefmt::now() + Duration::minutes(30)).to_rfc3339(); reserve(&p, "i", &deadline, None).await.unwrap(); let payload = crate::crypto::encrypt( &json!({"deadline":deadline}).to_string(), @@ -347,7 +348,7 @@ async fn strict_settlement_cannot_be_bypassed_by_a_stale_scanner_snapshot() { reserve( &p, "i", - &(Utc::now() + Duration::minutes(30)).to_rfc3339(), + &(crate::timefmt::now() + Duration::minutes(30)).to_rfc3339(), None, ) .await @@ -391,7 +392,7 @@ async fn http_flow_creates_once_and_provider_success_does_not_settle() { echo["appFees"]=json!([{"recipient":"cipherscan.near","fee":125},{"recipient":"provider.near","fee":20}]); HttpResponse::Ok().json(signatures::signed(json!({"correlationId":"test-quote","quoteRequest":echo,"quote":{ "amountIn":"130000000","amountOut":"10000000","minAmountOut":"10000000", - "depositAddress":"0x2345678901234567890123456789012345678901","deadline":(chrono::DateTime::parse_from_rfc3339(body["deadline"].as_str().unwrap()).unwrap()+Duration::days(3)).to_rfc3339(),"timeEstimate":150 + "depositAddress":"0x2345678901234567890123456789012345678901","deadline":(crate::timefmt::parse_rfc3339(body["deadline"].as_str().unwrap()).unwrap()+Duration::days(3)).to_rfc3339(),"timeEstimate":150 }}))) })) .route("/status", web::get().to(|| async { HttpResponse::Ok().json(json!({"status":"SUCCESS"})) }))) @@ -448,19 +449,19 @@ async fn http_flow_creates_once_and_provider_success_does_not_settle() { .fetch_one(&p).await.unwrap(); assert_eq!(fee_terms, (145, 125)); let funding_deadline = - chrono::DateTime::parse_from_rfc3339(first["quote"]["deadline"].as_str().unwrap()).unwrap(); + crate::timefmt::parse_rfc3339(first["quote"]["deadline"].as_str().unwrap()).unwrap(); let provider_deadline = - chrono::DateTime::parse_from_rfc3339(first["quote"]["providerDeadline"].as_str().unwrap()) + crate::timefmt::parse_rfc3339(first["quote"]["providerDeadline"].as_str().unwrap()) .unwrap(); - assert!(funding_deadline < Utc::now() + Duration::minutes(31)); - assert!(provider_deadline > Utc::now() + Duration::days(2)); + assert!(funding_deadline < crate::timefmt::now() + Duration::minutes(31)); + assert!(provider_deadline > crate::timefmt::now() + Duration::days(2)); let invoice = crate::invoices::get_invoice(&p, "i") .await .unwrap() .unwrap(); assert!( - chrono::DateTime::parse_from_rfc3339(&invoice.expires_at).unwrap() - == chrono::DateTime::parse_from_rfc3339("2099-01-01T00:00:00Z").unwrap() + crate::timefmt::parse_rfc3339(&invoice.expires_at).unwrap() + == crate::timefmt::parse_rfc3339("2099-01-01T00:00:00Z").unwrap() ); let second: Value = test::call_and_read_body_json( @@ -709,27 +710,27 @@ async fn committed_quote_extension_keeps_funding_window_bounded() { let (_, i) = fixture().await; let body = quote_body(&i, &input(), &asset(), false).unwrap(); let requested = - chrono::DateTime::parse_from_rfc3339(body["deadline"].as_str().unwrap()).unwrap(); + crate::timefmt::parse_rfc3339(body["deadline"].as_str().unwrap()).unwrap(); let provider = (requested + Duration::days(3)).to_rfc3339(); let mut response = json!({"quoteRequest":body,"quote":{"amountIn":"5490787","amountOut":"10000000","minAmountOut":"10000000","depositAddress":input().refund_address,"deadline":provider,"timeWhenInactive":provider}}); let checked = checked_quote(&response, &body, &asset(), false).unwrap(); assert_eq!( - chrono::DateTime::parse_from_rfc3339(checked["deadline"].as_str().unwrap()).unwrap(), + crate::timefmt::parse_rfc3339(checked["deadline"].as_str().unwrap()).unwrap(), requested ); assert_eq!(checked["providerDeadline"], provider); let earlier = - (Utc::now() + Duration::minutes(5)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true); + (crate::timefmt::now() + Duration::minutes(5)).rfc3339_millis_z(); response["quote"]["timeWhenInactive"] = json!(earlier); assert_eq!( checked_quote(&response, &body, &asset(), false).unwrap()["deadline"], earlier ); - response["quote"]["timeWhenInactive"] = json!((Utc::now() - Duration::seconds(1)).to_rfc3339()); + response["quote"]["timeWhenInactive"] = json!((crate::timefmt::now() - Duration::seconds(1)).to_rfc3339()); assert!(checked_quote(&response, &body, &asset(), false).is_err()); response["quote"]["timeWhenInactive"] = Value::Null; for deadline in [ - (Utc::now() - Duration::seconds(1)).to_rfc3339(), + (crate::timefmt::now() - Duration::seconds(1)).to_rfc3339(), (requested + Duration::days(8)).to_rfc3339(), "invalid".into(), ] { @@ -754,7 +755,7 @@ async fn public_invoice_marks_crosschain_without_exposing_swap_details() { reserve( &p, "i", - &(Utc::now() + Duration::minutes(30)).to_rfc3339(), + &(crate::timefmt::now() + Duration::minutes(30)).to_rfc3339(), None, ) .await @@ -777,7 +778,7 @@ async fn merchant_invoice_tag_is_scoped_and_preserves_received_amount() { reserve( &p, "i", - &(Utc::now() + Duration::minutes(30)).to_rfc3339(), + &(crate::timefmt::now() + Duration::minutes(30)).to_rfc3339(), None, ) .await @@ -868,7 +869,7 @@ async fn unused_reservation_preserves_and_resolves_direct_fee_obligation() { async fn quote_never_extends_direct_price_lock_and_recovery_accepts_only_delivery() { let (p, _) = fixture().await; let original = - (Utc::now() + Duration::minutes(2)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true); + (crate::timefmt::now() + Duration::minutes(2)).rfc3339_secs_z(); sqlx::query("UPDATE invoices SET expires_at=? WHERE id='i'") .bind(&original) .execute(&p) @@ -877,7 +878,7 @@ async fn quote_never_extends_direct_price_lock_and_recovery_accepts_only_deliver reserve( &p, "i", - &(Utc::now() + Duration::days(3)).to_rfc3339(), + &(crate::timefmt::now() + Duration::days(3)).to_rfc3339(), None, ) .await @@ -970,7 +971,7 @@ async fn public_invoice_cannot_create_adopt_or_lock_a_swap() { reserve( &p, "i", - &(Utc::now() + Duration::minutes(30)).to_rfc3339(), + &(crate::timefmt::now() + Duration::minutes(30)).to_rfc3339(), None, ) .await @@ -1023,8 +1024,8 @@ async fn private_swap_details_require_the_invoice_capability_for_every_state() { use actix_web::{test,App}; let (p,_)=fixture().await; let mut config=crate::config::Config::from_env().unwrap();config.encryption_key="11".repeat(32); - reserve(&p,"i",&(Utc::now()+Duration::minutes(10)).to_rfc3339(),None).await.unwrap(); - let payload=crate::crypto::encrypt(&json!({"asset":asset(),"refundAddress":"private-refund","depositAddress":"private-deposit","depositMemo":"private-memo","amountIn":"123","deadline":(Utc::now()+Duration::minutes(10)).to_rfc3339()}).to_string(),&config.encryption_key).unwrap(); + reserve(&p,"i",&(crate::timefmt::now()+Duration::minutes(10)).to_rfc3339(),None).await.unwrap(); + let payload=crate::crypto::encrypt(&json!({"asset":asset(),"refundAddress":"private-refund","depositAddress":"private-deposit","depositMemo":"private-memo","amountIn":"123","deadline":(crate::timefmt::now()+Duration::minutes(10)).to_rfc3339()}).to_string(),&config.encryption_key).unwrap(); let gateway=Gateway{enabled:true,fee_recipient:None,key:String::new(),base:"http://127.0.0.1:1".into(),client:reqwest::Client::new(), confirmation_client: reqwest::Client::new(), cipherscan_api_url: "http://127.0.0.1:1".into(),tokens:Mutex::new(None),eligibility:Mutex::new(HashMap::new()),eligibility_slots:Semaphore::new(4)}; let app=test::init_service(App::new().app_data(web::Data::new(p.clone())).app_data(web::Data::new(config)).app_data(web::Data::new(gateway)).route("/{id}",web::get().to(status))).await; let token=security::token(&p,"i").await.unwrap(); @@ -1058,7 +1059,7 @@ async fn disabling_crosschain_blocks_new_reservations_but_preserves_existing_dep use actix_web::{test,App}; let (p,_)=fixture().await; assert!(operations::enabled(&p,"i").await.unwrap()); - let deadline=(Utc::now()+Duration::minutes(10)).to_rfc3339(); + let deadline=(crate::timefmt::now()+Duration::minutes(10)).to_rfc3339(); sqlx::query("UPDATE merchants SET crosschain_enabled=0 WHERE id='m'").execute(&p).await.unwrap(); assert!(!reserve(&p,"i",&deadline,None).await.unwrap()); let config=crate::config::Config::from_env().unwrap(); @@ -1079,7 +1080,7 @@ async fn interrupted_setup_is_reported_and_cannot_be_retried_as_a_new_quote() { use actix_web::{test,App}; let (p,_)=fixture().await; let mut config=crate::config::Config::from_env().unwrap();config.admin_key=Some("test-admin".into()); - reserve(&p,"i",&(Utc::now()+Duration::minutes(10)).to_rfc3339(),None).await.unwrap(); + reserve(&p,"i",&(crate::timefmt::now()+Duration::minutes(10)).to_rfc3339(),None).await.unwrap(); sqlx::query("UPDATE crosschain_attempts SET state='NEEDS_REVIEW' WHERE invoice_id='i'").execute(&p).await.unwrap(); let issues=operations::issues(&p).await.unwrap();assert_eq!(issues[0]["reason"],"setup_review"); let app=test::init_service(App::new().app_data(web::Data::new(p.clone())).app_data(web::Data::new(config)).route("/issues",web::get().to(operations::admin_issues)).route("/{id}",web::post().to(operations::retry))).await; diff --git a/src/email.rs b/src/email.rs index dacf34b..8097337 100644 --- a/src/email.rs +++ b/src/email.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; use sqlx::SqlitePool; use uuid::Uuid; @@ -87,7 +88,7 @@ async fn email_already_sent( /// Record that an email was sent (insert-or-ignore for idempotency). async fn record_email_sent(pool: &SqlitePool, merchant_id: &str, template: &str, entity_id: &str) { let id = Uuid::new_v4().to_string(); - let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); sqlx::query( "INSERT OR IGNORE INTO email_events (id, merchant_id, template, entity_id, sent_at) VALUES (?, ?, ?, ?, ?)", ) diff --git a/src/events/mod.rs b/src/events/mod.rs index 30b7a78..1b6b94c 100644 --- a/src/events/mod.rs +++ b/src/events/mod.rs @@ -1,4 +1,4 @@ -use chrono::Utc; +use crate::timefmt::TimestampExt; use serde::{Deserialize, Serialize}; use sqlx::{FromRow, SqlitePool}; use thiserror::Error; @@ -98,8 +98,8 @@ fn validation_error(message: impl Into) -> anyhow::Error { } /// Parse event_date strings in either "YYYY-MM-DDTHH:MM:SS" or "YYYY-MM-DDTHH:MM" format. -/// Returns the parsed NaiveDateTime if valid. -pub fn parse_event_datetime(s: &str) -> Option { +/// Returns the parsed date-time (no offset) if valid. +pub fn parse_event_datetime(s: &str) -> Option { // Strip trailing 'Z' and fractional seconds to normalize ISO 8601 variants let s = s.trim_end_matches('Z'); let s = if let Some(dot) = s.rfind('.') { @@ -107,9 +107,7 @@ pub fn parse_event_datetime(s: &str) -> Option { } else { s }; - chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") - .or_else(|_| chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M")) - .ok() + crate::timefmt::parse_naive(s).ok() } fn slugify(name: &str) -> String { @@ -589,7 +587,7 @@ pub async fn get_event_detail( } pub async fn mark_past_events(pool: &SqlitePool) -> anyhow::Result { - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); // Also deactivate the backing products so no new checkouts can be created sqlx::query( diff --git a/src/invoices/mod.rs b/src/invoices/mod.rs index c7141ea..0cb5a80 100644 --- a/src/invoices/mod.rs +++ b/src/invoices/mod.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; mod amounts; pub mod matching; pub mod pricing; @@ -5,7 +6,7 @@ mod queries; mod types; use base64::Engine; -use chrono::{Duration, Utc}; +use crate::timefmt::Duration; use sqlx::SqlitePool; use uuid::Uuid; @@ -54,10 +55,9 @@ pub async fn create_invoice( price_zec * rates.zec_usd }; - let expires_at = (Utc::now() + Duration::minutes(expiry_minutes)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); - let created_at = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let expires_at = (crate::timefmt::now() + Duration::minutes(expiry_minutes)) + .format_z(); + let created_at = crate::timefmt::now().format_z(); let div_index = crate::merchants::next_diversifier_index(pool, merchant_id).await?; let derived = crate::addresses::derive_invoice_address(merchant_ufvk, div_index)?; @@ -219,10 +219,9 @@ pub async fn mark_detected( txid: &str, received_zatoshis: i64, ) -> anyhow::Result { - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); - let new_expires = (Utc::now() + Duration::minutes(30)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let now = crate::timefmt::now().format_z(); + let new_expires = (crate::timefmt::now() + Duration::minutes(30)) + .format_z(); let result = sqlx::query( "UPDATE invoices SET status = 'detected', detected_txid = ?, detected_at = ?, received_zatoshis = ?, expires_at = ? WHERE id = ? AND status IN ('pending', 'underpaid') @@ -252,7 +251,7 @@ pub async fn mark_confirmed( confirmed_rate: Option, confirmed_fiat_amount: Option, ) -> anyhow::Result { - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); let result = sqlx::query( "UPDATE invoices SET status = 'confirmed', confirmed_at = ?, confirmed_rate = ?, confirmed_fiat_amount = ? @@ -277,7 +276,7 @@ pub async fn mark_refunded( invoice_id: &str, refund_txid: Option<&str>, ) -> anyhow::Result<()> { - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); sqlx::query( "UPDATE invoices SET status = 'refunded', refunded_at = ?, refund_txid = ? WHERE id = ? AND status = 'confirmed'", @@ -326,10 +325,9 @@ pub async fn mark_underpaid( received_zatoshis: i64, txid: &str, ) -> anyhow::Result<()> { - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); - let new_expires = (Utc::now() + Duration::minutes(10)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let now = crate::timefmt::now().format_z(); + let new_expires = (crate::timefmt::now() + Duration::minutes(10)) + .format_z(); sqlx::query( "UPDATE invoices SET status = 'underpaid', received_zatoshis = ?, detected_txid = ?, detected_at = ?, expires_at = ? @@ -383,9 +381,8 @@ pub async fn record_payment( .fetch_one(pool) .await?; - let new_expires = (Utc::now() + Duration::minutes(10)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let new_expires = (crate::timefmt::now() + Duration::minutes(10)) + .format_z(); sqlx::query( "UPDATE invoices SET received_zatoshis = ?, expires_at = ? WHERE id = ? AND status IN ('pending', 'underpaid')", @@ -433,7 +430,7 @@ pub async fn create_draft_invoice( ) -> anyhow::Result { let id = Uuid::new_v4().to_string(); let memo_code = generate_memo_code(); - let created_at = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let created_at = crate::timefmt::now().format_z(); let div_index = crate::merchants::next_diversifier_index(pool, merchant_id).await?; let derived = crate::addresses::derive_invoice_address(merchant_ufvk, div_index)?; @@ -510,7 +507,7 @@ pub async fn finalize_invoice( if let Some(ref sub_id) = invoice.subscription_id { let sub = crate::subscriptions::get_subscription(pool, sub_id).await?; if let Some(s) = sub { - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); if now >= s.current_period_end { anyhow::bail!("Subscription billing period has ended"); } @@ -547,9 +544,8 @@ pub async fn finalize_invoice( }; let price_zatoshis = zec_to_zatoshis(price_zec)?; - let expires_at = (Utc::now() + Duration::minutes(15)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let expires_at = (crate::timefmt::now() + Duration::minutes(15)) + .format_z(); let memo_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(invoice.memo_code.as_bytes()); diff --git a/src/invoices/pricing.rs b/src/invoices/pricing.rs index 47c57c7..38b896c 100644 --- a/src/invoices/pricing.rs +++ b/src/invoices/pricing.rs @@ -1,4 +1,3 @@ -use chrono::{DateTime, Utc}; use serde::Serialize; use std::sync::Arc; use tokio::sync::RwLock; @@ -16,7 +15,8 @@ pub struct ZecRates { pub zec_ngn: f64, pub zec_chf: f64, pub zec_inr: f64, - pub updated_at: DateTime, + #[serde(serialize_with = "crate::timefmt::serialize_rfc3339_z")] + pub updated_at: crate::timefmt::OffsetDateTime, } impl ZecRates { @@ -64,7 +64,7 @@ impl PriceService { { let cache = self.cached.read().await; if let Some(rates) = &*cache { - let age = (Utc::now() - rates.updated_at).num_seconds() as u64; + let age = (crate::timefmt::now() - rates.updated_at).whole_seconds() as u64; if age < self.cache_secs { return Ok(rates.clone()); } @@ -87,7 +87,7 @@ impl PriceService { Err(e) => { let cache = self.cached.read().await; if let Some(stale) = &*cache { - tracing::warn!(error = %e, age_secs = (Utc::now() - stale.updated_at).num_seconds(), "CoinGecko unavailable, using last known rate"); + tracing::warn!(error = %e, age_secs = (crate::timefmt::now() - stale.updated_at).whole_seconds(), "CoinGecko unavailable, using last known rate"); return Ok(stale.clone()); } tracing::error!(error = %e, "CoinGecko unavailable and no cached rate — prices will be inaccurate"); @@ -141,7 +141,7 @@ impl PriceService { zec_ngn: zec["ngn"].as_f64().unwrap_or(0.0), zec_chf: zec["chf"].as_f64().unwrap_or(0.0), zec_inr: zec["inr"].as_f64().unwrap_or(0.0), - updated_at: Utc::now(), + updated_at: crate::timefmt::now(), }) } } diff --git a/src/main.rs b/src/main.rs index d127626..2feedc1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,6 +21,7 @@ mod scanner; mod sessions; mod subscriptions; mod tickets; +mod timefmt; mod validation; mod webhooks; diff --git a/src/merchants/mod.rs b/src/merchants/mod.rs index 65eff28..0f3a5fd 100644 --- a/src/merchants/mod.rs +++ b/src/merchants/mod.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use sqlx::SqlitePool; @@ -495,9 +496,8 @@ pub async fn recovery_recently_requested( pool: &SqlitePool, merchant_id: &str, ) -> anyhow::Result { - let cutoff = (chrono::Utc::now() - chrono::Duration::minutes(RECOVERY_EMAIL_COOLDOWN_MINUTES)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let cutoff = (crate::timefmt::now() - crate::timefmt::Duration::minutes(RECOVERY_EMAIL_COOLDOWN_MINUTES)) + .format_z(); let recent: Option<(i64,)> = sqlx::query_as( "SELECT 1 FROM recovery_tokens WHERE merchant_id = ? AND created_at > ? LIMIT 1", ) @@ -512,9 +512,8 @@ pub async fn create_recovery_token(pool: &SqlitePool, merchant_id: &str) -> anyh let token = Uuid::new_v4().to_string(); let token_hash = hash_key(&token); let id = Uuid::new_v4().to_string(); - let expires_at = (chrono::Utc::now() + chrono::Duration::hours(1)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let expires_at = (crate::timefmt::now() + crate::timefmt::Duration::hours(1)) + .format_z(); sqlx::query("DELETE FROM recovery_tokens WHERE merchant_id = ?") .bind(merchant_id) @@ -643,10 +642,9 @@ mod recovery_cooldown_tests { assert!(recovery_recently_requested(&pool, "m1").await.unwrap()); assert!(!recovery_recently_requested(&pool, "m2").await.unwrap()); - let old = (chrono::Utc::now() - - chrono::Duration::minutes(RECOVERY_EMAIL_COOLDOWN_MINUTES + 1)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let old = (crate::timefmt::now() + - crate::timefmt::Duration::minutes(RECOVERY_EMAIL_COOLDOWN_MINUTES + 1)) + .format_z(); sqlx::query("UPDATE recovery_tokens SET created_at = ? WHERE merchant_id = 'm1'") .bind(&old) .execute(&pool) diff --git a/src/scanner/mod.rs b/src/scanner/mod.rs index c9aa6c3..cf1ddb4 100644 --- a/src/scanner/mod.rs +++ b/src/scanner/mod.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; mod api; pub mod blocks; pub mod decrypt; @@ -545,12 +546,12 @@ async fn scan_blocks( .fetch_all(pool).await?; for (id,txid) in fees { sqlx::query("INSERT INTO direct_fee_checks VALUES (?,?,?) ON CONFLICT(invoice_id,txid) DO UPDATE SET next_check=excluded.next_check") - .bind(&id).bind(&txid).bind(chrono::Utc::now().timestamp()+300).execute(pool).await?; + .bind(&id).bind(&txid).bind(crate::timefmt::now().unix_timestamp()+300).execute(pool).await?; if matches!(blocks::check_tx_confirmed(http,&config.cipherscan_api_url,&txid).await,Ok(true)) { if let Ok(raw)=mempool::fetch_raw_tx(http,&config.cipherscan_api_url,&txid).await { try_detect_fee(pool,config,&raw,&id,Some(&txid)).await; sqlx::query("UPDATE direct_fee_checks SET next_check=? WHERE invoice_id=? AND txid=?") - .bind(chrono::Utc::now().timestamp()+21600).bind(&id).bind(&txid).execute(pool).await?; + .bind(crate::timefmt::now().unix_timestamp()+21600).bind(&id).bind(&txid).execute(pool).await?; } } } @@ -667,10 +668,10 @@ async fn scan_blocks( let start_height = { let oldest_ts = earliest_relevant_timestamp(&pending, &active_campaigns); if let Some(ts) = oldest_ts { - let now = chrono::Utc::now(); - if let Ok(created) = chrono::DateTime::parse_from_rfc3339(&ts) { - let secs_ago = (now - created.with_timezone(&chrono::Utc)) - .num_seconds() + let now = crate::timefmt::now(); + if let Ok(created) = crate::timefmt::parse_rfc3339(&ts) { + let secs_ago = (now - created) + .whole_seconds() .max(0) as u64; let earliest_block = earliest_relevant_height(current_height, secs_ago); if earliest_block > persisted_start { @@ -1261,8 +1262,8 @@ async fn schedule_luma_retry(pool: &SqlitePool, invoice_id: &str) { // Exponential backoff: min(60, 5 * 2^(attempt-1)) minutes let backoff_minutes = std::cmp::min(60, 5 * (1i64 << (new_count - 1))); - let retry_at = chrono::Utc::now() + chrono::Duration::minutes(backoff_minutes); - let retry_at_str = retry_at.format("%Y-%m-%dT%H:%M:%S").to_string(); + let retry_at = crate::timefmt::now() + crate::timefmt::Duration::minutes(backoff_minutes); + let retry_at_str = retry_at.format_naive(); tracing::warn!( invoice_id, @@ -1287,7 +1288,7 @@ async fn retry_due_luma_registrations( pool: &SqlitePool, outbound_http: &reqwest::Client, ) { - let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S").to_string(); + let now = crate::timefmt::now().format_naive(); let rows: Vec<(String, Option, Option)> = sqlx::query_as( "SELECT i.id, i.product_id, i.price_id FROM invoices i diff --git a/src/subscriptions/mod.rs b/src/subscriptions/mod.rs index 2daeede..0875e93 100644 --- a/src/subscriptions/mod.rs +++ b/src/subscriptions/mod.rs @@ -1,4 +1,4 @@ -use chrono::{Duration as ChronoDuration, Utc}; +use crate::timefmt::TimestampExt; use serde::{Deserialize, Serialize}; use sqlx::{FromRow, SqlitePool}; use uuid::Uuid; @@ -20,9 +20,9 @@ pub struct Subscription { } impl Subscription { - pub fn has_access_at(&self, now: chrono::DateTime) -> bool { + pub fn has_access_at(&self, now: crate::timefmt::OffsetDateTime) -> bool { self.status == "active" - && chrono::DateTime::parse_from_rfc3339(&self.current_period_end) + && crate::timefmt::parse_rfc3339(&self.current_period_end) .is_ok_and(|end| now < end) } } @@ -36,16 +36,16 @@ pub struct CreateSubscriptionRequest { const SUB_COLS: &str = "id, merchant_id, price_id, label, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, created_at, current_invoice_id, pause_at_period_end"; fn compute_period_end( - start: &chrono::DateTime, + start: &crate::timefmt::OffsetDateTime, interval: &str, count: i32, -) -> chrono::DateTime { +) -> crate::timefmt::OffsetDateTime { match interval { - "day" => *start + ChronoDuration::days(count as i64), - "week" => *start + ChronoDuration::weeks(count as i64), - "month" => *start + ChronoDuration::days(30 * count as i64), - "year" => *start + ChronoDuration::days(365 * count as i64), - _ => *start + ChronoDuration::days(30), + "day" => *start + crate::timefmt::Duration::days(count as i64), + "week" => *start + crate::timefmt::Duration::weeks(count as i64), + "month" => *start + crate::timefmt::Duration::days(30 * count as i64), + "year" => *start + crate::timefmt::Duration::days(365 * count as i64), + _ => *start + crate::timefmt::Duration::days(30), } } @@ -75,11 +75,10 @@ pub async fn create_subscription( let interval = price.billing_interval.as_deref().unwrap_or("month"); let count = price.interval_count.unwrap_or(1); - let now = Utc::now(); - let period_start = now.format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now(); + let period_start = now.format_z(); let period_end = compute_period_end(&now, interval, count) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + .format_z(); let id = format!("sub_{}", Uuid::new_v4().to_string().replace('-', "")); @@ -143,7 +142,7 @@ pub async fn cancel_subscription( return Ok(Some(sub)); } - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); if at_period_end { sqlx::query( @@ -272,11 +271,10 @@ pub async fn resume_subscription( let interval = price.billing_interval.as_deref().unwrap_or("month"); let count = price.interval_count.unwrap_or(1); - let now = Utc::now(); - let new_start = now.format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now(); + let new_start = now.format_z(); let new_end = compute_period_end(&now, interval, count) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + .format_z(); sqlx::query( "UPDATE subscriptions SET status = 'active', pause_at_period_end = 0, @@ -326,7 +324,7 @@ pub async fn process_renewals( merchant_ufvks: &std::collections::HashMap, fee_config: Option<&crate::invoices::FeeConfig>, ) -> anyhow::Result { - let now_str = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now_str = crate::timefmt::now().format_z(); let mut actions = 0u32; // 0. Pause subscriptions scheduled to pause at period end @@ -414,9 +412,8 @@ pub async fn process_renewals( } // 2. Generate draft invoices for active subscriptions approaching period end - let notice_threshold = (Utc::now() + ChronoDuration::days(RENEWAL_NOTICE_DAYS)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let notice_threshold = (crate::timefmt::now() + crate::timefmt::Duration::days(RENEWAL_NOTICE_DAYS)) + .format_z(); let q = format!( "SELECT {} FROM subscriptions WHERE status = 'active' AND current_period_end <= ? AND cancel_at_period_end = 0 AND pause_at_period_end = 0 LIMIT 500", @@ -667,15 +664,14 @@ pub async fn renew_from_confirmed_invoice( .await? .ok_or_else(|| anyhow::anyhow!("Subscription price not found"))?; let period_end = - chrono::DateTime::parse_from_rfc3339(&sub.current_period_end)?.with_timezone(&Utc); - let new_start = period_end.format("%Y-%m-%dT%H:%M:%SZ").to_string(); + crate::timefmt::parse_rfc3339(&sub.current_period_end)?; + let new_start = period_end.format_z(); let new_end = compute_period_end( &period_end, price.billing_interval.as_deref().unwrap_or("month"), price.interval_count.unwrap_or(1), ) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + .format_z(); // Matching the invoice and old boundary makes concurrent/repeated application a no-op. let result = sqlx::query( @@ -717,11 +713,10 @@ pub async fn advance_subscription_period( // A renewal buys the next period, including when it is paid early. // Keep the existing billing boundary instead of discarding paid time. let period_end = - chrono::DateTime::parse_from_rfc3339(&sub.current_period_end)?.with_timezone(&Utc); - let new_start = period_end.format("%Y-%m-%dT%H:%M:%SZ").to_string(); + crate::timefmt::parse_rfc3339(&sub.current_period_end)?; + let new_start = period_end.format_z(); let new_end = compute_period_end(&period_end, interval, count) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + .format_z(); sqlx::query( "UPDATE subscriptions SET current_period_start = ?, current_period_end = ?, current_invoice_id = NULL @@ -795,10 +790,9 @@ mod tests { async fn seed_confirmed_renewal(pool: &SqlitePool, sub: &Subscription) -> String { let invoice_id = format!("renewal_{}", sub.id); - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); - let expiry = (Utc::now() + ChronoDuration::minutes(10)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let now = crate::timefmt::now().format_z(); + let expiry = (crate::timefmt::now() + crate::timefmt::Duration::minutes(10)) + .format_z(); sqlx::query("INSERT INTO invoices (id, merchant_id, memo_code, price_eur, price_zec, zec_rate_at_creation, status, expires_at, confirmed_at, subscription_id, price_id, price_zatoshis, received_zatoshis) VALUES (?, ?, ?, 9.99, 0.1, 100.0, 'confirmed', ?, ?, ?, ?, 10000000, 10000000)") .bind(&invoice_id).bind(&sub.merchant_id).bind(&invoice_id) @@ -819,9 +813,8 @@ mod tests { seed_merchant(&pool, "renewal").await; seed_product_and_price(&pool, "renewal", "renewal_product", "renewal_price").await; let sub = create_test_sub(&pool, "renewal", "renewal_price").await; - let old_end = (Utc::now() + ChronoDuration::days(3)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let old_end = (crate::timefmt::now() + crate::timefmt::Duration::days(3)) + .format_z(); sqlx::query("UPDATE subscriptions SET current_period_end = ? WHERE id = ?") .bind(&old_end) .bind(&sub.id) @@ -838,10 +831,9 @@ mod tests { let second = second.unwrap(); assert_ne!(first.is_some(), second.is_some()); let renewed = first.or(second).unwrap(); - let expected_end = (chrono::DateTime::parse_from_rfc3339(&old_end).unwrap() - + ChronoDuration::days(30)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let expected_end = (crate::timefmt::parse_rfc3339(&old_end).unwrap() + + crate::timefmt::Duration::days(30)) + .format_z(); assert_eq!(renewed.current_period_start, old_end); assert_eq!(renewed.current_period_end, expected_end); assert!(renew_from_confirmed_invoice(&pool, &invoice_id) @@ -856,9 +848,8 @@ mod tests { seed_merchant(&pool, "delayed").await; seed_product_and_price(&pool, "delayed", "delayed_product", "delayed_price").await; let sub = create_test_sub(&pool, "delayed", "delayed_price").await; - let old_end = (Utc::now() - ChronoDuration::minutes(5)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let old_end = (crate::timefmt::now() - crate::timefmt::Duration::minutes(5)) + .format_z(); sqlx::query("UPDATE subscriptions SET current_period_end = ? WHERE id = ?") .bind(&old_end) .bind(&sub.id) @@ -873,18 +864,17 @@ mod tests { .await .unwrap(); let expired = get_subscription(&pool, &sub.id).await.unwrap().unwrap(); - assert!(!expired.has_access_at(Utc::now())); + assert!(!expired.has_access_at(crate::timefmt::now())); let renewed = renew_from_confirmed_invoice(&pool, &invoice_id) .await .unwrap() .unwrap(); - let expected_end = (chrono::DateTime::parse_from_rfc3339(&old_end).unwrap() - + ChronoDuration::days(30)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let expected_end = (crate::timefmt::parse_rfc3339(&old_end).unwrap() + + crate::timefmt::Duration::days(30)) + .format_z(); assert_eq!(renewed.current_period_start, old_end); assert_eq!(renewed.current_period_end, expected_end); - assert!(renewed.has_access_at(Utc::now())); + assert!(renewed.has_access_at(crate::timefmt::now())); } #[tokio::test] @@ -961,9 +951,8 @@ mod tests { seed_product_and_price(&pool, "recovery", "recovery_product", "recovery_price").await; let sub = create_test_sub(&pool, "recovery", "recovery_price").await; let invoice_id = seed_confirmed_renewal(&pool, &sub).await; - let past = (Utc::now() - ChronoDuration::minutes(5)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let past = (crate::timefmt::now() - crate::timefmt::Duration::minutes(5)) + .format_z(); sqlx::query( "UPDATE subscriptions SET status = 'past_due', current_period_end = ? WHERE id = ?", ) @@ -984,7 +973,7 @@ mod tests { assert_eq!(actions, 1); let renewed = get_subscription(&pool, &sub.id).await.unwrap().unwrap(); assert_eq!(renewed.current_period_start, past); - assert!(renewed.has_access_at(Utc::now())); + assert!(renewed.has_access_at(crate::timefmt::now())); assert!(renew_from_confirmed_invoice(&pool, &invoice_id) .await .unwrap() @@ -997,9 +986,8 @@ mod tests { seed_merchant(&pool, "unpaid").await; seed_product_and_price(&pool, "unpaid", "unpaid_product", "unpaid_price").await; let sub = create_test_sub(&pool, "unpaid", "unpaid_price").await; - let old_end = (Utc::now() + ChronoDuration::minutes(5)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let old_end = (crate::timefmt::now() + crate::timefmt::Duration::minutes(5)) + .format_z(); sqlx::query("UPDATE subscriptions SET current_period_end = ?, current_invoice_id = 'unpaid_invoice' WHERE id = ?") .bind(&old_end) .bind(&sub.id) @@ -1025,7 +1013,7 @@ mod tests { zec_ngn: 100.0, zec_chf: 100.0, zec_inr: 100.0, - updated_at: Utc::now(), + updated_at: crate::timefmt::now(), }; for _ in 0..2 { @@ -1036,21 +1024,19 @@ mod tests { assert!(invoice.expires_at > old_end); let unchanged = get_subscription(&pool, &sub.id).await.unwrap().unwrap(); assert_eq!(unchanged.current_period_end, old_end); - let boundary = chrono::DateTime::parse_from_rfc3339(&old_end) - .unwrap() - .with_timezone(&Utc); - assert!(unchanged.has_access_at(boundary - ChronoDuration::seconds(1))); + let boundary = crate::timefmt::parse_rfc3339(&old_end) + .unwrap(); + assert!(unchanged.has_access_at(boundary - crate::timefmt::Duration::seconds(1))); assert!(!unchanged.has_access_at(boundary)); - assert!(!unchanged.has_access_at(boundary + ChronoDuration::minutes(1))); + assert!(!unchanged.has_access_at(boundary + crate::timefmt::Duration::minutes(1))); sqlx::query("UPDATE invoices SET status = 'expired' WHERE id = 'unpaid_invoice'") .execute(&pool) .await .unwrap(); } - let past = (Utc::now() - ChronoDuration::seconds(1)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let past = (crate::timefmt::now() - crate::timefmt::Duration::seconds(1)) + .format_z(); sqlx::query("UPDATE subscriptions SET current_period_end = ? WHERE id = ?") .bind(&past) .bind(&sub.id) @@ -1318,9 +1304,8 @@ mod tests { // Schedule pause and fast-forward period end to the past pause_subscription(&pool, &sub.id, m).await.unwrap(); - let past = (Utc::now() - ChronoDuration::hours(1)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let past = (crate::timefmt::now() - crate::timefmt::Duration::hours(1)) + .format_z(); sqlx::query("UPDATE subscriptions SET current_period_end = ? WHERE id = ?") .bind(&past) .bind(&sub.id) diff --git a/src/tickets/mod.rs b/src/tickets/mod.rs index 1ae0b00..936c77b 100644 --- a/src/tickets/mod.rs +++ b/src/tickets/mod.rs @@ -1,3 +1,4 @@ +use crate::timefmt::TimestampExt; use rand::rngs::OsRng; use rand::RngCore; use serde::{Deserialize, Serialize}; @@ -126,7 +127,7 @@ pub async fn scan_ticket( code: &str, merchant_id: &str, ) -> anyhow::Result> { - let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); let update = sqlx::query( "UPDATE tickets SET status = 'used', used_at = ? diff --git a/src/timefmt.rs b/src/timefmt.rs new file mode 100644 index 0000000..9a02ffe --- /dev/null +++ b/src/timefmt.rs @@ -0,0 +1,470 @@ +//! UTC timestamp helpers built on the `time` crate. +//! +//! CipherPay stores timestamps as TEXT and compares many of them lexically in +//! SQL, so every string produced here must be byte-for-byte what the previous +//! chrono code produced. The parsers accept what chrono's parsers accepted for +//! the inputs this service sees. The tests below are golden values captured +//! from chrono 0.4.45. + +use std::fmt; + +use time::{Date, Month, Time, UtcOffset}; +pub use time::{Duration, OffsetDateTime, PrimitiveDateTime}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TimestampError(&'static str); + +impl fmt::Display for TimestampError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "invalid timestamp: {}", self.0) + } +} + +impl std::error::Error for TimestampError {} + +pub fn now() -> OffsetDateTime { + OffsetDateTime::now_utc() +} + +fn utc(t: OffsetDateTime) -> OffsetDateTime { + t.to_offset(UtcOffset::UTC) +} + +fn date_time(p: PrimitiveDateTime) -> String { + format!( + "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", + p.year(), + u8::from(p.month()), + p.day(), + p.hour(), + p.minute(), + p.second() + ) +} + +fn primitive(t: OffsetDateTime) -> PrimitiveDateTime { + let t = utc(t); + PrimitiveDateTime::new(t.date(), t.time()) +} + +/// `%Y-%m-%dT%H:%M:%SZ` in UTC, truncated to whole seconds. +pub fn format_z(t: OffsetDateTime) -> String { + format!("{}Z", date_time(primitive(t))) +} + +/// `%Y-%m-%dT%H:%M:%S` in UTC, without an offset. +pub fn format_naive(t: OffsetDateTime) -> String { + date_time(primitive(t)) +} + +/// `%Y-%m-%dT%H:%M`. +pub fn format_naive_minutes(p: PrimitiveDateTime) -> String { + let s = date_time(p); + s[..s.len() - 3].to_string() +} + +/// Fractional seconds the way chrono's `SecondsFormat::AutoSi` writes them. +fn auto_si_fraction(nanos: u32) -> String { + if nanos == 0 { + String::new() + } else if nanos % 1_000_000 == 0 { + format!(".{:03}", nanos / 1_000_000) + } else if nanos % 1_000 == 0 { + format!(".{:06}", nanos / 1_000) + } else { + format!(".{nanos:09}") + } +} + +/// chrono's `DateTime::to_rfc3339()`: AutoSi fraction and `+00:00`. +pub fn rfc3339(t: OffsetDateTime) -> String { + let t = utc(t); + format!( + "{}{}+00:00", + date_time(primitive(t)), + auto_si_fraction(t.nanosecond()) + ) +} + +/// chrono's `to_rfc3339_opts(SecondsFormat::Secs, true)`. +pub fn rfc3339_secs_z(t: OffsetDateTime) -> String { + format_z(t) +} + +/// chrono's `to_rfc3339_opts(SecondsFormat::Millis, true)`. +pub fn rfc3339_millis_z(t: OffsetDateTime) -> String { + let t = utc(t); + format!( + "{}.{:03}Z", + date_time(primitive(t)), + t.nanosecond() / 1_000_000 + ) +} + +/// Serialize like chrono's serde impl for `DateTime` (AutoSi, `Z`). +pub fn serialize_rfc3339_z( + t: &OffsetDateTime, + serializer: S, +) -> Result { + let t = utc(*t); + serializer.serialize_str(&format!( + "{}{}Z", + date_time(primitive(t)), + auto_si_fraction(t.nanosecond()) + )) +} + +/// Method-style access so call sites read like the chrono code they replace. +pub trait TimestampExt { + fn format_z(self) -> String; + fn format_naive(self) -> String; + fn to_rfc3339(self) -> String; + fn rfc3339_secs_z(self) -> String; + fn rfc3339_millis_z(self) -> String; +} + +impl TimestampExt for OffsetDateTime { + fn format_z(self) -> String { + format_z(self) + } + fn format_naive(self) -> String { + format_naive(self) + } + fn to_rfc3339(self) -> String { + rfc3339(self) + } + fn rfc3339_secs_z(self) -> String { + rfc3339_secs_z(self) + } + fn rfc3339_millis_z(self) -> String { + rfc3339_millis_z(self) + } +} + +struct Cursor<'a> { + b: &'a [u8], + i: usize, +} + +impl<'a> Cursor<'a> { + fn new(s: &'a str) -> Self { + Self { + b: s.as_bytes(), + i: 0, + } + } + + /// Between `min` and `max` ASCII digits. + fn digits(&mut self, min: usize, max: usize) -> Result { + let start = self.i; + let mut v: u32 = 0; + while self.i < self.b.len() && self.i - start < max && self.b[self.i].is_ascii_digit() { + v = v * 10 + u32::from(self.b[self.i] - b'0'); + self.i += 1; + } + if self.i - start < min { + return Err(TimestampError("expected digits")); + } + Ok(v) + } + + fn lit(&mut self, options: &[u8]) -> Result { + match self.b.get(self.i) { + Some(c) if options.contains(c) => { + self.i += 1; + Ok(*c) + } + _ => Err(TimestampError("unexpected character")), + } + } + + fn peek(&self) -> Option { + self.b.get(self.i).copied() + } + + fn done(&self) -> Result<(), TimestampError> { + if self.i == self.b.len() { + Ok(()) + } else { + Err(TimestampError("trailing input")) + } + } +} + +fn build( + year: u32, + month: u32, + day: u32, + hour: u32, + minute: u32, + second: u32, + nanos: u32, +) -> Result { + let out_of_range = |_| TimestampError("out of range"); + let month = Month::try_from(u8::try_from(month).map_err(|_| TimestampError("out of range"))?) + .map_err(out_of_range)?; + let date = Date::from_calendar_date(year as i32, month, day as u8).map_err(out_of_range)?; + // chrono represents a leap second as :59 plus an extra second of nanos; the + // nearest instant `time` can hold is the end of second 59. + let (second, nanos) = if second == 60 { + (59, 999_999_999) + } else { + (second, nanos) + }; + let time = + Time::from_hms_nano(hour as u8, minute as u8, second as u8, nanos).map_err(out_of_range)?; + Ok(PrimitiveDateTime::new(date, time)) +} + +/// chrono's `DateTime::parse_from_rfc3339`: `T`, `t` or space separator, +/// any number of fraction digits (beyond nine are ignored), `Z`/`z` or a +/// `±HH:MM` offset below 24 hours. +pub fn parse_rfc3339(s: &str) -> Result { + let mut c = Cursor::new(s); + let year = c.digits(4, 4)?; + c.lit(b"-")?; + let month = c.digits(2, 2)?; + c.lit(b"-")?; + let day = c.digits(2, 2)?; + c.lit(b"Tt ")?; + let hour = c.digits(2, 2)?; + c.lit(b":")?; + let minute = c.digits(2, 2)?; + c.lit(b":")?; + let second = c.digits(2, 2)?; + let mut nanos = 0u32; + if c.peek() == Some(b'.') { + c.i += 1; + let start = c.i; + while let Some(d) = c.peek().filter(u8::is_ascii_digit) { + if c.i - start < 9 { + nanos = nanos * 10 + u32::from(d - b'0'); + } + c.i += 1; + } + let n = c.i - start; + if n == 0 { + return Err(TimestampError("empty fraction")); + } + for _ in n..9 { + nanos *= 10; + } + } + let offset_secs: i32 = match c.lit(b"Zz+-")? { + b'Z' | b'z' => 0, + sign => { + let h = c.digits(2, 2)? as i32; + c.lit(b":")?; + let m = c.digits(2, 2)? as i32; + if h > 23 || m > 59 { + return Err(TimestampError("offset out of range")); + } + let v = h * 3600 + m * 60; + if sign == b'-' { + -v + } else { + v + } + } + }; + c.done()?; + let p = build(year, month, day, hour, minute, second, nanos)?; + let offset = UtcOffset::from_whole_seconds(offset_secs) + .map_err(|_| TimestampError("offset out of range"))?; + Ok(utc(p.assume_offset(offset))) +} + +/// Numeric fields as chrono's `parse_from_str` reads `%Y-%m-%dT%H:%M[:%S]`: +/// a four-digit year and one- or two-digit other fields. +fn parse_fields(c: &mut Cursor<'_>, seconds: bool) -> Result { + let year = c.digits(4, 4)?; + c.lit(b"-")?; + let month = c.digits(1, 2)?; + c.lit(b"-")?; + let day = c.digits(1, 2)?; + c.lit(b"T")?; + let hour = c.digits(1, 2)?; + c.lit(b":")?; + let minute = c.digits(1, 2)?; + let second = if seconds { + c.lit(b":")?; + c.digits(1, 2)? + } else { + 0 + }; + build(year, month, day, hour, minute, second, 0) +} + +/// chrono's `NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%SZ")`, as UTC. +pub fn parse_z(s: &str) -> Result { + let mut c = Cursor::new(s); + let p = parse_fields(&mut c, true)?; + c.lit(b"Z")?; + c.done()?; + Ok(p.assume_utc()) +} + +/// `%Y-%m-%dT%H:%M:%S`, falling back to `%Y-%m-%dT%H:%M`. +pub fn parse_naive(s: &str) -> Result { + let mut c = Cursor::new(s); + if let Ok(p) = parse_fields(&mut c, true).and_then(|p| c.done().map(|_| p)) { + return Ok(p); + } + let mut c = Cursor::new(s); + let p = parse_fields(&mut c, false)?; + c.done()?; + Ok(p) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(secs: i64, nanos: u32) -> OffsetDateTime { + OffsetDateTime::from_unix_timestamp(secs).unwrap() + Duration::nanoseconds(nanos as i64) + } + + fn ts(t: OffsetDateTime) -> (i64, u32) { + (t.unix_timestamp(), t.nanosecond()) + } + + #[test] + fn formats_match_chrono() { + // (secs, nanos, to_rfc3339, Secs+Z, Millis+Z, serde, %..%SZ, naive, minutes) + let cases = [ + ( + 0, + "2025-11-21T04:40:00+00:00", + "2025-11-21T04:40:00.000Z", + "\"2025-11-21T04:40:00Z\"", + ), + ( + 123_000_000, + "2025-11-21T04:40:00.123+00:00", + "2025-11-21T04:40:00.123Z", + "\"2025-11-21T04:40:00.123Z\"", + ), + ( + 123_456_000, + "2025-11-21T04:40:00.123456+00:00", + "2025-11-21T04:40:00.123Z", + "\"2025-11-21T04:40:00.123456Z\"", + ), + ( + 123_456_789, + "2025-11-21T04:40:00.123456789+00:00", + "2025-11-21T04:40:00.123Z", + "\"2025-11-21T04:40:00.123456789Z\"", + ), + ( + 5_000, + "2025-11-21T04:40:00.000005+00:00", + "2025-11-21T04:40:00.000Z", + "\"2025-11-21T04:40:00.000005Z\"", + ), + ]; + #[derive(serde::Serialize)] + struct W(#[serde(serialize_with = "serialize_rfc3339_z")] OffsetDateTime); + for (nanos, rfc, millis, serde) in cases { + let t = at(1_763_700_000, nanos); + assert_eq!(rfc3339(t), rfc); + assert_eq!(rfc3339_secs_z(t), "2025-11-21T04:40:00Z"); + assert_eq!(rfc3339_millis_z(t), millis); + assert_eq!(serde_json::to_string(&W(t)).unwrap(), serde); + assert_eq!(format_z(t), "2025-11-21T04:40:00Z"); + assert_eq!(format_naive(t), "2025-11-21T04:40:00"); + assert_eq!(format_naive_minutes(primitive(t)), "2025-11-21T04:40"); + } + // Non-UTC offsets are written in UTC. + let tokyo = at(1_763_700_000, 0).to_offset(UtcOffset::from_hms(9, 0, 0).unwrap()); + assert_eq!(format_z(tokyo), "2025-11-21T04:40:00Z"); + assert_eq!(rfc3339(tokyo), "2025-11-21T04:40:00+00:00"); + } + + #[test] + fn rfc3339_parse_matches_chrono() { + let ok = [ + ("2026-11-21T04:40:00Z", (1_795_236_000, 0)), + ("2026-11-21t04:40:00z", (1_795_236_000, 0)), + ("2026-11-21 04:40:00Z", (1_795_236_000, 0)), + ( + "2026-11-21T04:40:00.1234567891234Z", + (1_795_236_000, 123_456_789), + ), + ("2026-11-21T04:40:00.000000000000Z", (1_795_236_000, 0)), + ("2026-11-21T13:40:00+09:00", (1_795_236_000, 0)), + ("2026-11-21T04:40:00-00:00", (1_795_236_000, 0)), + ("2026-11-21T04:40:00.5-00:30", (1_795_237_800, 500_000_000)), + ]; + for (s, want) in ok { + assert_eq!(ts(parse_rfc3339(s).unwrap()), want, "{s}"); + } + let err = [ + "2026-11-21T04:40:00", + "2026-11-21T04:40:00+24:00", + "2026-02-30T00:00:00Z", + "2026-11-21T04:40:00.Z", + "2026-11-21T04:40:00+0900", + "2026-11-21T04:40:00+09", + "2026-1-21T04:40:00Z", + "2026-11-21T4:40:00Z", + "2026-11-21T04:40:00+9:00", + "2026-11-21T04:40:00+09:00:00", + "2026-11-21T04:40:00Z ", + "2026-11-21 04:40:00Z", + ]; + for s in err { + assert!(parse_rfc3339(s).is_err(), "{s}"); + } + // chrono keeps a leap second as 59 + 1e9 ns; we hold the end of :59. + assert_eq!( + ts(parse_rfc3339("2026-11-21T04:40:60Z").unwrap()), + (1_795_236_059, 999_999_999) + ); + } + + #[test] + fn z_and_naive_parse_match_chrono() { + for (s, want) in [ + ("2026-11-21T04:40:00Z", 1_795_236_000), + ("2026-11-21T4:40:00Z", 1_795_236_000), + ("2026-1-5T04:40:00Z", 1_767_588_000), + ] { + assert_eq!(parse_z(s).unwrap().unix_timestamp(), want, "{s}"); + } + for s in [ + "2026-11-21T04:40:00", + "2026-11-21T04:40:00.5Z", + "2026-11-21t04:40:00Z", + "2026-11-21T04:40:00z", + "2026-11-21T04:40:00Z ", + "2026-11-21T004:40:00Z", + "2026-13-01T00:00:00Z", + "2026-11-21T24:00:00Z", + "12026-11-21T04:40:00Z", + ] { + assert!(parse_z(s).is_err(), "{s}"); + } + for (s, want) in [ + ("2026-11-21T04:40:00", 1_795_236_000), + ("2026-11-21T04:40", 1_795_236_000), + ("2026-11-21T4:40", 1_795_236_000), + ("2026-1-5T04:40", 1_767_588_000), + ("2026-11-21T04:40:5", 1_795_236_005), + ("2026-11-21T04:4", 1_795_233_840), + ] { + assert_eq!( + parse_naive(s).unwrap().assume_utc().unix_timestamp(), + want, + "{s}" + ); + } + for s in [ + "2026-11-21T04:40:00Z", + "2026-11-21 04:40", + "2026-11-21t04:40", + ] { + assert!(parse_naive(s).is_err(), "{s}"); + } + } +} diff --git a/src/webhooks/mod.rs b/src/webhooks/mod.rs index 8236735..3200ac5 100644 --- a/src/webhooks/mod.rs +++ b/src/webhooks/mod.rs @@ -1,4 +1,4 @@ -use chrono::Utc; +use crate::timefmt::TimestampExt; use hmac::{Hmac, Mac}; use sha2::Sha256; use sqlx::SqlitePool; @@ -81,7 +81,7 @@ pub async fn dispatch_event( return Ok(()); } - let timestamp = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let timestamp = crate::timefmt::now().format_z(); let mut payload = extra; if let Some(obj) = payload.as_object_mut() { @@ -99,9 +99,8 @@ pub async fn dispatch_event( let signature = sign_payload(&webhook_secret, ×tamp, &payload_str); let delivery_id = Uuid::new_v4().to_string(); - let next_retry = (Utc::now() + chrono::Duration::seconds(jittered_retry_delay_secs(1))) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let next_retry = (crate::timefmt::now() + crate::timefmt::Duration::seconds(jittered_retry_delay_secs(1))) + .format_z(); let invoice_id_for_fk = payload.get("invoice_id").and_then(|v| v.as_str()); @@ -169,7 +168,7 @@ pub async fn retry_failed( http: &reqwest::Client, encryption_key: &str, ) -> anyhow::Result<()> { - let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let now = crate::timefmt::now().format_z(); let rows = sqlx::query_as::<_, (String, String, String, String, i64)>( "WITH ready AS ( @@ -240,7 +239,7 @@ pub async fn retry_failed( continue; } - let ts = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let ts = crate::timefmt::now().format_z(); let mut body: serde_json::Value = serde_json::from_str(&payload)?; if let Some(obj) = body.as_object_mut() { obj.insert( @@ -311,9 +310,8 @@ pub async fn retry_failed( let delay = retry_after_secs .map(|ra| base_delay.max(ra.min(36000))) .unwrap_or(base_delay); - let next = (Utc::now() + chrono::Duration::seconds(delay)) - .format("%Y-%m-%dT%H:%M:%SZ") - .to_string(); + let next = (crate::timefmt::now() + crate::timefmt::Duration::seconds(delay)) + .format_z(); sqlx::query( "UPDATE webhook_deliveries SET attempts = ?, last_attempt_at = ?, next_retry_at = ?, response_status = ?, response_error = ? WHERE id = ?" )