From 030a5289828addd714b0b1fdf6e20add7e41f308 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 24 Nov 2026 10:14:34 +0100 Subject: [PATCH 1/2] Test SQLite store edge cases and upgrades The SQLite store's tests only ever read databases they wrote themselves, and neither covered zero-length or multi-megabyte values, a schema migration failing halfway through, nor contention with a second connection. These are the paths most likely to change behavior when the underlying SQLite wrapper is touched. Add tests asserting that values of any length are stored as BLOBs, that a database written by LDK Node v0.7 is migrated and remains usable, that a failed migration leaves the database untouched, and that writes wait for a lock held by another connection. Co-Authored-By: HAL 9000 --- src/io/sqlite_store/migrations.rs | 98 +++++++++++++++++ src/io/sqlite_store/mod.rs | 175 ++++++++++++++++++++++++++++++ 2 files changed, 273 insertions(+) diff --git a/src/io/sqlite_store/migrations.rs b/src/io/sqlite_store/migrations.rs index 7adde7e8b6..f9ae8d8438 100644 --- a/src/io/sqlite_store/migrations.rs +++ b/src/io/sqlite_store/migrations.rs @@ -327,4 +327,102 @@ mod tests { // Check we can continue to use the store just fine. do_read_write_remove_list_persist(&store).await; } + + #[tokio::test] + async fn failed_schema_2_migration_rolls_back() { + let mut temp_path = random_storage_path(); + temp_path.push("failed_schema_2_migration_rolls_back"); + + let db_file_name = "test_db".to_string(); + let kv_table_name = "test_table".to_string(); + + let test_ns = "testspace"; + let test_sub = "testsub"; + + fs::create_dir_all(temp_path.clone()).unwrap(); + let mut db_file_path = temp_path.clone(); + db_file_path.push(db_file_name.clone()); + + let read_state = |connection: &Connection| -> (u16, Vec, i64) { + let user_version = connection + .query_row("SELECT user_version FROM pragma_user_version", [], |row| row.get(0)) + .unwrap(); + let mut stmt = + connection.prepare(&format!("PRAGMA table_info({})", kv_table_name)).unwrap(); + let columns = stmt + .query_map([], |row| row.get::<_, String>(1)) + .unwrap() + .collect::, _>>() + .unwrap(); + let row_count = connection + .query_row(&format!("SELECT COUNT(*) FROM {}", kv_table_name), [], |row| row.get(0)) + .unwrap(); + (user_version, columns, row_count) + }; + + let connection = Connection::open(db_file_path.clone()).unwrap(); + connection.pragma_update(None, "user_version", 2u16).unwrap(); + + let sql = format!( + "CREATE TABLE IF NOT EXISTS {} ( + primary_namespace TEXT NOT NULL, + secondary_namespace TEXT DEFAULT \"\" NOT NULL, + key TEXT NOT NULL CHECK (key <> ''), + value BLOB, PRIMARY KEY ( primary_namespace, secondary_namespace, key ) + );", + kv_table_name + ); + connection.execute(&sql, []).unwrap(); + + for i in 0..3 { + let sql = format!( + "INSERT INTO {} (primary_namespace, secondary_namespace, key, value) VALUES (:ns, :sub, :key, :value);", + kv_table_name + ); + connection + .execute( + &sql, + named_params! { + ":ns": test_ns, + ":sub": test_sub, + ":key": format!("key_{}", i), + ":value": vec![i as u8; 8], + }, + ) + .unwrap(); + } + + // The migration only creates its index after having altered the table, so that a + // pre-existing index of the same name makes it fail halfway through. + let sql = + format!("CREATE INDEX idx_{}_paginated ON {} (key)", kv_table_name, kv_table_name); + connection.execute(&sql, []).unwrap(); + + let state_before = read_state(&connection); + assert_eq!(state_before.0, 2); + assert!(!state_before.1.contains(&"sort_order".to_string())); + assert_eq!(state_before.2, 3); + + assert!(SqliteStore::new( + temp_path.clone(), + Some(db_file_name.clone()), + Some(kv_table_name.clone()) + ) + .is_err()); + assert_eq!(read_state(&connection), state_before); + + // Once the conflict is resolved, the migration needs to be able to start over. + connection.execute(&format!("DROP INDEX idx_{}_paginated", kv_table_name), []).unwrap(); + drop(connection); + + let store = SqliteStore::new(temp_path, Some(db_file_name), Some(kv_table_name)).unwrap(); + for i in 0..3 { + let key = format!("key_{}", i); + let data = KVStore::read(&store, test_ns, test_sub, &key).await.unwrap(); + assert_eq!(data, vec![i as u8; 8]); + } + let response = + PaginatedKVStore::list_paginated(&store, test_ns, test_sub, None).await.unwrap(); + assert_eq!(response.keys, vec!["key_2", "key_1", "key_0"]); + } } diff --git a/src/io/sqlite_store/mod.rs b/src/io/sqlite_store/mod.rs index 8848137b62..1ea8d545a3 100644 --- a/src/io/sqlite_store/mod.rs +++ b/src/io/sqlite_store/mod.rs @@ -1378,6 +1378,181 @@ mod tests { assert_eq!(response.keys, vec!["key_c", "key_b", "key_a"]); } } + + fn read_user_version(connection: &Connection) -> u16 { + connection + .query_row("SELECT user_version FROM pragma_user_version", [], |row| row.get(0)) + .unwrap() + } + + #[tokio::test] + async fn value_edge_cases_persist_as_blobs() { + let mut temp_path = random_storage_path(); + temp_path.push("value_edge_cases_persist_as_blobs"); + let db_file_name = "test_db".to_string(); + let kv_table_name = "test_table".to_string(); + + let ns = "test_ns"; + let sub = "test_sub"; + let values: Vec<(&str, Vec)> = vec![ + ("empty", Vec::new()), + ("nul_bytes", vec![0u8; 64]), + ("all_bytes", (0..=u8::MAX).collect()), + ("large", (0..8 * 1024 * 1024).map(|i| (i % 251) as u8).collect()), + ]; + + { + let store = SqliteStore::new( + temp_path.clone(), + Some(db_file_name.clone()), + Some(kv_table_name.clone()), + ) + .unwrap(); + + for (key, value) in &values { + KVStore::write(&store, ns, sub, key, value.clone()).await.unwrap(); + assert_eq!(&KVStore::read(&store, ns, sub, key).await.unwrap(), value); + } + + // Replacing a large value with a shorter one must not leave stale bytes behind. + KVStore::write(&store, ns, sub, "shrunk", vec![7u8; 1024 * 1024]).await.unwrap(); + KVStore::write(&store, ns, sub, "shrunk", vec![8u8; 3]).await.unwrap(); + + // Don't drop/cleanup since we want to reopen + std::mem::forget(store); + } + + { + // Values of any length, including zero, need to be stored as BLOBs rather than as + // NULL or TEXT, as they otherwise couldn't be read back. + let connection = Connection::open(temp_path.join(&db_file_name)).unwrap(); + assert_eq!(read_user_version(&connection), SCHEMA_USER_VERSION); + + let sql = format!( + "SELECT typeof(value), length(value) FROM {} WHERE key=:key;", + kv_table_name + ); + let mut stmt = connection.prepare_cached(&sql).unwrap(); + let expected = values.iter().map(|(key, value)| (*key, value.len())); + for (key, expected_len) in expected.chain(std::iter::once(("shrunk", 3))) { + let (value_type, len): (String, i64) = stmt + .query_row(named_params! { ":key": key }, |row| Ok((row.get(0)?, row.get(1)?))) + .unwrap(); + assert_eq!(value_type, "blob", "unexpected storage class for {}", key); + assert_eq!(len as usize, expected_len, "unexpected length for {}", key); + } + } + + let store = SqliteStore::new(temp_path, Some(db_file_name), Some(kv_table_name)).unwrap(); + for (key, value) in &values { + assert_eq!(&KVStore::read(&store, ns, sub, key).await.unwrap(), value); + } + assert_eq!(KVStore::read(&store, ns, sub, "shrunk").await.unwrap(), vec![8u8; 3]); + + let mut listed_keys = KVStore::list(&store, ns, sub).await.unwrap(); + listed_keys.sort(); + assert_eq!(listed_keys, vec!["all_bytes", "empty", "large", "nul_bytes", "shrunk"]); + } + + #[tokio::test] + async fn migrates_database_written_by_v0_7() { + use ldk_node_070::io::sqlite_store::SqliteStore as OldSqliteStore; + use ldk_node_070::lightning::util::persist::KVStoreSync as OldKVStoreSync; + + let mut temp_path = random_storage_path(); + temp_path.push("migrates_database_written_by_v0_7"); + let db_file_name = "test_db".to_string(); + let kv_table_name = "test_table".to_string(); + + let ns = "test_ns"; + let sub = "test_sub"; + let values: Vec<(&str, Vec)> = vec![ + ("key_0", vec![42u8; 32]), + ("key_1", Vec::new()), + ("key_2", (0..=u8::MAX).collect()), + ("key_3", (0..1024 * 1024).map(|i| (i % 251) as u8).collect()), + ]; + + { + let old_store = OldSqliteStore::new( + temp_path.clone(), + Some(db_file_name.clone()), + Some(kv_table_name.clone()), + ) + .unwrap(); + for (key, value) in &values { + OldKVStoreSync::write(&old_store, ns, sub, key, value.clone()).unwrap(); + } + OldKVStoreSync::write(&old_store, "other_ns", "", "other_key", vec![1u8; 8]).unwrap(); + } + + { + let connection = Connection::open(temp_path.join(&db_file_name)).unwrap(); + assert_eq!(read_user_version(&connection), 2); + } + + let store = + SqliteStore::new(temp_path.clone(), Some(db_file_name.clone()), Some(kv_table_name)) + .unwrap(); + + { + let connection = Connection::open(temp_path.join(&db_file_name)).unwrap(); + assert_eq!(read_user_version(&connection), SCHEMA_USER_VERSION); + } + + for (key, value) in &values { + assert_eq!(&KVStore::read(&store, ns, sub, key).await.unwrap(), value); + } + assert_eq!(KVStore::read(&store, "other_ns", "", "other_key").await.unwrap(), vec![1u8; 8]); + + // Pre-existing entries are ordered by their insertion order, newest first. + let response = PaginatedKVStore::list_paginated(&store, ns, sub, None).await.unwrap(); + assert_eq!(response.keys, vec!["key_3", "key_2", "key_1", "key_0"]); + + KVStore::write(&store, ns, sub, "key_new", vec![99u8; 8]).await.unwrap(); + KVStore::write(&store, ns, sub, "key_0", vec![43u8; 32]).await.unwrap(); + KVStore::remove(&store, ns, sub, "key_2", false).await.unwrap(); + let response = PaginatedKVStore::list_paginated(&store, ns, sub, None).await.unwrap(); + assert_eq!(response.keys, vec!["key_new", "key_3", "key_1", "key_0"]); + assert_eq!(KVStore::read(&store, ns, sub, "key_0").await.unwrap(), vec![43u8; 32]); + + do_read_write_remove_list_persist(&store).await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn write_waits_for_lock_held_by_other_connection() { + use std::time::{Duration, Instant}; + + let mut temp_path = random_storage_path(); + temp_path.push("write_waits_for_lock_held_by_other_connection"); + let db_file_name = "test_db".to_string(); + + let store = SqliteStore::new( + temp_path.clone(), + Some(db_file_name.clone()), + Some("test_table".to_string()), + ) + .unwrap(); + KVStore::write(&store, "test_ns", "", "key_a", vec![1u8; 8]).await.unwrap(); + + let competing_connection = Connection::open(temp_path.join(&db_file_name)).unwrap(); + competing_connection.execute_batch("BEGIN IMMEDIATE").unwrap(); + + let hold_duration = Duration::from_millis(500); + let start = Instant::now(); + let competing_thread = std::thread::spawn(move || { + std::thread::sleep(hold_duration); + competing_connection.execute_batch("COMMIT").unwrap(); + }); + + // Rather than failing right away, the write needs to wait for the lock to be released. + KVStore::write(&store, "test_ns", "", "key_b", vec![2u8; 8]).await.unwrap(); + assert!(start.elapsed() >= hold_duration); + competing_thread.join().unwrap(); + + assert_eq!(KVStore::read(&store, "test_ns", "", "key_a").await.unwrap(), vec![1u8; 8]); + assert_eq!(KVStore::read(&store, "test_ns", "", "key_b").await.unwrap(), vec![2u8; 8]); + } } #[cfg(ldk_bench)] From 01b9284ea041bdf2c87024d3383890cee3ab11d9 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 24 Nov 2026 10:16:24 +0100 Subject: [PATCH 2/2] Replace rusqlite with sqlite-thin As libsqlite3-sys may only be linked once per build and every rusqlite release pins a single version of it, LDK Node and any application using SQLite themselves had to agree on a rusqlite release. Our MSRV furthermore kept us from admitting recent releases, leaving downstream users unable to pick up newer bundled SQLite versions. Access SQLite through sqlite-thin instead, which declares the C API itself and hence accepts any libsqlite3-sys release from 0.28 on, leaving the choice to the application. It mirrors the subset of rusqlite's API we use, so the store's logic remains unchanged. As the crate is not released yet, we for now pin the revision proposed in cashubtc/cdk#2963. Co-Authored-By: HAL 9000 --- .github/workflows/rust.yml | 3 ++- Cargo.toml | 5 ++--- src/io/sqlite_store/migrations.rs | 6 +++--- src/io/sqlite_store/mod.rs | 6 +++--- tests/rusqlite-compat/README.md | 15 +++++++++------ 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 750d637f32..b6f416c621 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -12,7 +12,8 @@ jobs: timeout-minutes: 30 strategy: matrix: - # Keep these endpoints in sync with the supported range in Cargo.toml. + # The oldest release sqlite-thin can share a libsqlite3-sys with, and the newest + # release line entirely compiling on our MSRV. rusqlite: ["0.31.0", "0.39.0"] env: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS: fallback diff --git a/Cargo.toml b/Cargo.toml index a506ca2818..ba03aae632 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,7 @@ chain-electrum = [ "lightning-transaction-sync/electrum-rustls-ring", ] chain-bitcoind = ["dep:lightning-block-sync"] -storage-sqlite = ["dep:rusqlite"] +storage-sqlite = ["dep:sqlite-thin"] storage-filesystem = ["dep:lightning-persister"] storage-vss = ["dep:vss-client", "dep:prost"] storage-postgres = ["dep:tokio-postgres", "dep:native-tls", "dep:postgres-native-tls"] @@ -106,8 +106,7 @@ bdk_wallet = { version = "3.2.0", default-features = false, features = ["std", " bitreq = { version = "0.3", default-features = false, features = ["async-https", "json-using-serde"] } rustls = { version = "0.23", default-features = false, features = ["ring"] } -# rusqlite 0.40.0 and 0.40.1 do not compile on our MSRV. -rusqlite = { version = ">=0.31.0, <0.40.0", features = ["bundled"], optional = true } +sqlite-thin = { git = "https://github.com/thesimplekid/cdk", rev = "50b2688b0c0b78e55538935a795f83ad1f26c58a", features = ["bundled"], optional = true } bitcoin = "0.32.7" bip39 = { version = "3.0.0", features = ["rand"] } bip21 = { version = "0.5", features = ["std"], default-features = false, optional = true } diff --git a/src/io/sqlite_store/migrations.rs b/src/io/sqlite_store/migrations.rs index f9ae8d8438..ccbac1ff9f 100644 --- a/src/io/sqlite_store/migrations.rs +++ b/src/io/sqlite_store/migrations.rs @@ -6,7 +6,7 @@ // accordance with one or both of these licenses. use lightning::io; -use rusqlite::Connection; +use sqlite_thin::Connection; pub(super) fn migrate_schema( connection: &mut Connection, kv_table_name: &str, mut from_version: u16, to_version: u16, @@ -68,7 +68,7 @@ fn migrate_v1_to_v2(connection: &mut Connection, kv_table_name: &str) -> io::Res } fn migrate_v2_to_v3(connection: &mut Connection, kv_table_name: &str) -> io::Result<()> { - let map_err = |e: rusqlite::Error| -> io::Error { + let map_err = |e: sqlite_thin::Error| -> io::Error { let msg = format!("Failed to migrate table {} from v2 to v3: {}", kv_table_name, e); io::Error::new(io::ErrorKind::Other, msg) }; @@ -166,7 +166,7 @@ mod tests { use std::fs; use lightning::util::persist::{KVStore, PaginatedKVStore}; - use rusqlite::{named_params, Connection}; + use sqlite_thin::{named_params, Connection}; use crate::io::sqlite_store::SqliteStore; use crate::io::test_utils::{do_read_write_remove_list_persist, random_storage_path}; diff --git a/src/io/sqlite_store/mod.rs b/src/io/sqlite_store/mod.rs index 1ea8d545a3..8f71d4bfdd 100644 --- a/src/io/sqlite_store/mod.rs +++ b/src/io/sqlite_store/mod.rs @@ -23,7 +23,7 @@ use lightning::util::persist::{ KVStore, MigratableKVStore, PageToken, PaginatedKVStore, PaginatedListResponse, }; use lightning_types::string::PrintableString; -use rusqlite::{named_params, Connection}; +use sqlite_thin::{named_params, Connection}; use crate::io::utils::{check_namespace_key_validity, create_dir_all_private}; use crate::runtime::StoreRuntime; @@ -395,7 +395,7 @@ impl SqliteStoreInner { |row| row.get(0), ) .map_err(|e| match e { - rusqlite::Error::QueryReturnedNoRows => { + sqlite_thin::Error::QueryReturnedNoRows => { let msg = format!( "Failed to read as key could not be found: {}/{}/{}", PrintableString(primary_namespace), @@ -563,7 +563,7 @@ impl SqliteStoreInner { .query_row(&count_sql, [], |row| { let count: i64 = row.get(0)?; usize::try_from(count) - .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(0, count)) + .map_err(|_| sqlite_thin::Error::IntegralValueOutOfRange(0, count)) }) .map_err(|e| { let msg = format!("Failed to count rows: {}", e); diff --git a/tests/rusqlite-compat/README.md b/tests/rusqlite-compat/README.md index c27412e60c..f416652e03 100644 --- a/tests/rusqlite-compat/README.md +++ b/tests/rusqlite-compat/README.md @@ -5,10 +5,14 @@ rusqlite release while using LDK Node's default features. The test writes throug LDK Node, reopens the store, and reads the database with the application's rusqlite. Neither rusqlite nor libsqlite3-sys is patched. +LDK Node itself accesses SQLite through sqlite-thin, which accepts any +libsqlite3-sys release from 0.28 onwards. As a build can only hold a single +libsqlite3-sys, the application's rusqlite determines which one is used. + The root crate's development dependencies on LDK Node 0.6.2 and 0.7.0 require rusqlite 0.31 unconditionally. They constrain root builds even when individual tests are filtered out, but do not participate in downstream resolution. Keep -this fixture separate so CI actually tests both ends of the supported range. +this fixture separate so CI actually tests both ends of the tested range. From the repository root, run: @@ -24,9 +28,8 @@ change its direct requirement with and rerun the test. Restore the maximum requirement afterwards. The resolver setting selects MSRV-compatible versions of unrelated transitive dependencies. -When changing the supported range, update both endpoints in +When changing the tested range, update both endpoints in `.github/workflows/rust.yml` and test each newly included release locally. The -current upper bound excludes 0.40.0 and 0.40.1, which use `cfg_select!` and fail to -compile on Rust 1.85. Although the bundled-feature probe for 0.40.2 passes on -1.85, Cargo cannot express a disjoint requirement that admits it while excluding -those earlier patches and retaining the older release lines. +upper endpoint stays at 0.39.0, the newest release line of which every patch +release compiles on Rust 1.85: 0.40.0 and 0.40.1 use `cfg_select!`, and +releases from 0.41 onwards declare a higher `rust-version`.