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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ Notable changes to `bdk_turso` are documented here. Released versions are linked
- **Breaking:** Removed `Error::ConflictingOptions`, which only reported combinations of the removed builders.
- **Dependency refresh.** Updated `bdk_wallet`, `bdk_chain`, `rand`, `toml`, and Turso to their latest stable releases. These updates do not change the public API, and the MSRV remains Rust 1.88.0.

### Fixed

- **Immutable wallet network.** `Store::write_network` and `Store::write_changeset` no longer overwrite a persisted network with a different one. The mismatch returns `Error::NetworkMismatch { stored, attempted }` before the transaction commits and leaves the database unchanged. Writing the same network remains idempotent, and switching networks requires a new database.

### Security

- **`time` vulnerability fixed.** `time` now resolves to 0.3.55, closing RUSTSEC-2026-0009 (`CVE-2026-25727`), a denial-of-service when parsing RFC 2822 timestamps.
Expand Down
16 changes: 15 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use core::num::TryFromIntError;

use bdk_chain::bitcoin;
use bdk_chain::miniscript;
use bitcoin::{consensus, hex::error::HexToArrayError, network::ParseNetworkError};
use bitcoin::{Network, consensus, hex::error::HexToArrayError, network::ParseNetworkError};

/// Errors returned while encoding, decoding, parsing, or accessing persisted wallet data.
#[derive(Debug)]
Expand All @@ -24,6 +24,16 @@ pub enum Error {
PsbtRequiresEncryption,
/// The stored network name could not be parsed as a Bitcoin network.
ParseNetwork(ParseNetworkError),
/// A write attempted to change the persisted wallet network.
///
/// A wallet's network is immutable after it is first persisted. To use a different network,
/// create a new database.
NetworkMismatch {
/// The network already stored in the database.
stored: Network,
/// The network supplied by the caller.
attempted: Network,
},
/// A store-to-store transfer could not safely copy the source schema or data.
Migration(String),
/// The blocking persister could not build its Tokio runtime.
Expand Down Expand Up @@ -61,6 +71,10 @@ impl fmt::Display for Error {
"PSBT persistence requires a database opened with local at-rest encryption"
),
Self::ParseNetwork(e) => write!(f, "Network Parse Error: {e}"),
Self::NetworkMismatch { stored, attempted } => write!(
f,
"Network Mismatch Error: stored network is {stored}, cannot change it to {attempted}"
),
#[cfg(feature = "remote")]
Self::UnsupportedOption(message) => write!(f, "Unsupported Option Error: {message}"),
Self::Migration(message) => write!(f, "Migration error: {message}"),
Expand Down
87 changes: 80 additions & 7 deletions src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ impl Store {
/// Network, descriptors, local-chain blocks, transaction-graph data, keychain scripts, and
/// locked outpoints are committed together. Run [`Store::migrate`] first, or initialize the
/// store through the async wallet persister, which migrates automatically.
///
/// The wallet network cannot change after it is first persisted. If [`ChangeSet::network`]
/// differs from the stored network, the write is rejected with [`Error::NetworkMismatch`]
/// before the transaction commits. To switch networks, use a new database.
pub async fn write_changeset(&self, changeset: &ChangeSet) -> Result<(), Error> {
let mut conn = self.connect().await?;
let txn = conn.transaction().await?;
Expand Down Expand Up @@ -49,7 +53,12 @@ impl Store {
Ok(())
}

/// Persist the wallet network, replacing any previously stored value.
/// Persist the wallet network, if none is stored yet.
///
/// The first write inserts the network. Writing the same network again is idempotent, but a
/// different network is rejected with [`Error::NetworkMismatch`] and leaves the stored value
/// unchanged. A wallet's network is immutable after it is first persisted; to switch networks,
/// use a new database.
///
/// This method opens and commits its own transaction; use wallet changeset persistence when
/// several state components must be written atomically.
Expand All @@ -67,8 +76,18 @@ impl Store {
conn: &DatabaseTransaction<'_>,
network: Network,
) -> Result<(), Error> {
if let Some(stored) = Self::read_network_in_transaction(conn).await? {
if stored != network {
return Err(Error::NetworkMismatch {
stored,
attempted: network,
});
}
return Ok(());
}

conn.execute(
"INSERT INTO network(id, network) VALUES(0, ?1) ON CONFLICT(id) DO UPDATE SET network = ?1",
"INSERT INTO network(id, network) VALUES(0, ?1)",
[network.to_string()],
)
.await?;
Expand Down Expand Up @@ -343,15 +362,69 @@ mod test {
store.migrate().await?;

store.write_network(Network::Bitcoin).await?;
store.write_network(Network::Signet).await?;
let err = store
.write_network(Network::Signet)
.await
.expect_err("changing the stored network must fail");

assert!(matches!(
err,
Error::NetworkMismatch {
stored: Network::Bitcoin,
attempted: Network::Signet,
}
));
assert_eq!(store.read_network().await?, Some(Network::Bitcoin));
assert_eq!(network_row_count(&store).await?, 1);
Ok(())
}

#[tokio::test]
async fn writing_the_same_network_is_idempotent() -> anyhow::Result<()> {
let store = Store::new_memory().await?;
store.migrate().await?;

store.write_network(Network::Bitcoin).await?;
store.write_network(Network::Bitcoin).await?;
store.write_network(Network::Bitcoin).await?;

assert_eq!(store.read_network().await?, Some(Network::Bitcoin));
assert_eq!(network_row_count(&store).await?, 1);
Ok(())
}

#[tokio::test]
async fn changeset_write_rejects_network_mismatch() -> anyhow::Result<()> {
let store = Store::new_memory().await?;
store.migrate().await?;

store.write_network(Network::Bitcoin).await?;
let changeset = ChangeSet {
network: Some(Network::Signet),
..Default::default()
};
let err = store
.write_changeset(&changeset)
.await
.expect_err("a changeset that changes the network must fail");

assert!(matches!(
err,
Error::NetworkMismatch {
stored: Network::Bitcoin,
attempted: Network::Signet,
}
));
assert_eq!(store.read_network().await?, Some(Network::Bitcoin));
assert_eq!(network_row_count(&store).await?, 1);
Ok(())
}

async fn network_row_count(store: &Store) -> anyhow::Result<i64> {
let conn = store.connect().await?;
let mut rows = conn.query("SELECT COUNT(*) FROM network", ()).await?;
let row = rows.next().await?.expect("expected count row");
let count: i64 = row.get(0)?;
assert_eq!(count, 1, "network table should have at most 1 row");
assert_eq!(store.read_network().await?, Some(Network::Signet));
Ok(())
Ok(row.get(0)?)
}

#[cfg(feature = "blocking")]
Expand Down
Loading