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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here we could test the fallback mentioned above against an application that only depends on SQLite ldk-node, and does not specify a rustqlite dependency itself. Without the fallback cargo selects libsqlite3-sys 0.40.0 which does not build on MSRV 1.85.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also here we could also replace v0.39.0 with v0.40.2 to test the full range available on MSRV

env:
CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS: fallback
Expand Down
10 changes: 5 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ default = [
"chain-esplora",
"chain-electrum",
"chain-bitcoind",
"storage-sqlite",
"storage-sqlite-bundled",
"storage-filesystem",
"storage-vss",
"unified-payments",
Expand All @@ -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"]
Comment on lines -55 to +56

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here i'd prefer to have something like this:

storage-sqlite = ["storage-sqlite-system", "sqlite-thin/bundled"]
storage-sqlite-system = ["dep:sqlite-thin"]

This keeps something like

cargo build --no-default-features --features storage-sqlite

the same across this PR. Otherwise a user building with this command gets a dynamic link of SQLite, which they never asked for.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Features are new to v0.8, we can freely change them. And the default stays -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"]
Expand All @@ -67,7 +68,7 @@ uniffi-default = [
"uniffi",
"chain-esplora",
"chain-electrum",
"storage-sqlite",
"storage-sqlite-bundled",
"storage-vss",
"unified-payments",
]
Expand Down Expand Up @@ -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 }
Expand Down
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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.
Comment on lines +94 to +96

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be good to document here that with dynamic linking, database migrations requires at least SQLite 3.35.0. With 3.34.1, the v1 migration fails.


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
Expand All @@ -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
Expand Down
104 changes: 101 additions & 3 deletions src/io/sqlite_store/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
};
Expand Down Expand Up @@ -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};
Expand Down Expand Up @@ -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<String>, 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::<Result<Vec<_>, _>>()
.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"]);
}
}
Loading
Loading