Repository navigation
Add functions to test persistence #2012
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
evanlinjin
merged 3 commits into
bitcoindevkit:master
from
110CodingP:add_persist_test_utils
Oct 26, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
73dc5cd
feat(testenv): add `persist_test_utils` for testing persistence backends
110CodingP 206f9d0
test(chain): test rusqlite persistence with `assert_persist_changesets`
110CodingP c537631
test(file_store): test `Store` persistence with `assert_persist_chang…
110CodingP File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| #![cfg(feature = "rusqlite")] | ||
| #[cfg(feature = "miniscript")] | ||
| use bdk_chain::keychain_txout; | ||
| use bdk_chain::{local_chain, tx_graph, Merge}; | ||
| use bdk_testenv::persist_test_utils::*; | ||
| use core::fmt::Debug; | ||
| use rusqlite::Transaction; | ||
|
|
||
| #[test] | ||
| fn changesets_are_persisted() { | ||
| #[track_caller] | ||
| fn assert_sqlite_persists<C>( | ||
| changesets: &[C], | ||
| init_tables: fn(&Transaction) -> rusqlite::Result<()>, | ||
| from_sqlite: fn(&Transaction) -> rusqlite::Result<C>, | ||
| persist_to_sqlite: fn(&C, &Transaction) -> rusqlite::Result<()>, | ||
| ) where | ||
| C: Debug + PartialEq + Default + Merge + Clone, | ||
| { | ||
| let temp_dir = tempfile::tempdir().unwrap(); | ||
| assert_persist_changesets( | ||
| || { | ||
| let mut db = rusqlite::Connection::open(temp_dir.path().join("wallet.sqlite"))?; | ||
| let db_tx = db.transaction()?; | ||
| init_tables(&db_tx)?; | ||
| db_tx.commit()?; | ||
| Ok(db) | ||
| }, | ||
| |db| { | ||
| let db_tx = db.transaction()?; | ||
| Ok(from_sqlite(&db_tx)?) | ||
| }, | ||
| |db, changeset| { | ||
| let db_tx = db.transaction()?; | ||
| persist_to_sqlite(changeset, &db_tx)?; | ||
| db_tx.commit()?; | ||
| Ok(()) | ||
| }, | ||
| changesets, | ||
| ); | ||
| } | ||
|
|
||
| assert_sqlite_persists( | ||
| &tx_graph_changesets(), | ||
| tx_graph::ChangeSet::init_sqlite_tables, | ||
| tx_graph::ChangeSet::from_sqlite, | ||
| tx_graph::ChangeSet::persist_to_sqlite, | ||
| ); | ||
| #[cfg(feature = "miniscript")] | ||
| assert_sqlite_persists( | ||
| &keychain_txout_changesets(), | ||
| keychain_txout::ChangeSet::init_sqlite_tables, | ||
| keychain_txout::ChangeSet::from_sqlite, | ||
| keychain_txout::ChangeSet::persist_to_sqlite, | ||
| ); | ||
| assert_sqlite_persists( | ||
| &local_chain_changesets(), | ||
| local_chain::ChangeSet::init_sqlite_tables, | ||
| local_chain::ChangeSet::from_sqlite, | ||
| local_chain::ChangeSet::persist_to_sqlite, | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
ValuedMammal marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,197 @@ | ||
| //! This module provides utility functions for testing custom persistence backends. | ||
| use crate::{block_id, hash}; | ||
| use bdk_chain::{ | ||
| bitcoin::{self, transaction::Version, OutPoint}, | ||
| local_chain, tx_graph, ConfirmationBlockTime, Merge, | ||
| }; | ||
| use std::sync::Arc; | ||
|
|
||
| #[cfg(feature = "miniscript")] | ||
| use bdk_chain::{indexer::keychain_txout, DescriptorExt, SpkIterator}; | ||
| use core::{error::Error, fmt::Debug}; | ||
|
|
||
| use crate::utils::{create_test_tx, create_txout}; | ||
|
|
||
| #[cfg(feature = "miniscript")] | ||
| use crate::utils::{parse_descriptor, spk_at_index}; | ||
|
|
||
| const ADDRS: [&str; 2] = [ | ||
| "bcrt1q3qtze4ys45tgdvguj66zrk4fu6hq3a3v9pfly5", | ||
| "bcrt1q8an5jfmpq8w2hr648nn34ecf9zdtxk0qyqtrfl", | ||
| ]; | ||
|
|
||
| /// Asserts a persistence backend correctly stores and reloads a sequence of `ChangeSet`s. | ||
| /// | ||
| /// Persists every changeset, drops and reopens the store, then checks that `load` returns the merge | ||
| /// of everything `persist`ed. The backend is supplied as three closures: | ||
| /// | ||
| /// - `init`: open-or-create a handle. This must never wipe existing data. | ||
| /// - `load`: return the full persisted changeset (`C::default()` on a fresh store). | ||
| /// - `persist`: durably write one changeset on top of what's stored; must survive the handle being | ||
| /// dropped. | ||
| /// | ||
| /// # Panics | ||
| /// | ||
| /// Panics naming the failing step if a closure errors or a load doesn't match the expected merge. | ||
| #[track_caller] | ||
| pub fn assert_persist_changesets<C, Store, Init, Load, Persist>( | ||
| init: Init, | ||
| load: Load, | ||
| persist: Persist, | ||
| changesets: &[C], | ||
| ) where | ||
| C: Debug + PartialEq + Default + Merge + Clone, | ||
| Init: Fn() -> Result<Store, Box<dyn Error>>, | ||
| Load: Fn(&mut Store) -> Result<C, Box<dyn Error>>, | ||
| Persist: Fn(&mut Store, &C) -> Result<(), Box<dyn Error>>, | ||
| { | ||
| let mut store = match init() { | ||
| Ok(store) => store, | ||
| Err(err) => panic!("Failed to initialize the store: {err}"), | ||
| }; | ||
| let init_changeset = match load(&mut store) { | ||
| Ok(changeset) => changeset, | ||
| Err(err) => panic!("Failed to load from the new store: {err}"), | ||
| }; | ||
| assert!( | ||
| init_changeset.is_empty(), | ||
| "Loading from a new store should return an empty changeset." | ||
| ); | ||
|
|
||
| let mut merged_changeset = C::default(); | ||
| for (i, changeset) in changesets.iter().enumerate() { | ||
| if let Err(err) = persist(&mut store, changeset) { | ||
| panic!("Failed to persist changeset no. {}: {err}", i + 1); | ||
| } | ||
| merged_changeset.merge(changeset.clone()); | ||
| } | ||
|
|
||
|
evanlinjin marked this conversation as resolved.
|
||
| drop(store); | ||
| let mut store = match init() { | ||
| Ok(store) => store, | ||
| Err(err) => panic!("Failed to reopen the store: {err}"), | ||
| }; | ||
| let persisted_changeset = match load(&mut store) { | ||
| Ok(changeset) => changeset, | ||
| Err(err) => panic!("Failed to load after reopening the store: {err}"), | ||
| }; | ||
| assert_eq!( | ||
| persisted_changeset, merged_changeset, | ||
| "Loaded changeset after reopening doesn't match what was persisted." | ||
| ); | ||
| } | ||
|
|
||
| /// Get two [`tx_graph::ChangeSet`]s. | ||
| pub fn tx_graph_changesets() -> [tx_graph::ChangeSet<ConfirmationBlockTime>; 2] { | ||
| use tx_graph::ChangeSet; | ||
|
|
||
| let tx1 = Arc::new(create_test_tx( | ||
| [hash!("BTC")], | ||
| [0], | ||
| [30_000], | ||
| [ADDRS[0]], | ||
| Version::ONE, | ||
| 0, | ||
| )); | ||
|
|
||
| let conf_anchor: ConfirmationBlockTime = ConfirmationBlockTime { | ||
| block_id: block_id!(910425, "Rust"), | ||
| confirmation_time: 1755416660, | ||
| }; | ||
|
|
||
| let tx_graph_changeset1 = ChangeSet::<ConfirmationBlockTime> { | ||
| txs: [tx1.clone()].into(), | ||
| txouts: [ | ||
| (OutPoint::new(hash!("BDK"), 0), create_txout(1300, ADDRS[1])), | ||
| ( | ||
| OutPoint::new(hash!("Bitcoin_fixes_things"), 0), | ||
| create_txout(1400, ADDRS[1]), | ||
| ), | ||
| ] | ||
| .into(), | ||
| anchors: [(conf_anchor, tx1.compute_txid())].into(), | ||
| last_seen: [(tx1.compute_txid(), 1755416650)].into(), | ||
| first_seen: [(tx1.compute_txid(), 1755416655)].into(), | ||
| last_evicted: [(tx1.compute_txid(), 1755416660)].into(), | ||
| }; | ||
|
|
||
| let tx2 = Arc::new(create_test_tx( | ||
| [tx1.compute_txid()], | ||
| [0], | ||
| [20_000], | ||
| [ADDRS[0]], | ||
| Version::ONE, | ||
| 0, | ||
| )); | ||
|
Comment on lines
+118
to
+125
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. https://github.com/rust-fuzz/arbitrary could help remove work here, at the same time is exposing the API for fuzzers and other tests. |
||
|
|
||
| let conf_anchor: ConfirmationBlockTime = ConfirmationBlockTime { | ||
| block_id: block_id!(910426, "BOSS"), | ||
| confirmation_time: 1755416700, | ||
| }; | ||
|
|
||
| let tx_graph_changeset2 = ChangeSet::<ConfirmationBlockTime> { | ||
| txs: [tx2.clone()].into(), | ||
| txouts: [( | ||
| OutPoint::new(hash!("Magical_Bitcoin"), 0), | ||
| create_txout(10000, ADDRS[1]), | ||
| )] | ||
| .into(), | ||
| anchors: [(conf_anchor, tx2.compute_txid())].into(), | ||
| last_seen: [(tx2.compute_txid(), 1755416700)].into(), | ||
| first_seen: [(tx2.compute_txid(), 1755416670)].into(), | ||
| last_evicted: [(tx2.compute_txid(), 1755416760)].into(), | ||
| }; | ||
|
|
||
| [tx_graph_changeset1, tx_graph_changeset2] | ||
| } | ||
|
|
||
| /// Get two [`keychain_txout::ChangeSet`]s. | ||
| #[cfg(feature = "miniscript")] | ||
| pub fn keychain_txout_changesets() -> [keychain_txout::ChangeSet; 2] { | ||
| use crate::utils::DESCRIPTORS; | ||
| use keychain_txout::ChangeSet; | ||
|
|
||
| let descs = DESCRIPTORS.map(|desc| parse_descriptor(desc).0); | ||
| let descriptor_ids = descs.each_ref().map(|d| d.descriptor_id()); | ||
|
|
||
| let changeset = ChangeSet { | ||
| last_revealed: [(descriptor_ids[0], 1), (descriptor_ids[1], 100)].into(), | ||
| spk_cache: [ | ||
| ( | ||
| descriptor_ids[0], | ||
| SpkIterator::new_with_range(&descs[0], 0..=26).collect(), | ||
| ), | ||
| ( | ||
| descriptor_ids[1], | ||
| SpkIterator::new_with_range(&descs[1], 0..=125).collect(), | ||
| ), | ||
| ] | ||
| .into(), | ||
| }; | ||
|
|
||
| let changeset_new = ChangeSet { | ||
| last_revealed: [(descriptor_ids[0], 2)].into(), | ||
| spk_cache: [( | ||
| descriptor_ids[0], | ||
| [(27, spk_at_index(&descs[0], 27))].into(), | ||
| )] | ||
| .into(), | ||
| }; | ||
|
|
||
| [changeset, changeset_new] | ||
| } | ||
|
|
||
| /// Get two [`local_chain::ChangeSet`]s. | ||
| pub fn local_chain_changesets() -> [local_chain::ChangeSet; 2] { | ||
| use local_chain::ChangeSet; | ||
|
evanlinjin marked this conversation as resolved.
|
||
|
|
||
| let changeset = ChangeSet { | ||
| blocks: [(910425, Some(hash!("B"))), (910426, Some(hash!("D")))].into(), | ||
| }; | ||
|
|
||
| let changeset_new = ChangeSet { | ||
| blocks: [(910427, Some(hash!("K")))].into(), | ||
| }; | ||
|
|
||
| [changeset, changeset_new] | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.