39 Commits

Author SHA1 Message Date
Steve Myers
79262185d5
refactor(chain)!: update KeychainTxOutIndex methods to use owned ScriptBuf 2024-07-21 20:28:01 -05:00
Rob N
7c07b9de02
refactor(chain)!: update KeychainTxOutIndex methods to use owned K 2024-07-21 20:27:59 -05:00
志宇
6b43001951
feat!: Rework sqlite, changesets, persistence and wallet-construction
Rework sqlite: Instead of only supported one schema (defined in
`bdk_sqlite`), we have a schema per changeset type for more flexiblity.

* rm `bdk_sqlite` crate (as we don't need `bdk_sqlite::Store` anymore).
* add `sqlite` feature on `bdk_chain` which adds methods on each
  changeset type for initializing tables, loading the changeset and
  writing.

Rework changesets: Some callers may want to use `KeychainTxOutIndex`
where `K` may change per descriptor on every run. So we only want to
persist the last revealed indices by `DescriptorId` (which uniquely-ish
identifies the descriptor).

* rm `keychain_added` field from `keychain_txout`'s changeset.
* Add `keychain_added` to `CombinedChangeSet` (which is renamed to
  `WalletChangeSet`).

Rework persistence: add back some safety and convenience when persisting
our types. Working with changeset directly (as we were doing before) can
be cumbersome.

* Intoduce `struct Persisted<T>` which wraps a type `T` which stores
  staged changes to it. This adds safety when creating and or loading
  `T` from db.
* `struct Persisted<T>` methods, `create`, `load` and `persist`, are
  avaliable if `trait PersistWith<Db>` is implemented for `T`. `Db`
  represents the database connection and `PersistWith` should be
  implemented per database-type.
* For async, we have `trait PersistedAsyncWith<Db>`.
* `Wallet` has impls of `PersistedWith<rusqlite::Connection>`,
  `PersistedWith<rusqlite::Transaction>` and
  `PersistedWith<bdk_file_store::Store>` by default.

Rework wallet-construction: Before, we had multiple methods for loading
and creating with different input-counts so it would be unwieldly to add
more parameters in the future. This also makes it difficult to impl
`PersistWith` (which has a single method for `load` that takes in
`PersistWith::LoadParams` and a single method for `create` that takes in
`PersistWith::CreateParams`).

* Introduce a builder pattern when constructing a `Wallet`. For loading
  from persistence or `ChangeSet`, we have `LoadParams`. For creating a
  new wallet, we have `CreateParams`.
2024-07-18 03:25:41 +00:00
Wei Chen
1a62488abf
feat(chain)!: Implement ConfirmationBlockTime
Both `bdk_electrum` and `bdk_esplora` now report the exact block
that the transaction is in, which removes the need for having the
old `ConfirmationTimeHeightAnchor` and `ConfirmationHeightAnchor`.
This PR introduces a new, simpler anchor type that can be modified
to support additional data in the future.
2024-07-09 00:23:02 +08:00
Wei Chen
962305f415
chore(chain)!: Rename Append to Merge 2024-07-07 16:46:10 +08:00
valued mammal
c3fc1dd123
ref(chain)!: create module indexer
and replace keychain module with `balance.rs`
2024-07-05 12:22:28 -04:00
valued mammal
2ce4bb4dfc
test(indexed_tx_graph): Add test_get_chain_position 2024-06-30 10:08:54 -04:00
valued mammal
bbc19c3536
fix(tx_graph)!: Change tx_last_seen to Option<u64>
Also fixup `test_list_owned_txouts` to check that the right
outputs, utxos, and balance are returned at different local
chain heights.

This fixes an issue where unbroadcast and otherwise non-canonical
transactions were returned from methods `list_chain_txs` and
`Wallet::transactions` because every tx inserted had a last_seen
of 0 making it appear unconfirmed.

Note this commit changes the way `Balance` is represented due to
new logic in `try_get_chain_position` that no longer considers
txs with non-canonical anchors. Before this change, a tx anchored
to a block that is reorged out had a permanent effect on the
pending balance, and now only txs with a last_seen time or an
anchor confirmed in the best chain will return a `ChainPosition`.
2024-06-30 10:08:54 -04:00
LLFourn
4d2442c37f
chore(chain): misc docs and insert_descriptor fixes 2024-06-13 22:52:43 +08:00
LLFourn
bc2a8be979
refactor(keychain): Fix KeychainTxOutIndex range queries
The underlying SpkTxOutIndex should not use DescriptorIds to index
because this loses the ordering relationship of the spks so queries on
subranges of keychains work.

Along with that we enforce that there is a strict 1-to-1 relationship
between descriptors and keychains. Violating this leads to an error in
insert_descriptor now.

In general I try to make the translation layer between the SpkTxOutIndex
and the KeychainTxOutIndex thinner. Ergonomics of this will be improved
in next commit.

The test from the previous commit passes.
2024-06-13 22:52:43 +08:00
Leonardo Lima
2a4564097b
deps(bdk): bump bitcoin to 0.32.0, miniscript to 12.0.0
deps(chain): bump `bitcoin` to `0.32.0`, miniscript to `12.0.0`

fix(chain): use `minimal_non_dust()` instead of `dust_value()`

fix(chain): use `compute_txid()` instead of `txid`

deps(testenv): bump `electrsd` to `0.28.0`

deps(electrum): bump `electrum-client` to `0.20.0`

fix(electrum): use `compute_txid()` instead of `txid`

deps(esplora): bump `esplora-client` to `0.8.0`

deps(bitcoind_rpc): bump `bitcoin` to `0.32.0`, `bitcoincore-rpc` to
`0.19.0`

fix(bitcoind_rpc): use `compute_txid()` instead of `txid`

fix(nursery/tmp_plan): use proper `sighash` errors, and fix the expected
`Signature` fields

fix(sqlite): use `compute_txid()` instead of `txid`

deps(hwi): bump `hwi` to `0.9.0`

deps(wallet): bump `bitcoin` to `0.32.0`, miniscript to `12.0.0`

fix(wallet): use `compute_txid()` and `minimal_non_dust()`

- update to use `compute_txid()` instead of deprecated `txid()`
- update to use `minimal_non_dust()` instead of `dust_value()`
- remove unused `bitcoin::hex::FromHex`.

fix(wallet): uses `.into` conversion on `Network` for `NetworkKind`

- uses `.into()` when appropriate, otherwise use the explicit
  `NetworkKind`, and it's `.is_mainnet()` method.

fix(wallet): add P2wpkh, Taproot, InputsIndex errors to `SignerError`

fix(wallet): fields on taproot, and ecdsa `Signature` structure

fix(wallet/wallet): convert `Weight` to `usize` for now

- converts the `bitcoin-units::Weight` type to `usize` with help of
  `to_wu()` method.
- it should be updated/refactored in the future to handle the `Weight`
  type throughout the code instead of current `usize`, only converting
  it for now.
- allows the usage of deprecated `is_provably_unspendable()`, needs
  further discussion if suggested `is_op_return` is suitable.
- update the expect field to `signature`, as it was renamed from `sig`.

fix(wallet/wallet): use `is_op_return` instead of
`is_provably_unspendable`

fix(wallet/wallet): use `relative::Locktime` instead of `Sequence`

fix(wallet/descriptor): use `ParsePublicKeyError`

fix(wallet/descriptor): use `.into()` to convert from `AbsLockTime` and
`RelLockTime` to `absolute::LockTime` and `relative::LockTime`

fix(wallet/wallet): use `Message::from_digest()` instead of relying on
deprecated `ThirtyTwoByteHash` trait.

fix(wallet/descriptor+wallet): expect `Threshold` type, and handle it
internally

fix(wallet/wallet): remove `0x` prefix from expected `TxId` display

fix(examples): use `compute_txid()` instead of `txid`

fix(ci): remove usage of `bitcoin/no-std` feature

- remove comment: `# The `no-std` feature it's implied when the `std` feature is disabled.`
2024-06-12 10:31:50 -03:00
Daniela Brozzoni
1d294b734d
fix: Run tests only if the miniscript feature is..
..enabled, enable it by default
2024-05-08 15:49:44 +02:00
Daniela Brozzoni
4f05441a00
keychain::ChangeSet includes the descriptor
- The KeychainTxOutIndex's internal SpkIterator now uses DescriptorId
  instead of K. The DescriptorId -> K translation is made at the
  KeychainTxOutIndex level.
- The keychain::Changeset is now a struct, which includes a map for last
  revealed indexes, and one for newly added keychains and their
  descriptor.

API changes in bdk:
- Wallet::keychains returns a `impl Iterator` instead of `BTreeMap`
- Wallet::load doesn't take descriptors anymore, since they're stored in
  the db
- Wallet::new_or_load checks if the loaded descriptor from db is the
  same as the provided one

API changes in bdk_chain:
- `ChangeSet` is now a struct, which includes a map for last revealed
  indexes, and one for keychains and descriptors.
- `KeychainTxOutIndex::inner` returns a `SpkIterator<(DescriptorId, u32)>`
- `KeychainTxOutIndex::outpoints` returns a `impl Iterator` instead of `&BTreeSet`
- `KeychainTxOutIndex::keychains` returns a `impl Iterator` instead of
  `&BTreeMap`
- `KeychainTxOutIndex::txouts` doesn't return a ExactSizeIterator
  anymore
- `KeychainTxOutIndex::unbounded_spk_iter` returns an `Option`
- `KeychainTxOutIndex::next_index` returns an `Option`
- `KeychainTxOutIndex::last_revealed_indices` returns a `BTreeMap`
  instead of `&BTreeMap`
- `KeychainTxOutIndex::reveal_to_target` returns an `Option`
- `KeychainTxOutIndex::reveal_next_spk` returns an `Option`
- `KeychainTxOutIndex::next_unused_spk` returns an `Option`
- `KeychainTxOutIndex::add_keychain` has been renamed to
  `KeychainTxOutIndex::insert_descriptor`, and now it returns a
  ChangeSet
2024-05-08 15:49:41 +02:00
Daniela Brozzoni
8ff99f27df
ref(chain): Define test descriptors, use them...
...everywhere
2024-05-08 13:23:28 +02:00
Leonardo Lima
8a33d98db9
feat: update wallet::Balance to use bitcoin::Amount
- update all fields `immature`, ` trusted_pending`, `unstrusted_pending`
  and `confirmed` to use the `bitcoin::Amount` instead of `u64`
- update all `impl Balance` methods to use `bitcoin::Amount`
- update all tests that relies on `keychain::Balance`
2024-05-04 21:59:07 -03:00
Tobin C. Harding
984c758f96
Upgrade miniscript/bitcoin dependency
Upgrade:

- bitcoin to v0.31.0
- miniscript to v11.0.0

Note: The bitcoin upgrade includes improvements to the
`Transaction::weight()` function, it appears those guys did good, we
no longer need to add the 2 additional weight units "just in case".
2024-04-08 15:16:02 +10:00
志宇
9a62d56900
feat(chain): add get and range methods to CheckPoint
These methods allow us to query for checkpoints contained within the
linked list by height and height range. This is useful to determine
checkpoints to fetch for chain sources without having to refer back to
the `LocalChain`.

Currently this is not implemented efficiently, but in the future, we
will change `CheckPoint` to use a skip list structure.
2024-04-05 16:36:00 +08:00
志宇
8ab58af093
feat(chain)!: wrap TxGraph txs with Arc
Wrapping transactions as `Arc<Transaction>` allows us to share
transactions cheaply between the chain-source and receiving structures.
Therefore the chain-source can keep already-fetched transactions (save
bandwidth) and have a shared pointer to the transactions (save memory).

This is better than the current way we do things, which is to refer back
to the receiving structures mid-sync.

Documentation for `TxGraph` is also updated.
2024-03-25 12:57:26 +08:00
Antoine Poinsot
4fd539b647
feat(chain)!: KeychainTxOutIndex uses a universal lookahead
The wallet is currently created without setting any lookahead value for
the keychain. This implicitly makes it a lookahead of 0. As this is a
high-level interface we should avoid footguns and aim for a reasonable
default.

Instead of simply patching it for wallet, we alter `KeychainTxOutIndex`
to have a default lookahead value. Additionally, instead of a
per-keychain lookahead, the constructor asks for a `lookahead` value.
This avoids the footguns of having methods which allows the caller the
decrease the `lookahead` (and therefore panicing). This also simplifies
the API.

Co-authored-by: Antoine Poisot <darosior@protonmail.com>
Co-authored-by: 志宇 <hello@evanlinjin.me>
2023-12-28 12:51:11 +08:00
志宇
5998a22819
feat!: LocalChain with hardwired genesis checkpoint
This ensures that `LocalChain` will always have a tip. The `ChainOracle`
trait's `get_chain_tip` method no longer needs to return an option.
2023-11-16 06:41:18 +08:00
志宇
4f5695d43a
chain: improvements to IndexedTxGraph and TxGraph APIs
For `IndexedTxGraph`:
- Remove `InsertTxItem` type (this is too complex).
    - `batch_insert_relevant` now uses a simple tuple `(&tx, anchors)`.
    - `batch_insert` is now also removed, as the same functionality can be
      done elsewhere.
- Add internal helper method `index_tx_graph_changeset` so we don't need
  to create a seprate `TxGraph` update in each method.
- `batch_insert_<relevant>_unconfirmed` no longer takes in an option of
  last_seen.
- `batch_insert_unconfirmed` no longer takes a reference of a
  transaction (since we apply all transactions anyway, so there is no
  need to clone).

For `TxGraph`:
- Add `batch_insert_unconfirmed` method.
2023-10-09 22:14:04 +08:00
志宇
240657b167
chain: add batch-insert methods for IndexedTxGraph 2023-10-09 22:14:03 +08:00
Daniela Brozzoni
80f5ecf3be
feat(chain): Add initial_changeset to graphs
Add `initial_changeset` to TxGraph and IndexedTxGraph
2023-08-18 11:52:31 +02:00
Daniela Brozzoni
ea50b6a932
refactor!(chain): Unify ChangeSet nomenclature
This commit renames:

- indexed_tx_graph::IndexedAdditions -> indexed_tx_graph::ChangeSet
- indexed_tx_graph::IndexedAdditions::graph_additions -> indexed_tx_graph::ChangeSet::graph
- indexed_tx_graph::IndexedAdditions::index_additions -> indexed_tx_graph::ChangeSet::indexer
- tx_graph::Additions -> tx_graph::ChangeSet
- keychain::DerivationAdditions -> keychain::ChangeSet
- CanonicalTx::node -> CanonicalTx::tx_node
- CanonicalTx::observed_as -> CanonicalTx::chain_position
- LocalChangeSet -> WalletChangeSet
- LocalChangeSet::chain_changeset -> WalletChangeSet::chain
- LocalChangeSet::indexed_additions -> WalletChangeSet::indexed_tx_graph
- LocalUpdate -> WalletUpdate

This commit also changes the visibility of TxGraph::determine_changeset
to be pub(crate), and the method accepts a TxGraph instead of &TxGraph

This commit removes:
- `TxGraph::insert_txout_preview`
- `TxGraph::insert_tx_preview`
- `insert_anchor_preview`
- `insert_seen_at_preview`

Solves #1022
2023-08-18 11:51:45 +02:00
Daniela Brozzoni
853d361751
Update bdk_chain to bitcoin 0.30.0 2023-08-03 10:58:59 +02:00
志宇
b206a985cf
fix: Even more refactoring to code and documentation
Thank you to @LLFourn and @danielabrozzoni for these suggestions.
2023-08-01 18:31:22 +08:00
志宇
95312d4d05
fix: docs and some minor refactoring
Shout out to @LLFourn for these suggestions.

* Improve/fix `LocalChain` documentation
* Refactor `TxGraph::missing_blocks` to make it more explicit that
  `last_block` has state.
* `update_local_chain` method of `EsploraExt` and `EsploraAsyncExt` now
  returns a `local_chain::Update` instead of just a `CheckPoint`.
2023-07-28 11:30:17 +08:00
志宇
eabeb6ccb1
Implement linked-list LocalChain and update chain-src crates/examples
This commit changes the `LocalChain` implementation to have blocks
stored as a linked-list. This allows the data-src thread to hold a
shared ref to a single checkpoint and have access to the whole history
of checkpoints without cloning or keeping a lock on `LocalChain`.

The APIs of `bdk::Wallet`, `esplora` and `electrum` are also updated to
reflect these changes. Note that the `esplora` crate is rewritten to
anchor txs in the confirmation block (using the esplora API's tx status
block_hash). This guarantees 100% consistency between anchor blocks and
their transactions (instead of anchoring txs to the latest tip).
`ExploraExt` now has separate methods for updating the `TxGraph` and
`LocalChain`.

A new method `TxGraph::missing_blocks` is introduced for finding
"floating anchors" of a `TxGraph` update (given a chain).

Additional changes:

* `test_local_chain.rs` is refactored to make test cases easier to
  write. Additional tests are also added.
* Examples are updated.
* Fix `tempfile` dev dependency of `bdk_file_store` to work with MSRV

Co-authored-by: LLFourn <lloyd.fourn@gmail.com>
2023-07-28 11:30:16 +08:00
Shourya742
ac80829caa
Rename fields of tx_graph::Additions
* Changed `tx` to `txs`
* Changed `txout` to `txouts`
2023-06-04 03:32:18 +08:00
志宇
1c3cbefa4d
[chain_redesign] Remove old structures
Other changes:

* The `async-https` feature of `bdk_esplora` is no longer default.
* Rename `ObservedAs` to `ChainPosition`.
* Set temporary MSRV to 1.60.0 to compile all workspace members will all
  features.
2023-06-04 03:32:18 +08:00
志宇
e01d17d59b
Improve txout listing and balance APIs for redesigned structures
Instead of relying on a `OwnedIndexer` trait to filter for relevant
txouts, we move the listing and balance methods from `IndexedTxGraph` to
`TxGraph` and add an additional input (list of relevant outpoints) to
these methods.

This provides a simpler implementation and a more flexible API.
2023-05-10 23:57:24 +08:00
志宇
065c64a675
[chain_redesign] Rename LocalChain::inner() to blocks()
Also, we can get rid of `LocalChain::get_blockhash`, since we can
already expose the internal map.

Additionally, tests and docs are improved.
2023-05-05 19:49:30 +08:00
志宇
a56d289eef
[chain_redesign] Various LocalChain improvements
* Introduce `LocalChain::inner` method to get the inner map of block
  height to hash.
* Replace `LocalChain::get_block` (which outputted `BlockId`, thus able
  to return invalid representation) with `get_blockhash` that just
returns a `BlockHash`.
* Remove `TODO` comments that should be github tickets.
2023-05-05 16:55:21 +08:00
志宇
2ccc116eda
[chain_redesign] BlockId should not implement Anchor
If `BlockId` implements `Anchor`, the meaning is ambiguous. We cannot
tell whether it means the tx is anchors at the block, or whether it also
means the tx is confirmed at that block.

Instead, `ConfirmationHeightAnchor` and `ConfirmationTimeAnchor` structs
are introduced as non-ambiguous `Anchor` implementations.

Additionally, `TxGraph::relevant_heights` is removed because it is also
ambiguous. What heights are deemed relevant? A simpler and more flexible
method `TxGraph::all_anchors` is introduced instead.
2023-05-05 16:38:29 +08:00
rajarshimaitra
29055658a6
Test cleanup and added documentation.
- Explainer doc added for the test.
- Test code simplified.
- One more edge cases added.
2023-04-29 17:27:12 +05:30
rajarshimaitra
b799a5728b
[bdk_chain_redesign] Add tests for IndexedTxGraph with LocalChain
These tests cover list_txout, list_utxo and balance methods.
2023-04-28 19:18:50 +08:00
志宇
1b152647c5
[bdk_chain_redesign] Change insert_relevant_txs method
Instead of forcing all transactions inserted to use the same anchors, we
change the API to have unique anchors per transaction.

This allows for more flexibility in general. For example, use `Anchor`
implementations that contain the position in a block of a transaction.
2023-04-23 00:21:31 +08:00
志宇
ac336aa32f
[bdk_chain_redesign] Make insert_relevant_txs topologically-agnostic
The `insert_relevant_txs` test has also been changed to used
`KeychainTxOutIndex` so that index additions can be checked
(`SpkTxOutIndex` has no additions).

Additionally, generic bounds of some `IndexedTxGraph` list methods have
been fixed.
2023-04-22 23:09:39 +08:00
志宇
165b874dfe
[bdk_chain_redesign] Add test for insert_relevant_txs
Ensure `insert_relevant_txs` does not require transactions to be in
topological order.

Other changes: Rm `try_list_owned_txs` as it is useless
2023-04-21 14:55:30 +08:00