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..8713103837 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ default = [ "chain-esplora", "chain-electrum", "chain-bitcoind", - "storage-sqlite", + "storage-sqlite-bundled", "storage-filesystem", "storage-vss", "unified-payments", @@ -52,7 +52,8 @@ chain-electrum = [ "lightning-transaction-sync/electrum-rustls-ring", ] chain-bitcoind = ["dep:lightning-block-sync"] -storage-sqlite = ["dep:rusqlite"] +storage-sqlite = ["dep:sqlite-thin"] +storage-sqlite-bundled = ["storage-sqlite", "sqlite-thin/bundled"] storage-filesystem = ["dep:lightning-persister"] storage-vss = ["dep:vss-client", "dep:prost"] storage-postgres = ["dep:tokio-postgres", "dep:native-tls", "dep:postgres-native-tls"] @@ -67,7 +68,7 @@ uniffi-default = [ "uniffi", "chain-esplora", "chain-electrum", - "storage-sqlite", + "storage-sqlite-bundled", "storage-vss", "unified-payments", ] @@ -106,8 +107,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 = { version = "0.1.0", 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/README.md b/README.md index 1652541137..230e99c278 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,8 @@ LDK Node's optional dependencies are grouped by the functionality they provide: | `chain-esplora` | Esplora chain source | | `chain-electrum` | Electrum chain source | | `chain-bitcoind` | Bitcoin Core RPC and REST chain source | -| `storage-sqlite` | SQLite storage | +| `storage-sqlite` | SQLite storage, linking the system's SQLite library | +| `storage-sqlite-bundled` | SQLite storage, building SQLite from source | | `storage-filesystem` | Filesystem storage | | `storage-vss` | Versioned Storage Service storage | | `storage-postgres` | PostgreSQL storage | @@ -87,8 +88,12 @@ LDK Node's optional dependencies are grouped by the functionality they provide: | `uniffi-default` | The standard language-binding feature set | The `default` feature set preserves the native Rust API's previous behavior. It enables all three -chain sources, SQLite, filesystem and VSS storage, and unified payments. PostgreSQL and UniFFI -remain opt-in. Every build must enable at least one chain source feature. +chain sources, bundled SQLite, filesystem and VSS storage, and unified payments. PostgreSQL and +UniFFI remain opt-in. Every build must enable at least one chain source feature. + +`storage-sqlite` links the SQLite library installed on the system, which hence needs to be +available at build time and at runtime. Enable `storage-sqlite-bundled` instead to build SQLite from +source and link it statically, which requires a C compiler. On Linux, `storage-postgres` uses the system OpenSSL installation and requires the OpenSSL development headers and `pkg-config`. Enable `storage-postgres-vendored-tls` instead to build @@ -98,11 +103,12 @@ Disable the default features to select only the functionality and dependencies a needs. For example: ```shell -cargo build --no-default-features --features chain-esplora,storage-sqlite +cargo build --no-default-features --features chain-esplora,storage-sqlite-bundled ``` -`uniffi-default` enables UniFFI, Esplora, Electrum, SQLite, VSS, and unified payments. It excludes -Bitcoin Core, filesystem storage, and PostgreSQL. Binding users can add any of those features: +`uniffi-default` enables UniFFI, Esplora, Electrum, bundled SQLite, VSS, and unified payments. It +excludes Bitcoin Core, filesystem storage, and PostgreSQL. Binding users can add any of those +features: ```shell cargo build --no-default-features --features uniffi-default,chain-bitcoind diff --git a/src/io/sqlite_store/migrations.rs b/src/io/sqlite_store/migrations.rs index 7adde7e8b6..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}; @@ -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..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); @@ -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)] 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`.