Expand description
§Project status
bdk_turso is early-stage and experimental. It currently implements async wallet persistence, and its API may change. bdk_turso was built in response to a request for Turso support in bdk_wallet.
§What is bdk_turso?
bdk_turso is a standalone persistence backend for bdk_wallet, storing wallet state in Turso, an in-process, SQLite-compatible database written in Rust. It implements the AsyncWalletPersister trait behind the wallet feature and WalletPersister trait behing blocking, without changes to bdk_wallet or bdk_persist.
bdk_turso is forked from bdk_sqlite, with its persistence implementation adapted for Turso’s async-first API. Its persistence tests are adapted from the test suite in bdk_redb.
§Why Turso?
§Native async persistence
Turso’s async-first design allows bdk_turso to implement AsyncWalletPersister natively rather than wrapping blocking database operations in spawn_blocking. Turso is designed to support concurrent write scaling. Connections wait up to five seconds for a contended write lock before returning an error, matching the default used by SQLite drivers. Reproducible comparisons with bdk_sqlite and bdk_redb are published in BENCHMARK.md; results are workload- and machine-dependent and do not imply that one backend is best for every use case.
§SQLite compatibility
bdk_turso stays within Turso’s SQLite-compatible feature subset and avoids Turso-only extensions. Unencrypted database files can be read by bdk_sqlite; Turso-encrypted files require Turso to open. Do not call bdk_sqlite::Store::migrate() on a bdk_turso database: it has no SQLx migration history, so bdk_sqlite runs migrations containing DROP TABLE IF EXISTS statements and erases the existing wallet state.
§Benchmarks
The repository includes a reproducible benchmark suite in benches/backends.rs that runs the same generated wallet changesets through bdk_turso, bdk_sqlite, and bdk_redb. It measures changeset read and write speed, concurrent writes at several writer counts, opening an existing database, and on-disk storage size. Run it with:
cargo bench --bench backendsSample counts, batch sizes, writer counts, dataset shape, Turso options, and the included backends can be set in an optional benches/config.toml; copy benches/example.toml to that path and edit it, or pass -- --config path/to/config.toml. Without a config file the defaults are used.
Detailed results, environment details, methodology, and limitations are in BENCHMARK.md. Results are kept for each measured release and are not CI performance thresholds.
§Installation
bdk_turso requires Rust 1.88.0 or newer and an async runtime; the examples and persistence calls use tokio. The turso dependency is compiled from source as a pure-Rust crate, so no separate database server is needed.
Add the crate with the features you need:
cargo add bdk_turso # wallet persistence, the default feature
cargo add bdk_turso --features psbt # plus PSBT storage
cargo add bdk_turso --features remoteOr declare it directly in Cargo.toml:
[dependencies]
bdk_turso = { version = "0.3", features = ["wallet", "psbt"] }Open a store and call Store::migrate() before reading or writing; tables for disabled features are not created. See Feature flags for the full list.
§Usage
With the wallet feature enabled, Store implements BDK’s async wallet persistence API. Replace the descriptor strings below with valid descriptors for your wallet.
use bdk_turso::Store;
use bdk_wallet::{bitcoin::Network, KeychainKind, Wallet};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let external_descriptor = "wpkh(...)";
let internal_descriptor = "wpkh(...)";
let mut store = Store::new("wallet.sqlite").await?;
store.migrate().await?;
let mut wallet = match Wallet::load()
.descriptor(KeychainKind::External, Some(external_descriptor))
.descriptor(KeychainKind::Internal, Some(internal_descriptor))
.check_network(Network::Regtest)
.load_wallet_async(&mut store)
.await?
{
Some(wallet) => wallet,
None => Wallet::create(external_descriptor, internal_descriptor)
.network(Network::Regtest)
.create_wallet_async(&mut store)
.await?,
};
let address = wallet.reveal_next_address(KeychainKind::External);
wallet.persist_async(&mut store).await?;
println!("Receive address: {}", address.address);
Ok(())
}§Blocking persistence
wallet enables the blocking feature by default, so Store also implements BDK’s blocking WalletPersister and the non-async load_wallet and create_wallet APIs work too:
use bdk_turso::Store;
use bdk_wallet::{bitcoin::Network, KeychainKind, Wallet};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut store = Store::new("wallet.sqlite").await?;
let _wallet = Wallet::load()
.descriptor(KeychainKind::External, Some("wpkh(...)"))
.check_network(Network::Regtest)
.load_wallet(&mut store)?;
Ok(())
}Each blocking call runs on a dedicated thread with its own Tokio runtime, so it is safe to call from inside an async runtime. It still blocks the calling thread until the operation finishes, so prefer the async persister on async hot paths.
§Options and encryption
Options::new() leaves all experimental Turso settings disabled. Build the options before opening the store and pass them to Store::new_with_options, Store::new_memory_with_options, or Store::new_remote_with_options; the settings apply while Turso opens the database and cannot be changed on an open store.
§Encryption
Local at-rest encryption is the main option. It is configured with the publicly re-exported EncryptionOpts and Options::with_encryption; no separate Cargo feature is required. Supply a 32-byte key as hexadecimal through a secret manager or environment variable, never a committed literal. Keep the same cipher and key to reopen the database; losing the key makes its data inaccessible.
generate_encryption_opts() builds options for a new database: it sets cipher to aes256gcm and fills hexkey with a random 32-byte key. Store that hex key safely before opening the database and reuse it to reopen it.
use bdk_turso::{EncryptionOpts, Options, Store};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let options = Options::new().with_encryption(EncryptionOpts {
cipher: "aes256gcm".to_owned(),
hexkey: std::env::var("TURSO_ENCRYPTION_HEXKEY")?,
});
let store = Store::new_with_options("wallet-encrypted.sqlite", options).await?;
store.migrate().await?;
Ok(())
}Local encryption is not supported for remote sync stores, and Turso Cloud encryption does not encrypt the local cache; see Remote Turso.
§Other Turso options
The remaining builders are pass-through engine settings. Except for with_transaction_behavior, they do not change the crate’s schema or persistence queries; they only affect SQL that the application runs on the same database. The default schema already creates B-tree indexes for its lookup columns, so with_index_method is only needed for alternative index methods.
| Builder | What it enables | When to use it | Effect on bdk_turso queries |
|---|---|---|---|
with_index_method | Turso’s experimental index methods, for example CREATE INDEX ... USING toy_vector_sparse_ivf (...) | Application SQL that needs a non-B-tree index method | None. Ordinary B-tree indexes are always available and the schema creates them; the flag is not needed for the crate’s lookups. Turso’s fts method is not compiled into the crate’s default dependency build. |
with_multiprocess_wal | Turso’s WAL coordinator for sharing one file between operating-system processes | Several processes open the same database file | None. It adds cross-process locking and coordination; Store clones in one process already share a database handle. |
with_vacuum | The VACUUM statement | Reclaiming space after large deletes or migrations | None. The crate never runs VACUUM; call it from application SQL. |
with_attach | ATTACH DATABASE and DETACH DATABASE | Application SQL that joins another SQLite-compatible file | None. migrate_to copies tables without ATTACH. |
with_generated_columns | Generated columns in application schemas | Application tables with computed columns | None. The crate schema has no generated columns and its INSERT/SELECT statements name columns explicitly. |
with_without_rowid | WITHOUT ROWID table definitions | Application tables with composite primary keys that do not need a rowid | None. The crate schema does not use WITHOUT ROWID; block and keychain rely on integer rowid aliases. |
with_mvcc_passive_checkpoint | Turso’s experimental passive-checkpoint behavior for MVCC databases | Long-running MVCC workloads that need background checkpointing | None. It does not start a checkpoint. Select Concurrent through with_transaction_behavior (or enable MVCC externally) first. |
with_transaction_behavior | The BEGIN mode for every transaction: Deferred, Immediate, Exclusive, or Concurrent | Tuning locking and write contention; Concurrent allows parallel writers | Applies to all crate transactions. Concurrent switches local databases to MVCC and is rejected for remote sync; migration still uses Deferred because Turso rejects DDL under BEGIN CONCURRENT. |
The four transaction behaviors are mutually exclusive because Turso stores one behavior per connection. Calling with_transaction_behavior again replaces the previous value; the last call wins. with_multiprocess_wal cannot be combined with Concurrent: Turso’s MVCC mode does not support multi-process access, so the constructor returns Error::ConflictingOptions.
use bdk_turso::{Options, Store, TransactionBehavior};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let options = Options::new()
.with_attach()
.with_generated_columns()
.with_transaction_behavior(TransactionBehavior::Immediate);
let store = Store::new_with_options("wallet.sqlite", options).await?;
store.migrate().await?;
Ok(())
}Local at-rest encryption and with_mvcc_passive_checkpoint are rejected by remote sync stores with an error, as is TransactionBehavior::Concurrent. with_remote_encryption is the only encryption option available to them; see Remote Turso.
§PSBT persistence
Enable the psbt feature to store partially signed transactions. It provides Store::write_psbt and Store::read_psbt and is independent of the wallet feature; Store::migrate() creates the psbt table only when the feature is enabled.
A PSBT is keyed by the txid of its unsigned transaction, and the complete PSBT is serialized, including signing metadata. Writing another PSBT for the same unsigned transaction replaces the stored one and returns that txid. Store::read_psbt returns Ok(None) when nothing is stored for the txid.
PSBTs can contain partial signatures, so persistence fails closed on unencrypted databases. Both methods return Error::PsbtRequiresEncryption unless the store was opened with Options::with_encryption. Stores created without encryption, stores wrapped with Store::from_database (whose opening options are unknown), and remote stores (whose local cache is not encrypted) are rejected.
use bdk_turso::Store;
let txid = store.write_psbt(&psbt).await?;
let stored = store.read_psbt(txid).await?;
assert_eq!(stored.as_ref(), Some(&psbt));This lets an unsigned PSBT survive a restart, be signed later, and be written back under the same unsigned txid. The transaction example builds, reloads, verifies, signs, and broadcasts a PSBT this way; see Examples. PSBT writes follow the persistence conflict behavior described below.
§Persistence conflict behavior
bdk_turso uses last-write-wins behavior for keyed persistence writes: when an incoming write targets an existing key, its value replaces the stored value rather than being ignored. This applies to component and wallet changeset writes, including a replacement block hash at the same height, and to PSBT writes. Explicit deletion entries remove their rows. This is storage-level behavior, not semantic validation of which value is newer or correct; ordering between independent remote clients follows Turso’s sync behavior.
§Examples
Both examples read examples/config.toml. Copy the committed template and edit the local copy:
cp examples/example.toml examples/config.tomlexamples/config.toml is ignored by git, so credentials stay out of the repository. Set the database path, network, Bitcoin Core RPC URL and credentials, external and internal descriptors, and optionally a recipient address. Add encryption_hexkey (64 hexadecimal characters) to open the database with local at-rest encryption; it is required by the transaction example because PSBT persistence is rejected on unencrypted databases. The template ships regtest-only sample keys; replace them before using another network. A database created without encryption cannot later be opened with a key. If the file is missing or invalid, the examples stop with an error explaining how to create it and which value is wrong.
cargo run --example walletloads the config, creates or loads the wallet, reveals a receive address, and syncs with a local Bitcoin Core regtest node.cargo run --features psbt --example transactionsyncs a regtest wallet, stores and reloads an unsigned PSBT, confirms it round-trips, signs it, broadcasts it, and persists the resulting wallet changeset. It requiresencryption_hexkey.recipient_addressis optional until this example reaches the send step; if the wallet has no spendable funds, it prints a receive address — fund it, mine 101 blocks, then rerun.
§Remote Turso
Enable the remote feature to connect to Turso Cloud through Turso’s local sync engine. The store keeps a local cache at the supplied path, pulls remote changes before reads, and pushes committed writes. An upload can fail after the local commit; the cache retains the change and the persistence operation returns Error::RemotePush. Call store.push().await to retry uploading pending changes without reapplying the changeset; a failure from this call is also reported as Error::RemotePush. The cache is not encrypted by Turso Cloud encryption; configure Options::with_remote_encryption for Turso Cloud database encryption and protect the local cache separately.
use bdk_turso::Store;
let store = Store::new_remote(
"wallet-cache.db",
&remote_url,
&auth_token,
).await?;
store.migrate().await?;Local at-rest encryption, MVCC passive checkpointing, and TransactionBehavior::Concurrent are not supported by Turso’s remote sync builder and return an error if requested. The ignored sync integration test can target a disposable Turso Cloud database or a local Turso sync server. Set BDK_TURSO_REMOTE_URL and BDK_TURSO_AUTH_TOKEN to the endpoint and token accepted by that server, then run cargo test --features remote --test persistence remote_store_syncs_changesets_between_local_caches -- --ignored.
§Feature flags
Store::migrate() always creates the core block and transaction tables. Wallet-specific and PSBT tables are created only when their respective features are enabled. The default schema also creates B-tree indexes for block(hash), txout(script), anchor(txid), and anchor(block_hash); the wallet schema adds keychain_script_pubkey(script).
| Feature | Description |
|---|---|
wallet | Enables wallet-specific tables, the AsyncWalletPersister implementation, and (through blocking) the blocking WalletPersister. |
blocking | Implements the blocking WalletPersister for Store. Enabled by default by wallet. |
psbt | Enables the PSBT table and the write_psbt/read_psbt storage methods; independent of wallet. |
remote | Enables Turso Cloud sync with a local cache. |
§Minimum Supported Rust Version (MSRV)
The MSRV is 1.88.0, based on the current resolved dependency graph.
§License
Licensed under either of MIT or Apache License, Version 2.0, at your option.
§Contribution
Contributions are welcome. Please read the contribution guide, the BDK contributing guidelines, and the BDK community standards.
Structs§
- Options
- Opt-in Turso features applied when opening a
Store. - Store
- An asynchronous store for BDK wallet changesets backed by Turso.
Enums§
- Error
- Errors returned while encoding, decoding, parsing, or accessing persisted wallet data.
- Transaction
Behavior - Options for transaction behavior. See BEGIN TRANSACTION for details.
Functions§
- generate_
encryption_ opts - Generate local encryption options with a random 32-byte key and the
aes256gcmcipher.