Compare commits

...

1952 Commits

Author SHA1 Message Date
Steve Myers
785371e0a1
Merge bitcoindevkit/bdk#1530: chore: fix clippy lints
Some checks failed
Code Coverage / Code Coverage (push) Failing after 1m1s
CI / Build and test (--all-features, map[clippy:true version:stable]) (push) Failing after 7m39s
CI / Build and test (--all-features, map[version:1.63.0]) (push) Failing after 18m9s
CI / Build and test (--no-default-features, map[clippy:true version:stable]) (push) Failing after 8m41s
CI / Build and test (--no-default-features, map[version:1.63.0]) (push) Failing after 16m42s
CI / Check no_std (push) Successful in 1m37s
CI / Check WASM (push) Successful in 3m15s
CI / Rust fmt (push) Successful in 21s
CI / clippy_check (push) Failing after 16s
Publish Nightly Docs / Build docs (push) Failing after 7s
Publish Nightly Docs / Publish docs (push) Has been skipped
8bf8c7d080194872188e1ab7a6f14c06b121e371 chore: fix clippy lints (Jose Storopoli)

Pull request description:

  ### Description

  Fix some clippy CI lints

  ### Notes to the reviewers

  More caught by the Nix CI in #1320.

  ### Changelog notice

  chore: clippy lints

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 8bf8c7d080194872188e1ab7a6f14c06b121e371

Tree-SHA512: 6b53cb739e506d79106a2f42aa2b8fa28ef226543fbbf100225f10ed82257f6fd0218f09c0f1291803fbc9c1c88e32ba1c7e02fe3f601ccc9dc5be8a6efea6e1
2024-07-31 23:11:38 -05:00
Steve Myers
18626c66ac
Merge bitcoindevkit/bdk#1529: fix: typos
a8efeaa0fb83848a04e7324311ccaca4e2c4ab71 fix: typos (Jose Storopoli)

Pull request description:

  ### Description

  Needed for the typos nix check in #1320.

  ### Notes to the reviewers

  More typos that the Nix CI caught.

  ### Changelog notice

  - fix: typos

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK a8efeaa0fb83848a04e7324311ccaca4e2c4ab71

Tree-SHA512: 44a625bcf538acb7a766316f1d512ef3fd7cc14aae03f09b129229946ef156be35dff73dab3dc24fbc21137764b5707a2bd632bfb84b38dc9fe4d061659ac766
2024-07-31 22:55:15 -05:00
Jose Storopoli
8bf8c7d080
chore: fix clippy lints 2024-07-30 14:43:32 -03:00
Jose Storopoli
a8efeaa0fb
fix: typos
Needed for the typos nix check in #1320.
2024-07-30 13:35:23 -03:00
Steve Myers
82141a8201
Merge bitcoindevkit/bdk#1524: ci: pin tokio to 1.38.1 to support MSRV 1.63
28d75304e1319f49ab72c582f03a916ee40463dd ci: pin tokio to 1.38.1 to support MSRV 1.63 (Steve Myers)

Pull request description:

  ### Description

  The latest tokio minor version update from 1.38.1 to 1.39.1 changed it's MSRV from 1.63.0 to 1.70.0, breaking our CI MSRV 1.63 testing. This PR pins `tokio` back to 1.38.1 for our CI MSRV testing.

  ### Notes to the reviewers

  https://github.com/tokio-rs/tokio/pull/6645

  https://crates.io/crates/tokio/versions

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  LagginTimes:
    ACK 28d75304e1319f49ab72c582f03a916ee40463dd
  ValuedMammal:
    ACK 28d75304e1319f49ab72c582f03a916ee40463dd
  oleonardolima:
    ACK 28d75304e1319f49ab72c582f03a916ee40463dd

Tree-SHA512: 9eef750422cb8c3faa15771438e790afae44362d7c77e1d36cf70816ac7dabdd2e408e14502836ec86f845a2f1fe82905000c681fb6b4e873b036a41a280abd9
2024-07-27 08:17:37 -05:00
Steve Myers
28d75304e1
ci: pin tokio to 1.38.1 to support MSRV 1.63 2024-07-25 22:16:25 -05:00
Steve Myers
17a9850cba
Merge bitcoindevkit/bdk#1522: Bump bdk version to 1.0.0-beta.1
53bea0d902f49f8f01f164bddcbc21327e2c7032 Bump bdk version to 1.0.0-beta.1 (Steve Myers)

Pull request description:

  ### Description

  Bump bdk version to 1.0.0-beta.1

  bdk_chain to 0.17.0
  bdk_bitcoind_rpc to 0.13.0
  bdk_electrum to 0.16.0
  bdk_esplora to 0.16.0
  bdk_file_store to 0.14.0
  bdk_testenv to 0.7.0
  bdk_hwi to 0.4.0

  ### Notes to the reviewers

  This release completes the 1.0.0-alpha milestone and starts our new 1.0.0-beta milestone series of releases.

  The beta releases will maintain a stable `bdk_wallet` API and be focused on improving testing, docs, CI, and fixing any newly discovered bugs.

ACKs for top commit:
  LLFourn:
    ACK 53bea0d902f49f8f01f164bddcbc21327e2c7032
  LagginTimes:
    ACK 53bea0d902f49f8f01f164bddcbc21327e2c7032
  storopoli:
    ACK 53bea0d902f49f8f01f164bddcbc21327e2c7032

Tree-SHA512: cc2adbdeb7c2786659198da64e96fcb374833666e8d98c3f255e2de5f7283573efe3e3c53fd0c7b0e475fe3ac30d3c88169075e079d4d0b67496fc9a962b39db
2024-07-22 09:13:42 -05:00
Steve Myers
53bea0d902
Bump bdk version to 1.0.0-beta.1
bdk_chain to 0.17.0
bdk_bitcoind_rpc to 0.13.0
bdk_electrum to 0.16.0
bdk_esplora to 0.16.0
bdk_file_store to 0.14.0
bdk_testenv to 0.7.0
bdk_hwi to 0.4.0
2024-07-21 21:47:39 -05:00
Steve Myers
5478bb1ebb
Merge bitcoindevkit/bdk#1506: Standardize API ownership in KeychainTxOutIndex
79262185d556009c3d3e918f886ba4a51a262351 refactor(chain)!: update KeychainTxOutIndex methods to use owned ScriptBuf (Steve Myers)
7c07b9de02edf9f2c2b8a153f7bc4c0ca0823b02 refactor(chain)!: update KeychainTxOutIndex methods to use owned K (Rob N)

Pull request description:

  ### Description

  Make all method signatures of `KeychainTxOutIndex` take owned `K` and use `ScriptBuf` instead of its borrowed counterpart `&Script`. Fixes #1482

  ### Notes to the reviewers

  Steve also added a CI fix as well

  ### Changelog notice

  - Make all method signatures of `KeychainTxOutIndex` take owned `K`
  - Update `KeychainTxOutIndex` methods to use `ScriptBuf`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

Top commit has no ACKs.

Tree-SHA512: 3cb7d627ef6f38e1eaf6b88174f143c42dfc4d34e3d3d56cc843c256b2f32360fd00fa9ee328d0a41dac1f46771ccae797a96d9e3cee6f5ac4ef63e27cf6b7b7
2024-07-21 21:37:11 -05:00
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
Steve Myers
0c8ee1dfe2
Merge bitcoindevkit/bdk#1514: refactor(wallet)!: rework persistence, changeset, and construction
64eb5763487df3c6cbb626e51f96ab6e47c5de22 chore(wallet): Fix ChangeSet::merge (LLFourn)
8875c92ec114ba9ca0ea8402d65d7a236566b618 chore(wallet): Fix descriptor mismatch error keychain (LLFourn)
2cf07d686b19787b5e97e0d5ed0b4cce7f56549f refactor(chain,wallet)!: move rusqlite things into it's own file (志宇)
93f9b83e275e8ab67630c925a39de6c01611a01b chore(chain): rm unused `sqlite` types (志宇)
892b97d4416d9d38ebf3d7e0c52636f110042302 feat(chain,wallet)!: Change persist-traits to be "safer" (志宇)
3aed4cf1798d7bd0189de315f5d7eacf212edb40 test(wallet): ensure checks work when loading wallet (志宇)
af4ee0fa4b82ddafa10c6b7fc35a2532351cd003 refactor(wallet)!: Make `bdk_wallet::ChangeSet` non-exhaustive (志宇)
22d02ed3d19e763d1ff54e3ec3657ed39c4ad66c feat!: improve wallet building methods (志宇)
eb73f0659e0046f39f5bf6a07d4145a19f865794 refactor!: move `WalletChangeSet` to `bdk_wallet` and fix import paths (志宇)
6b43001951db7738f788bcdbb46c8c1cd3e24a66 feat!: Rework sqlite, changesets, persistence and wallet-construction (志宇)

Pull request description:

  Closes #1496
  Closes #1498
  Closes #1500

  ### Description

  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 available 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`.

  ### Notes to the reviewers

  TODO

  ### Changelog notice

  ```
  ### Added

  - Add `sqlite` feature to `bdk_chain` which introduces methods on changeset types that encode/decode changesets to SQLite database.
  * Introduce `PersistWith<Db>` and `PersistAsyncWith<Db>` traits and a `Persisted` wrapper. This ergonomically makes sure user inits the db before reading/writing to it.

  ### Changed

  - Moved `bdk_chain::CombinedChangeSet` to `bdk_wallet::ChangeSet` and added `keychain_added` field.
  - `bdk_wallet::Wallet` construction now uses a builder API using the newly introduced `CreateParams` and `LoadParams`.

  ### Removed

  - Remove `keychains_added` field from `bdk_chain::keychain_txout::ChangeSet`.

  ```
  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  LLFourn:
    ACK: 64eb5763487df3c6cbb626e51f96ab6e47c5de22
  notmandatory:
    Re ACK 64eb5763487df3c6cbb626e51f96ab6e47c5de22

Tree-SHA512: b8a1d48aea26d9fa293a8387a3533cd16c8ddae890f94d61fb91efa492fb05ac5e0a66200d64d7c857774368d5f0f8991a98684307029c25f50a1d8fceee8e67
2024-07-21 20:26:30 -05:00
LLFourn
64eb576348
chore(wallet): Fix ChangeSet::merge
h/t @ValuedMammal
2024-07-22 03:01:52 +10:00
LLFourn
8875c92ec1
chore(wallet): Fix descriptor mismatch error keychain 2024-07-22 02:57:00 +10:00
志宇
2cf07d686b
refactor(chain,wallet)!: move rusqlite things into it's own file
Also fix imports and rename `sqlite` module to `rusqlite_impl`.
2024-07-19 11:25:11 +00:00
志宇
93f9b83e27
chore(chain): rm unused sqlite types 2024-07-19 07:22:09 +00:00
志宇
892b97d441
feat(chain,wallet)!: Change persist-traits to be "safer"
Previously, `Persist{Async}With::persist` can be directly called as a
method on the type (i.e. `Wallet`). However, the `db: Db` (which is an
input) may not be initialized. We want a design which makes it harder
for the caller to make this mistake.

We change `Persist{Async}With::persist` to be an "associated function"
which takes two inputs: `db: &mut Db` and `changeset`. However, the
implementer cannot take directly from `Self` (as it's no longer an
input). So we introduce a new trait `Staged` which defines the staged
changeset type and a method that gives us a `&mut` of the staged
changes.
2024-07-19 07:05:38 +00:00
志宇
3aed4cf179
test(wallet): ensure checks work when loading wallet 2024-07-18 06:47:34 +00:00
志宇
af4ee0fa4b
refactor(wallet)!: Make bdk_wallet::ChangeSet non-exhaustive 2024-07-18 05:47:12 +00:00
志宇
22d02ed3d1
feat!: improve wallet building methods
Remove returning `Result` for builder methods on `CreateParams` and
`LoadParams`.
2024-07-18 04:16:05 +00:00
志宇
eb73f0659e
refactor!: move WalletChangeSet to bdk_wallet and fix import paths 2024-07-18 04:15:47 +00: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
Steve Myers
d99b3ef4b4
Merge bitcoindevkit/bdk#1489: feat(electrum)!: Update bdk_electrum to use merkle proofs
1a62488abfd6213c2780c1465aebe01dfbb6b20a feat(chain)!: Implement `ConfirmationBlockTime` (Wei Chen)
e761adf48178e2688a817a2b7466b0ebf7902eeb test(electrum): Imported `bdk_esplora` tests into `bdk_electrum` (Wei Chen)
d7f4ab71e22ca3e8868dae22add8839fc25aa7f3 feat(electrum)!: Update `bdk_electrum` to use merkle proofs (Wei Chen)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->
  Fixes #980.

  ### Description

  This PR is the first step in reworking `bdk_electrum` to use merkle proofs. When we fetch a transaction, we now also obtain the merkle proof and block header for verification. We then insert an anchor only after validation that the transaction exists in a confirmed block. The loop logic that previously existed in `full_scan` to account for re-orgs has also been removed as part of this rework.

  This is a breaking change because `graph_update`s now provide the full `ConfirmationTimeHeightAnchor` type. This removes the need for the `ElectrumFullScanResult` and `ElectrumSyncResult` structs that existed only to provide the option for converting the anchor type from `ConfirmationHeightAnchor` into `ConfirmationTimeHeightAnchor`.

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->
  * `ConfirmationTimeHeightAnchor` and `ConfirmationHeightAnchor` have been removed.
  * `ConfirmationBlockTime` has been introduced as a new anchor type.
  * `bdk_electrum`'s `full_scan` and `sync` now return `graph_update`s with `ConfirmationBlockTime`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  ValuedMammal:
    ACK 1a62488abfd6213c2780c1465aebe01dfbb6b20a
  notmandatory:
    ACK 1a62488abfd6213c2780c1465aebe01dfbb6b20a

Tree-SHA512: 77af05bffcb9668ecb99b41abacc6b6aa503dc559226fa88c4cab6863e3af431b937706696ec765bb802c9c152333cd430c284d17a6cd190520e10b13d89e02f
2024-07-09 14:29:21 -05: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
e761adf481
test(electrum): Imported bdk_esplora tests into bdk_electrum 2024-07-09 00:23:02 +08:00
Wei Chen
d7f4ab71e2
feat(electrum)!: Update bdk_electrum to use merkle proofs 2024-07-09 00:23:02 +08:00
Steve Myers
1a39821b88
Merge bitcoindevkit/bdk#1505: ci: pin cc dependency version to build with rust 1.63
3f9ed95e2e84ea1d938ecab406740d23cf25db1b ci: pin cc dependency version to build with rust 1.63 (Wei Chen)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->
  `cc` version 1.0.106 raised `msrv` to 1.67.
  The previous working version 1.0.105 was pinned for CI to continue working.

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->
  * Pinned cc dependency version to build with rust 1.63.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  storopoli:
    ACK 3f9ed95e2e84ea1d938ecab406740d23cf25db1b
  notmandatory:
    ACK 3f9ed95e2e84ea1d938ecab406740d23cf25db1b

Tree-SHA512: 995786f214c06db278daa07643489cdae557c14ffda4b873d2951ca6b52de64630e39dafcbc43cecaede0911fd6d137b992a868478d4bae674e73b4ecc18650b
2024-07-08 10:49:46 -05:00
Wei Chen
3f9ed95e2e
ci: pin cc dependency version to build with rust 1.63 2024-07-08 23:20:26 +08:00
Steve Myers
8714e9d806
Merge bitcoindevkit/bdk#1503: feat(wallet): simplify public_descriptor fn and remove `get_descriptor_for_keych…
e7ec5a873328c9b68836306086bd9b021e9c952a refactor(wallet)!: remove redundant get_descriptor_for_keychain (Giovanni Napoli)

Pull request description:

  Fixes #1501

  ### Description

  Simplifies `public_descriptor` function by using `get_descriptor` and removes `get_descriptor_for_keychain`.

  ### Notes to the reviewers

  Tested with `cargo test --all-features`.

  ### Changelog notice

  - Simplifies `public_descriptor` function and removes `get_descriptor_for_keychain`

  ### Checklists

  #### All Submissions:

  * [X] I've signed all my commits
  * [X] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [X] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK e7ec5a873328c9b68836306086bd9b021e9c952a
  storopoli:
    ACK e7ec5a8733

Tree-SHA512: 5981190ac882e08e42b1be53c55afb70c4ba7e7a99a8ae2a4e05f0618d0eb23849ce544024bb406e6a6918d9e9757d9ff6ad5a701cd9814b686e36f1ea16b44a
2024-07-08 09:21:58 -05:00
Steve Myers
43f093d918
Merge bitcoindevkit/bdk#1502: chore(chain)!: Rename Append to Merge
962305f41546613b5b41b4131d4a5594f01a2de0 chore(chain)!: Rename `Append` to `Merge` (Wei Chen)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->
  Fixes #1467.

  ### Description

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->
  Renames the `Append` trait to `Merge`.

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->
  * Rename `bdk_chain::Append` to `bdk_chain::Merge`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 962305f41546613b5b41b4131d4a5594f01a2de0

Tree-SHA512: 2019d9ed631776850cda39c9a53bdd3660c7f4715d8c418824d8ad13718f2b2fd160159e03fd63743dbf0b9e91cfdfed7e4cd4a591636f67d2aaec419486d136
2024-07-07 21:02:39 -05:00
Wei Chen
962305f415
chore(chain)!: Rename Append to Merge 2024-07-07 16:46:10 +08:00
Lloyd Fournier
db8fbd729d
Merge pull request #1493 from ValuedMammal/refactor/keychain-balance
[chain] Create module `indexer`
2024-07-06 22:37:02 +10:00
Giovanni Napoli
e7ec5a8733
refactor(wallet)!: remove redundant get_descriptor_for_keychain
Simplify Wallet::public_descriptor() and update Wallet internals to use
public_descriptor() instead of get_descriptor_for_keychain().
2024-07-06 13:39:49 +02:00
Steve Myers
139eec7da0
Merge bitcoindevkit/bdk#1487: Add support for custom sorting and deprecate BIP69
3bee563c810ace941e0e80ee8e410d843a05f5d8 refactor(wallet)!: remove TxOrdering::Bip69Lexicographic (nymius)
e5cb7b206619f5f3437e5ee95ed3e53885b745e6 feat(wallet): add TxOrdering::Custom (FadedCoder)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Resolves https://github.com/bitcoindevkit/bdk/issues/534.

  Resumes from the work in https://github.com/bitcoindevkit/bdk/pull/556.

  Add custom sorting function for inputs and outputs through `TxOrdering::Custom` and deprecates `TxOrdering::Bip69Lexicographic`.

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers

  I tried consider all discussions in https://github.com/bitcoindevkit/bdk/issues/534 while implementing some changes to the original PR. I created a summary of the considerations I had while implementing this:

  ##### Why use smart pointers?
  The size of enums and structs should be known at compilation time. A struct whose fields implements some kind of trait cannot be specified without using a smart pointer because the size of the implementations of the trait cannot be known beforehand.

  ##### Why `Arc` or `Rc` instead of `Box`?
  The majority of the useful smart pointers that I know (`Arc`, `Box`, `Rc`) for this case implement `Drop` which rules out the implementation of `Copy`, making harder to manipulate a simple enum like `TxOrdering`. `Clone` can be used instead, implemented by `Arc` and `Rc`, but not implemented by `Box`.

  #####  Why `Arc` instead of `Rc`?
  Multi threading I guess.

  ##### Why using a type alias like `TxVecSort`?
  cargo-clippy was accusing a too complex type if using the whole type inlined in the struct inside the enum.

  ##### Why `Fn` and not `FnMut`?
  `FnMut` is not allowed inside `Arc`. I think this is due to the `&mut self` ocupies the first parameter of the `call` method when desugared (https://rustyyato.github.io/rust/syntactic/sugar/2019/01/17/Closures-Magic-Functions.html), which doesn't respects `Arc` limitation of not having mutable references to data stored inside `Arc`:
  Quoting the [docs](https://doc.rust-lang.org/std/sync/struct.Arc.html):
  > you cannot generally obtain a mutable reference to something inside an `Arc`.

  `FnOnce` > `FnMut` > `Fn`, where `>` stands for "is supertrait of", so, `Fn` can be used everywhere `FnMut` is expected.

  ##### Why not `&'a dyn FnMut`?
  It needs to include a lifetime parameter in `TxOrdering`, which will force the addition of a lifetime parameter in `TxParams`, which will require the addition of a lifetime parameter in a lot of places more. **Which one is preferable?**

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice

  - Adds new `TxOrdering` variant: `TxOrdering::Custom`. A structure that stores the ordering functions to sort the inputs and outputs of a transaction.
  - Deprecates `TxOrdering::Bip69Lexicographic`.

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [ ] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [ ] I've added docs for the new feature

Top commit has no ACKs.

Tree-SHA512: 0d3e3ea9aee3a6c9e9d5e1ae93215be84bd1bd99907a319976517819aeda768a7166860a48a8d24abb30c516e0129decb6a6aebd8f24783ea2230143e6dcd72a
2024-07-05 15:31:03 -05:00
nymius
3bee563c81
refactor(wallet)!: remove TxOrdering::Bip69Lexicographic
BIP 69 proposed a deterministic way to sort transaction inputs and
outputs with the idea of enhancing privacy. It was later discovered
there was no such enhancement but rather a decrement in privacy due to
this sorting.
To avoid the promotion of bad practices, the
TxOrdering::Bip69Lexicographic variant which implemented this BIP for
BDK is removed with this change.
Notice that you can still produce a BIP 69 compliant transaction
defining order functions for TxOrdering::Custom.

Signed-off-by: Steve Myers <steve@notmandatory.org>
2024-07-05 15:03:08 -05:00
FadedCoder
e5cb7b2066
feat(wallet): add TxOrdering::Custom
The deterministic sorting of transaction inputs and outputs proposed in
BIP 69 doesn't improve the privacy of transactions as originally
intended. In the search of not spreading bad practices but still provide
flexibility for possible use cases depending on particular order of the
inputs/outpus of a transaction, a new TxOrdering variant has been added
to allow the implementation of these orders through the definition of
comparison functions.

Signed-off-by: Steve Myers <steve@notmandatory.org>
2024-07-05 15:03:05 -05:00
valued mammal
c3fc1dd123
ref(chain)!: create module indexer
and replace keychain module with `balance.rs`
2024-07-05 12:22:28 -04:00
Steve Myers
a112b4d97c
Merge bitcoindevkit/bdk#1416: [chain] Change tx_last_seen to Option<u64>
af75817d4bedbb5e148812d1073fd0729a23358b ref(tx_graph): Change last_seen to `HashMap<Txid, u64>` (valued mammal)
6204d2c766f968af6b63c664dda61fa8fc897e85 feat(tx_graph): Add method `txs_with_no_anchor_or_last_seen` (valued mammal)
496601b8b148afd2199a530d40edeafcb7967d46 test(tx_graph): Add test for `list_canonical_txs` (valued mammal)
c4057297a96ccbd49d984b7139994b801c2120dc wallet: delete method `insert_anchor` (valued mammal)
b34790c6b6d612661a4595bf10910294af862323 ref(tx_graph)!: Rename `list_chain_txs` to `list_canonical_txs` (valued mammal)
2ce4bb4dfc4f7b779a815eca45a3f6cee3d6c4e0 test(indexed_tx_graph): Add test_get_chain_position (valued mammal)
36f58870cb6eb24fe8c50ba4cf3ede910dd11fe8 test(wallet): Add test_insert_tx_balance_and_utxos (valued mammal)
bbc19c3536b25c78be8b5f3fe0cd9810aa679742 fix(tx_graph)!: Change tx_last_seen to `Option<u64>` (valued mammal)
324eeb3eb4e5231c6a81e6d197df788ad08b23a8 fix(wallet)!: Rework `Wallet::insert_tx` to no longer insert anchors (valued mammal)

Pull request description:

  The PR changes the type of last_seen to `Option<u64>` for `txs` member of `TxGraph`.

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

  fixes #1446
  fixes #1396

  ### Notes to the reviewers

  ### Changelog notice

  Changed
  - Member `last_seen_unconfirmed` of `TxNode` is changed to `Option<u64>`
  - Renamed `TxGraph` method `list_chain_txs` to `list_canonical_txs`
  - Changed `Wallet::insert_tx` to take a single `tx: Transaction` as parameter

  Added
  - Add method `txs_with_no_anchor_or_last_seen` for `TxGraph`
  - Add method `unbroadcast_transactions` for `Wallet`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    Re ACK af75817d4bedbb5e148812d1073fd0729a23358b

Tree-SHA512: e664b3b49e2f547873923f15dffbbc7fa032b6240e5b856b180e9e26123ca141864d10448912dc4a31bbb200c75bef4251a910a4330dac17ee6841b564612d13
2024-07-02 16:50:26 -05:00
valued mammal
af75817d4b
ref(tx_graph): Change last_seen to HashMap<Txid, u64> 2024-06-30 11:26:15 -04:00
valued mammal
6204d2c766
feat(tx_graph): Add method txs_with_no_anchor_or_last_seen 2024-06-30 10:08:54 -04:00
valued mammal
496601b8b1
test(tx_graph): Add test for list_canonical_txs 2024-06-30 10:08:54 -04:00
valued mammal
c4057297a9
wallet: delete method insert_anchor 2024-06-30 10:08:54 -04:00
valued mammal
b34790c6b6
ref(tx_graph)!: Rename list_chain_txs to list_canonical_txs 2024-06-30 10:08:54 -04:00
valued mammal
2ce4bb4dfc
test(indexed_tx_graph): Add test_get_chain_position 2024-06-30 10:08:54 -04:00
valued mammal
36f58870cb
test(wallet): Add test_insert_tx_balance_and_utxos 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
Steve Myers
22368ab7b0
Merge bitcoindevkit/bdk#1486: refactor(chain): calculate DescriptorId as the sha256 hash of the spk at index 0
8f5b172e59b4d5e199b98777855b0d9b46742f66 test(wallet): verify wallet panics in dev mode if using keychains with duplicate spks (Steve Myers)
46c6f18cc3ff71efda2b8547aa32854f9b88762e refactor(chain): calculate DescriptorId as sha256 hash of spk at index 0 (Steve Myers)

Pull request description:

  ### Description

  Rename `DescriptorId` to `KeychainId` and `descriptor_id()` to `keychain_id()`.

  Calculate keychain ids as the hash of the spk derived from its descriptor as index 0.

  Added docs to `Wallet` and `KeychainTxOutIndex::insert_descriptor()` explaining that it's the users responsibility not to use wildcard and non-wildcard descriptors that can derive the same script pubkey. I also recommended for `Wallet` that legacy non-wildcard descriptors be added to a temporary `Wallet` and swept into a modern wildcard descriptor.

  ### Notes to the reviewers

  fixes #1483

  ### Changelog notice

  changed

  - Renamed DescriptorId to KeychainId, DescriptorExt::descriptor_id() to keychain_id().

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  LLFourn:
    ACK 8f5b172e59b4d5e199b98777855b0d9b46742f66
  oleonardolima:
    Concept ACK 8f5b172e59b4d5e199b98777855b0d9b46742f66

Tree-SHA512: 07defa208d9cfcd61bc6e31ded06a287c392c51bcc4949f601ecfac635c3443e7d08c62d92618ed894dc5ef13cdcf784771a6bf8904a5397110bedb1563f52d4
2024-06-28 17:38:11 -05:00
Steve Myers
d75d9f94ce
Merge bitcoindevkit/bdk#1490: Remove usage of blockdata:: from bitcoin paths
cf7aca84d113e639441350651112e9e701364497 Remove usage of blockdata:: from bitcoin paths (Tobin C. Harding)

Pull request description:

  ### Description

  In `rust-bitcoin` the `blockdata` module is a code organisation thing, it should never have been public. One day those guys would like to remove it, so as not to be a PITA for `bdk` when they do lets remove all usage of `blockdata::` now.

  ### Changelog notice

  Internal change only, no externally visible changes.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: 4c5e54a2ac3f71835c25ce97ad0acd1859e5ae8d45ebfde087e19e9494754e0aa70a47ca5f3d6a3b509f27e28ef9d4a5269573c686250f43834d09378155681c
2024-06-28 16:41:06 -05:00
Steve Myers
8f5b172e59
test(wallet): verify wallet panics in dev mode if using keychains with duplicate spks 2024-06-27 07:56:09 -05:00
Steve Myers
46c6f18cc3
refactor(chain): calculate DescriptorId as sha256 hash of spk at index 0
Also update docs to explain how KeychainTxOutIndex handles descriptors that
generate the same spks.
2024-06-27 07:56:08 -05:00
Tobin C. Harding
cf7aca84d1
Remove usage of blockdata:: from bitcoin paths
In `rust-bitcoin` the `blockdata` module is a code organisation thing,
it should never have been public. One day those guys would like to
remove it, so as not to be a PITA for `bdk` when they do lets remove all
usage of `blockdata::` now.

Internal change only, no externally visible changes.
2024-06-27 10:27:54 +10:00
Steve Myers
5c7cc30978
Merge bitcoindevkit/bdk#1468: feat: use Weight type instead of usize
438cd4682d14b5f4c6c9c653c9f05ccaaecb815d refactor(wallet)!: change WeightedUtxo to use Weight type (Leonardo Lima)

Pull request description:

  fixes #1466
  depends on #1448
  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  This PR is a follow-up on top of #1448, and should be rebased and merged after it, it uses the rust-bitcoin `Weight` type instead of the current `usize` usage.

  NOTE: ~~It also adds a new `MiniscriptError` variant, and remove the `.unwrap()` usage.~~ As suggested I'll address this on another issue #1485, trying to reproduce the error first.

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers
  It should be ready to review after #1448 gets merged.
  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice
  - Change `WeightedUtxo` `satisfaction_weight` has been changed to use `Weight` type.
  - Change `TxBuilder` methods `add_foreign_utxo` and `add_foreign_utxo_with_sequence` to expect `Weight` as `satisfaction_weight` type.

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  storopoli:
    Anyways, ACK 438cd4682d14b5f4c6c9c653c9f05ccaaecb815d
  notmandatory:
    ACK 438cd4682d14b5f4c6c9c653c9f05ccaaecb815d

Tree-SHA512: 1998fe659833da890ce07aa746572ae24d035e636732c1a11b7828ffed48e753adb4108f42d00b7cd05e6f45831a7a9840faa26f94058fc13760497837af002f
2024-06-26 17:51:23 -05:00
Leonardo Lima
438cd4682d
refactor(wallet)!: change WeightedUtxo to use Weight type 2024-06-26 09:09:23 -03:00
Steve Myers
275e069cf4
Merge bitcoindevkit/bdk#1424: Remove trait ComputeSighash
55a17293a455435c868f60f0c9f06ba80f2f0e4c ref(signer): Use `Psbt::sighash_ecdsa` for computing sighashes (valued mammal)
f2a2dae84cd04df4301f91745efa137975eeb8e4 refactor(signer): Remove trait ComputeSighash (valued mammal)

Pull request description:

  This PR does some cleanup of the `bdk_wallet` signer module most notably by removing the internal trait `ComputeSighash` and replacing old code for computing the sighash (for legacy and segwit context) with a single method [`Psbt::sighash_ecdsa`](https://docs.rs/bitcoin/0.31.2/bitcoin/psbt/struct.Psbt.html#method.sighash_ecdsa). The logic for computing the taproot sighash is unchanged and extracted to a new helper function `compute_tap_sighash`.

  - [x] Unimplement `ComputeSighash`
  - [x] Try de-duplicating code by using `Psbt::sighash_ecdsa`. see https://github.com/bitcoindevkit/bdk/pull/1023#discussion_r1263140218
  - Not done in this PR: Consider removing unused `SignerError` variants

  fixes #1038

  ### Notes to the reviewers

  ### Changelog notice

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: 56af3c9c463513ca3bae5480aa5b90d78de119c3c09c824a7220eb6832d5f403b172afc8168228918ea1adabb4bf8fca858790adfebf84fc334b4fc1cc99d3cd
2024-06-25 14:23:17 -05:00
valued mammal
55a17293a4
ref(signer): Use Psbt::sighash_ecdsa for computing sighashes
- Change param `hash` to `&Message` in `sign_psbt_ecdsa`
- Remove unused methods `compute_legacy_sighash`,
and `compute_segwitv0_sighash`.
- Match on `self.ctx` when signing for `SignerWrapper<PrivateKey>`
2024-06-24 09:06:32 -04:00
valued mammal
f2a2dae84c
refactor(signer): Remove trait ComputeSighash 2024-06-24 09:04:57 -04:00
valued mammal
324eeb3eb4
fix(wallet)!: Rework Wallet::insert_tx to no longer insert anchors
since we'd be lacking context that should normally occur during
sync with a chain source. The logic for inserting a graph
anchor from a `ConfirmationTime` is moved to the wallet common
test module in order to simulate receiving new txs and
confirming them.
2024-06-23 13:15:23 -04:00
Steve Myers
6dab68d35b
Merge bitcoindevkit/bdk#1395: Remove rand dependency from bdk
4bddb0de6262fb4014d51baf8c9453eb45a3d0ef feat(wallet): add back TxBuilder finish() and sort_tx() with thread_rng() (Steve Myers)
45c0cae0a461232bf746375083e2005c5df5f913 fix(bdk): remove rand dependency (rustaceanrob)

Pull request description:

  ### Description

  WIP towards removing `rand` fixes #871

  The `rand` dependency was imported explicitly, but `rand` is also implicitly used through the `rand-std` feature flag on `bitcoin`.

  ### Notes to he reviewers

  **Updated:**

  `rand` was used primarily in two parts of `bdk`. Particularly in signing and in building a transaction.

  Signing:
  - Used implicitly in [`sign_schnorr`](https://docs.rs/bitcoin/latest/bitcoin/key/struct.Secp256k1.html#method.sign_schnorr), but nowhere else within `signer`.

  Transaction ordering:
  - Used to shuffle the inputs and outputs of a transaction, the default
  - Used in the single random draw __as a fallback__ to branch and bound during coin selection. Branch and bound is the default coin selection option.

  See conversation for proposed solutions.

  ### Changelog notice

  - Remove the `rand` dependency from `bdk`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  ValuedMammal:
    ACK 4bddb0de6262fb4014d51baf8c9453eb45a3d0ef
  notmandatory:
    ACK 4bddb0de6262fb4014d51baf8c9453eb45a3d0ef

Tree-SHA512: 662d9bcb1e02f8195d73df16789b8c2aba8ccd7b37ba713ebb0bfd19c66163acbcb6f266b64f88347cbb1f96b88c8a150581012cbf818d1dc8b4437b3e53fc62
2024-06-22 21:28:37 -05:00
志宇
e406675f43
Merge bitcoindevkit/bdk#1476: fix(wallet)!: Simplify SignOptions and improve finalization logic
996605f2bf9440dd42647123a127c038253f0247 fix(wallet)!: Simplify `SignOptions` and improve finalization logic (valued mammal)

Pull request description:

  Rather than comingle various `SignOptions` with the finalization step, we simply clear all fields when finalizing as per the PSBT spec in BIPs 174 and 371 which is more in line with user expectations.

  ### Notes to the reviewers

  I chose to re-implement some parts of [`finalize_input`](https://docs.rs/miniscript/latest/src/miniscript/psbt/finalizer.rs.html#434) since it's fairly straightforward, see also https://github.com/bitcoindevkit/bdk/issues/1461#issuecomment-2171983426. I had to refactor some wallet tests but didn't go out of my way to add additional tests.

  closes #1461

  ### Changelog notice

  - Removed field `remove_partial_sigs` from `SignOptions`
  - Removed field `remove_taproot_extras` from `SignOptions`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    re-ACK 996605f2bf9440dd42647123a127c038253f0247

Tree-SHA512: 63e78e75c22031424e87fcc26cd6b0015c626cd57c02680256bad9d1783cef71f4048b2d7ce5d0425cd4239351e37dd0e2a626dda7e8417af7fc52cb0afe6933
2024-06-20 12:41:04 +08:00
Steve Myers
4bddb0de62
feat(wallet): add back TxBuilder finish() and sort_tx() with thread_rng() 2024-06-19 13:56:06 -10:00
valued mammal
996605f2bf
fix(wallet)!: Simplify SignOptions and improve finalization logic
Rather than comingle various `SignOptions` with the finalization
step, we simply clear all fields when finalizing as per the PSBT
spec in BIPs 174 and 371 which is more in line with user
expectations.
2024-06-19 12:02:15 -04:00
rustaceanrob
45c0cae0a4
fix(bdk): remove rand dependency 2024-06-17 15:27:58 -10:00
Steve Myers
0543801787
Merge bitcoindevkit/bdk#1472: Bump bdk version to 1.0.0-alpha.13
e21affdbbb9308bd6be38218ae5a26d9c800efe2 Bump bdk version to 1.0.0-alpha.13 (Steve Myers)

Pull request description:

  ### Description

  Bump bdk version to 1.0.0-alpha.13

  bdk_chain to 0.16.0
  bdk_bitcoind_rpc to 0.12.0
  bdk_electrum to 0.15.0
  bdk_esplora to 0.15.0
  bdk_file_store to 0.13.0
  bdk_sqlite keep at 0.2.0
  bdk_testenv to 0.6.0
  bdk_hwi to 0.3.0

  fixes #1471

Top commit has no ACKs.

Tree-SHA512: 987adf5084dc84261fb3767d8b1f8ebe3dd94a8a4eb30b8529b70c055e4f122cb48063d205e90831169c2d7b2a1509aef1966857bd6b67e78cfb0d52144822d9
2024-06-14 21:44:02 -05:00
Steve Myers
e21affdbbb
Bump bdk version to 1.0.0-alpha.13
bdk_chain to 0.16.0
bdk_bitcoind_rpc to 0.12.0
bdk_electrum to 0.15.0
bdk_esplora to 0.15.0
bdk_file_store to 0.13.0
bdk_sqlite keep at 0.2.0
bdk_testenv to 0.6.0
bdk_hwi to 0.3.0
2024-06-14 21:24:55 -05:00
Steve Myers
410ba173e4
Merge bitcoindevkit/bdk#1473: Remove persist submodule
a0bf45bef1b53f8aec273f7fe89915f3d41974c0 docs: remove PersistBackend from docs, Cargo.toml and wallet README.md (Steve Myers)
feb27df180938759670afd2c9cd15529a22c4772 feat(chain)!: add `take` convenience method to `Append` trait (志宇)
1eca568be5bb0c234fa1cea2eb7f9424f60974eb feat!: rm `persist` submodule (志宇)

Pull request description:

  ### Description

  @LLFourn suggested these changes which greatly simplifies the amount of code we have to maintain and removes the `async-trait` dependency. We remove `PersistBackend`, `PersistBackendAsync`, `StageExt` and `StageExtAsync` completely. Instead, we introduce `Wallet::take_staged(&mut self) -> Option<ChangeSet>`.

  The original intention to keep a staging area (`StageExt`, `StageExtAsync`) is to enforce:
  1. The caller will not persist an empty changeset.
  2. The caller does not take the staged changeset if the database (`PersistBackend`) fails.

  We achieve `1.` by returning `None` if the staged changeset is empty.

  `2.` is not too important. The caller can try figure out what to do with the changeset if persisting to db fails.

  ### Notes to the reviewers

  I added a `take` convenience method to the `Append` trait. I thought it would be handy for the caller to do a staging area with this.

  ### Changelog notice

  * Remove `persist` submodule from `bdk_chain`.
  * Change `Wallet` to outsource it's persistence logic by introducing `Wallet::take_staged`.
  * Add `take` convenience method to `Append` trait.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  ~* [ ] I've added tests for the new feature~
  * [x] I've added docs for the new feature

ACKs for top commit:
  notmandatory:
    ACK a0bf45bef1b53f8aec273f7fe89915f3d41974c0
  evanlinjin:
    self-ACK a0bf45bef1b53f8aec273f7fe89915f3d41974c0

Tree-SHA512: 38939ab446c84d9baecd4cd36a7b66add5a121212ad5e06ade04a60f7903133dd9a20219e230ab8a40404c47e07b946ccd43085572d71c3a2a80240a2223a500
2024-06-14 21:14:28 -05:00
Steve Myers
a0bf45bef1
docs: remove PersistBackend from docs, Cargo.toml and wallet README.md 2024-06-14 18:16:14 -05:00
志宇
feb27df180
feat(chain)!: add take convenience method to Append trait
This is useful if the caller wishes to use the type as a staging area.

This is breaking as `Append` has a `Default` bound now.
2024-06-15 00:52:23 +08:00
志宇
1eca568be5
feat!: rm persist submodule
Remove `PersistBackend`, `PersistBackendAsync`, `StageExt` and
`StageExtAsync`. Remove `async` feature flag and dependency. Update
examples and wallet.
2024-06-15 00:52:23 +08:00
Steve Myers
bc420923c2
Merge bitcoindevkit/bdk#1458: fix: typo on SignedAmount instead of Amount
20341a3ca1ab85ad77e022b5028136a635c3f42c fix: typo on `SignedAmount` instead of `Amount` (Leonardo Lima)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  It fixes the typo on the `expect()` message introduced on #1426, noticed at https://github.com/bitcoindevkit/bdk/pull/1426#discussion_r1626761825

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  storopoli:
    ACK 20341a3ca1ab85ad77e022b5028136a635c3f42c
  notmandatory:
    ACK 20341a3ca1ab85ad77e022b5028136a635c3f42c

Tree-SHA512: 62deb7308b2a6891eeb4598ebdf3c5ee1541fc52fd454bca2816b819bd7f6ab25c18e10c4166c80c4e553bcb3ce2207323376d260484a956837ac857854cbd6b
2024-06-14 10:38:30 -05:00
Steve Myers
782eb56bd4
Merge bitcoindevkit/bdk#1454: Refactor wallet and persist mod, remove bdk_persist crate
ec36c7eccacc8347568b77ed1dfc0c50a2524906 feat(example): use changeset staging with rpc polling example (志宇)
19328d4999c19557778b7b108f88f42b1258957e feat(wallet)!: change persist API to use `StageExt` and `StageExtAsync` (志宇)
2e40b0118cc88539f38420e347eb4d562b1be0b1 feat(chain): reintroduce a way to stage changesets before persisting (志宇)
36e82ec6869c5c5c5669d4d049636225f9a8e986 chore(chain): relax `miniscript` feature flag scope (志宇)
9e97ac03307f3194e043ef430e4bde2e5c25254c refactor(persist): update file_store, sqlite, wallet to use bdk_chain::persist (Steve Myers)
54b0c11cbe1d08eb955e50f0ac719a0b19e3032a feat(persist): add PersistAsync trait and StagedPersistAsync struct (Steve Myers)
aa640ab2770bea19259eedea6882b202a5845f35 refactor(persist): rename PersistBackend to Persist, move to chain crate (Steve Myers)

Pull request description:

  ### Description

  Sorry to submit another refactor PR for the persist related stuff, but I think it's worth revisiting. My primary motivations are:

  1. remove `db` from `Wallet` so users have the ability to use `async` storage crates, for example using `sqlx`. I updated docs and examples to let users know they are responsible for persisting changes.
  2. remove the `anyhow` dependency everywhere (except as a dev test dependency). It really doesn't belong in a lib and by removing persistence from `Wallet` it isn't needed.
  3. remove the `bdk_persist` crate and revert back to the original design with generic error types. I kept the `Debug` and `Display` constrains on persist errors so they could still be used with the `anyhow!` macro.

  ### Notes to the reviewers

  I also replaced/renamed old `Persist` with `StagedPersist` struct inspired by #1453, it is only used in examples. The `Wallet` handles it's own staging.

  ### Changelog notice

  Changed

  - Removed `db` from `Wallet`, users are now responsible for persisting changes, see docs and examples.
  - Removed the `bdk_persist` crate and moved logic back to `bdk_chain::persist` module.
  - Renamed `PersistBackend` trait to `Persist`
  - Replaced `Persist` struct with `StagedPersist`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  ValuedMammal:
    ACK ec36c7eccacc8347568b77ed1dfc0c50a2524906

Tree-SHA512: 380b94ae42411ea174720b7c185493c640425f551742f25576a6259a51c1037b441a238c6043f4fdfbf1490aa15f948a34139f1850d0c18d285110f6a9f36018
2024-06-13 17:52:54 -05:00
志宇
ec36c7ecca
feat(example): use changeset staging with rpc polling example 2024-06-13 12:58:39 -05:00
志宇
19328d4999
feat(wallet)!: change persist API to use StageExt and StageExtAsync 2024-06-13 12:58:35 -05:00
志宇
2e40b0118c
feat(chain): reintroduce a way to stage changesets before persisting
A staging area is helpful because we can contain logic to ignore empty
changesets and not clear staging area if the persistence backend fails.
2024-06-13 12:56:31 -05:00
志宇
36e82ec686
chore(chain): relax miniscript feature flag scope
Still enable the `persist` submodule without `miniscript` feature flag.
Only disable `CombinedChangeSet`.

Also stop `cargo clippy` from complaining about unused imports when
`miniscript` is disabled.
2024-06-13 12:56:30 -05:00
Steve Myers
9e97ac0330
refactor(persist): update file_store, sqlite, wallet to use bdk_chain::persist
Also update examples and remove bdk_persist crate.
2024-06-13 12:56:25 -05:00
Steve Myers
54b0c11cbe
feat(persist): add PersistAsync trait and StagedPersistAsync struct 2024-06-13 12:40:50 -05:00
Steve Myers
aa640ab277
refactor(persist): rename PersistBackend to Persist, move to chain crate
Also add refactored StagedPersist to chain crate with tests.
2024-06-13 12:40:49 -05:00
志宇
1c593a34ee
Merge bitcoindevkit/bdk#1463: No descriptor ids in spk txout index
8dd174479f9719309663ed979a5b4b86aca0a6e9 refactor(chain): compute txid once for `KeychainTxOutIndex::index_tx` (志宇)
639d735ca0ae54d8b2c3bc28241032154b94d45e refactor(chain): change field names to be more sane (志宇)
5a02f40122f1bfa06c80bac93f68f5799225d133 docs(chain): fix docs (志宇)
c77e12bae7f465ec7fb08b8be16d99793c757cf0 refactor(chain): `KeychainTxOutIndex` use `HashMap` for fields (志宇)
4d3846abf4f59b4a97bb825281655a6b67275603 chore(chain): s/replenish_lookahead/replenish_inner_index/ (LLFourn)
8779afdb0bf4e9b1004f47f86a770d25938d206d chore(chain): document insert_descriptor invariants better (LLFourn)
69f2a695f7dc25478489080598fea0813ea7d93d refactor(chain): improve replenish lookeahd internals (LLFourn)
5a584d0fd8c138757a10c7af93ec9e09523317e1 chore(chain): Fix Indexed and KeychainIndexed documentaion (Lloyd Fournier)
b8ba5a02066fad7ab2ce276ba071385cd1dbbe3a chore(chain): Improve documentation of keychain::ChangeSet (LLFourn)
101a09a97fa5e8d675c13396b9a800665b1b6c22 chore(chain): Standardise KeychainTxOutIndex return types (LLFourn)
bce070b1d662db7ac120e1d236fdda51842ad738 chore(chain): add type IndexSpk, fix clippy type complexity warning (Steve Myers)
4d2442c37f5c1bd822795271a79676d1ffbe7916 chore(chain): misc docs and insert_descriptor fixes (LLFourn)
bc2a8be97919f0d09b61438527bda24796bcec94 refactor(keychain): Fix KeychainTxOutIndex range queries (LLFourn)
3b2ff0cc953204c9925ace8e2f0bbef409c63ad5 Write failing test for keychain range querying (LLFourn)

Pull request description:

  Fixes #1459

  This reverts part of the changes in #1203. There the `SpkTxOutIndex<(K,u32)>` was changed to `SpkTxOutIndex<(DescriptorId, u32>)`. This led to a complicated translation logic in  `KeychainTxOutIndex` (where the API is based on `K`) to transform calls to it to calls to the underlying `SpkTxOutIndex` (which now indexes by `DescriptorId`). The translation layer was broken when it came to translating range queries from the `KeychainTxOutIndex`. My solution was just to revert this part of the change and remove the need for a translation layer (almost) altogether. A thin translation layer remains to ensure that un-revealed spks are filtered out before being returned from the `KeychainTxOutIndex` methods.

  I feel like this PR could be extended to include a bunch of ergonomics improvements that are easier to implement now. But I think that's the point of https://github.com/bitcoindevkit/bdk/pull/1451 so I held off and should probably go and scope creep that one instead.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK 8dd174479f9719309663ed979a5b4b86aca0a6e9

Tree-SHA512: 283e6b6d4218902298e2e848fe847a6c85e27af4eee3e4337e3dad6eacf9beaa08ac99b1dce7b6fb199ca53931e543ea365728a81c41567a2e510cce77b12ac0
2024-06-13 23:11:02 +08:00
志宇
8dd174479f
refactor(chain): compute txid once for KeychainTxOutIndex::index_tx 2024-06-13 23:03:34 +08:00
志宇
639d735ca0
refactor(chain): change field names to be more sane 2024-06-13 22:52:47 +08:00
志宇
5a02f40122
docs(chain): fix docs 2024-06-13 22:52:47 +08:00
志宇
c77e12bae7
refactor(chain): KeychainTxOutIndex use HashMap for fields
Instead of `BTreeMap` which is less performant.
2024-06-13 22:52:47 +08:00
LLFourn
4d3846abf4
chore(chain): s/replenish_lookahead/replenish_inner_index/ 2024-06-13 22:52:46 +08:00
LLFourn
8779afdb0b
chore(chain): document insert_descriptor invariants better 2024-06-13 22:52:46 +08:00
LLFourn
69f2a695f7
refactor(chain): improve replenish lookeahd internals
see: 4eb1e288a9 (r1630943639)
2024-06-13 22:52:45 +08:00
Lloyd Fournier
5a584d0fd8
chore(chain): Fix Indexed and KeychainIndexed documentaion
Co-authored-by: ValuedMammal <valuedmammal@protonmail.com>
2024-06-13 22:52:45 +08:00
LLFourn
b8ba5a0206
chore(chain): Improve documentation of keychain::ChangeSet 2024-06-13 22:52:45 +08:00
LLFourn
101a09a97f
chore(chain): Standardise KeychainTxOutIndex return types
The previous commit b9c5b9d08b040faf6c6b2d9b3745918031555b72 added
IndexSpk. This goes further and adds `Indexed` and `KeychainIndexed`
type alises (IndexSpk is Indexed<ScriptBuf>) and attempts to standardize
the structure of return types more generally.
2024-06-13 22:52:44 +08:00
Steve Myers
bce070b1d6
chore(chain): add type IndexSpk, fix clippy type complexity warning 2024-06-13 22:52:44 +08: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
LLFourn
3b2ff0cc95
Write failing test for keychain range querying 2024-06-13 22:52:42 +08:00
Steve Myers
3b040a7ee6
Merge bitcoindevkit/bdk#1448: bump(deps): upgrade rust bitcoin to 0.32.0, miniscript to 0.12.0 and others
11200810d048abb8deb3c7961ca93c68011d41fd chore(wallet): rm dup code (志宇)
2a4564097bd70905ed9fa21b92cdf074a72f878e deps(bdk): bump `bitcoin` to `0.32.0`, miniscript to `12.0.0` (Leonardo Lima)

Pull request description:

  fixes #1422
  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  This PR focuses on upgrading the `rust-bitcoin` and `miniscript` versions, to `0.32.0` and `0.12.0`, respectively. It also bumps the versions of other BDK ecosystem crates that also rely on both `rust-bitcoin` and `miniscript`, being:

  - electrum-client https://github.com/bitcoindevkit/rust-electrum-client/pull/133
  - esplora-client https://github.com/bitcoindevkit/rust-esplora-client/pull/85
  - hwi https://github.com/bitcoindevkit/rust-hwi/pull/99

  <ins>I structured the PR in multiple commits, with closed scope, being one for each BDK crate being upgraded, and one for each kind of fix and upgrade required, it seems like a lot of commits (**that should be squashed before merging**), but I think it'll make it easier during review phase.</ins>

  In summary I can already mention some of the main changes:
  - using `compute_txid()` instead of deprecated `txid()`
  - using `minimal_non_dust()` instead of `dust_value()`
  - using the renamed `signature` and `sighash_type` fields
  - using proper `sighash::P2wpkhError`,  `sighash::TaprootError` instead of older `sighash::Error`
  - conversion from `Network` to new expected `NetworkKind` #1465
  - conversion from the new `Weight` type to current expected `usize` #1466
  - using `.into()` to convert from AbsLockTime and `RelLockTime` to `absolute::LockTime` and `relative::LockTime`
  - using Message::from_digest() instead of relying on deprecated `ThirtyTwoByteHash` trait.
  - updating the miniscript policy and dsl to proper expect and handle new `Threshold` type, instead of the previous two parameters.

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers
  <ins>Again, I structured the PR in multiple commits, with closed scope, being one for each BDK crate being upgraded, and one for each kind of fix and upgrade required, it seems like a lot of commits (**that should be squashed before merging**), but I think it'll make it easier during review phase.</ins>

  It should definitely be carefully reviewed, especially the last commits for the wallet crate scope, the ones with the semantic `fix(wallet)`.

  I would also appreciate if @tcharding reviewed it, as he gave a try in the past (#1400 ), and I relied on some of it for the  policy part of it, other rust-bitcoin maintainers reviews are a definitely welcome 😁

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice
  > // TODO(@oleonardolima): Do another pass and double check the changes
  - Use `compute_txid()` instead of deprecated `txid()`
  - Use `minimal_non_dust()` instead of `dust_value()`
  - Use `signature` and `sighash_type` fields, instead of previous `sig` and `hash_type`
  - Use `sighash::P2wpkhError`,  and `sighash::TaprootError` instead of older `sighash::Error`
  - Converts from `Network` to `NetworkKind`, where expected
  - Converts from `Weight` type to current used `usize`
  - Use `.into()` to convert from `AbsLockTime` and `RelLockTime` to `absolute::LockTime` and `relative::LockTime`
  - Remove use of  deprecated `ThirtyTwoByteHash` trait, use `Message::from_digest()`
  - Update the miniscript policy and dsl macros to proper expect and handle new `Threshold` type, instead of the previous two parameters.

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 11200810d048abb8deb3c7961ca93c68011d41fd

Tree-SHA512: ba1ab64603b41014d3f0866d846167f77d31959ca6f1d9c3181d5e543964f5d772e05651d63935ba7bbffeba41a66868d27de4c32129739b9ca50f3bbaf9f2a1
2024-06-12 23:12:28 -05:00
志宇
11200810d0
chore(wallet): rm dup code
Methods `make_multi` and `make_multi_a` were essentially the same thing
except for a different const generic param on `Threshold`. So we rm
`make_multi_a` and put a const generic param on `make_multi`.
2024-06-13 11:47:01 +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
Lloyd Fournier
473ef9714f
Merge pull request #1470 from notmandatory/ci/pin_url_dep
ci: pin url dependency version to build with rust 1.63
2024-06-12 10:36:54 +10:00
Steve Myers
25b914ba0a
ci: pin url dependency version to build with rust 1.63 2024-06-11 18:43:07 -05:00
志宇
b4a847f801
Merge bitcoindevkit/bdk#1441: Remove duplicated InsufficientFunds error member
29c8a00b435bdf2fa1d7c707ad09c1a47edc07b3 chore(wallet): remove duplicated InsufficientFunds error member from CreateTxError (e1a0a0ea)

Pull request description:

  closes #1440

  ### Description

  - Replace `CreateTxError::InsufficientFunds` use by `coin_selection::Error::InsufficientFunds`
  - Remove `InsufficientFunds` member from `CreateTxError` enum
  - Rename `coin_selection::Error` to `coin_selection::CoinSelectionError`

  ### Notes to the reviewers

  - We could also keep both members but rename one of them to avoid confusion

  ### Checklists

  #### All Submissions:

  * [X] I've signed all my commits
  * [X] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [X] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 29c8a00b435bdf2fa1d7c707ad09c1a47edc07b3
  notmandatory:
    ACK 29c8a00b435bdf2fa1d7c707ad09c1a47edc07b3

Tree-SHA512: a1132d09929f99f0a5e82d3ccfaa85695ae50d7d4d5d9e8fd9ef847313918ed8c7a01005f45483fef6aeae36730a0da2fed9a9f10c3ce2f0a679527caf798bfe
2024-06-06 12:17:46 +08:00
Steve Myers
c5a3b62d63
Merge bitcoindevkit/bdk#1390: Make Wallet require a change descriptor
8bc3d35f6c83d078551c4bc57f72f13324865486 fix(wallet): `LoadError::MissingDescriptor` includes the missing KeychainKind (valued mammal)
412dee1f5b027af7800ee155717d47f4ab4b60e0 ref(wallet)!: Make `Wallet::public_descriptor` infallible (valued mammal)
c2513e1090374d7871a8623845bd10757e6ab0b3 test(wallet): Clarify docs for get_funded_wallet (valued mammal)
9d954cf7d25d43c77115cd931407005a09365389 refactor(wallet)!: Make Wallet require a change descriptor (valued mammal)

Pull request description:

  All `Wallet` constructors are modified to require a change descriptor, where previously it was optional. Additionally we enforce uniqueness of the change descriptor to avoid ambiguity when deriving scripts and ensure the wallet will always have two distinct keystores.

  Notable changes

  * Add error `DescriptorError::ExternalAndInternalAreTheSame`
  * Remove error `CreateTxError::ChangePolicyDescriptor`
  * No longer rely on `map_keychain`

  fixes #1383

  ### Notes to the reviewers

  ### Changelog notice

  Changed:

  Constructing a Wallet now requires two distinct descriptors.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    re-ACK 8bc3d35f6c83d078551c4bc57f72f13324865486

Tree-SHA512: f0621deb75d8e1e484b18b40d850f64e26314e39c4778f56c627763ddbffd376288bf6f0f37b61ba2ba744c7083683497d2dfef42bc4ef7d3ed7b374a54d813a
2024-06-05 23:11:00 -05:00
e1a0a0ea
29c8a00b43
chore(wallet): remove duplicated InsufficientFunds error member from CreateTxError
review: move back to old error naming
2024-06-06 11:08:23 +08:00
valued mammal
8bc3d35f6c
fix(wallet): LoadError::MissingDescriptor includes the missing KeychainKind 2024-06-05 06:29:58 -04:00
valued mammal
412dee1f5b
ref(wallet)!: Make Wallet::public_descriptor infallible 2024-06-05 06:29:58 -04:00
valued mammal
c2513e1090
test(wallet): Clarify docs for get_funded_wallet 2024-06-05 06:29:58 -04:00
valued mammal
9d954cf7d2
refactor(wallet)!: Make Wallet require a change descriptor
All `Wallet` constructors are modified to require a change
descriptor, where previously it was optional. Additionally
we enforce uniqueness of the change descriptor to avoid
ambiguity when deriving scripts and ensure the wallet will
always have two distinct keystores.

Notable changes

* Add error DescriptorError::ExternalAndInternalAreTheSame
* Remove error CreateTxError::ChangePolicyDescriptor
* No longer rely on `map_keychain`
2024-06-05 06:29:52 -04:00
志宇
8eef350bd0
Merge bitcoindevkit/bdk#1453: refactor(electrum) put the tx cache in electrum
2d2656acfa83ab4c4846c0aab14072efb64c5cc3 feat(electrum): re-export `transaction_broadcast` method (志宇)
53fa35096fbeea2b82b28987e8ef6f7d39ffc80b refactor(electrum)!: put the tx cache in electrum (LLFourn)

Pull request description:

  Previously there was a `TxCache` that you passed in as part of the sync request. There are lots of downsides to this:

  1. If the user forgets to do this you cache nothing
  2. where are you meant to keep this cache? The example shows it being recreated every time which seems very suboptimal.
  3. More API and documentation surface area.

  Instead just do a plain old simple cache inside the electrum client. This way at least you only download transactions once. You can pre-populate the cache with a method also and I did this in the examples.

  * [x] This pull request breaks the existing API

ACKs for top commit:
  evanlinjin:
    self-ACK 2d2656acfa83ab4c4846c0aab14072efb64c5cc3
  notmandatory:
    ACK 2d2656acfa83ab4c4846c0aab14072efb64c5cc3

Tree-SHA512: 6c29fd4f99ea5bd66234d5cdaf4b157a192ddd3baacc91076e402d8df0de7010bc482e24895e85fcb2f805ec6d1ce6cdb7654f8f552c90ba75ed35f80a00b856
2024-06-05 10:19:00 +08:00
Leonardo Lima
20341a3ca1
fix: typo on SignedAmount instead of Amount 2024-06-04 21:53:08 -03:00
Steve Myers
363d9f42e5
Merge bitcoindevkit/bdk#1455: refactor(wallet): rename get_balance() to balance()
50137b0425fe9c9aac8caaacf099bfe6c69859c2 refactor(wallet): rename get_balance() to balance() (Steve Myers)

Pull request description:

  ### Description

  fixes #1221

  ### Notes to the reviewers

  See discussion in #1221.

  ### Changelog notice

  Changed

  - Wallet::get_balance() renamed to Wallet::balance()

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  LagginTimes:
    ACK 50137b0425fe9c9aac8caaacf099bfe6c69859c2
  oleonardolima:
    ACK 50137b0425fe9c9aac8caaacf099bfe6c69859c2
  evanlinjin:
    ACK 50137b0425fe9c9aac8caaacf099bfe6c69859c2

Tree-SHA512: 20d188a32c79eca37b4f269e5bcdb8c2ecd595911558cb74812a37da13a4f39b603deed3bc11356aa6523b16417a2a025046b3dd4df5bd7247f39c29d7f48ac2
2024-06-04 17:12:37 -05:00
Steve Myers
26586fa7fe
Merge bitcoindevkit/bdk#1426: feat: add further bitcoin::Amount usage on public APIs
a03949adb0c38ba4c2f44b497871070c1a2170d2 feat: use `Amount` on `calculate_fee`, `fee_absolute`, `fee_amount` and others (Leonardo Lima)

Pull request description:

  builds on top of #1411, further improves #823

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  It further updates and adds the usage of `bitcoin::Amount` instead of `u64`.

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers

  Open for comments and discussions.

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice
  - Updated `CreateTxError::FeeTooLow` to use `bitcoin::Amount`.
  - Updated `Wallet::calculate_fee()`. to use `bitcoin::Amount`
  - Updated `TxBuilder::fee_absolute()`. to use `bitcoin::Amount`.
  - Updated `CalculateFeeError::NegativeFee` to use `bitcoin::SignedAmount`.
  - Updated `TxGraph::calculate_fee()`. to use `bitcoin::Amount`.
  - Updated `PsbUtils::fee_amount()` to use `bitcoin::Amount`.

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  storopoli:
    ACK a03949adb0c38ba4c2f44b497871070c1a2170d2

Tree-SHA512: abfbf7d48ec004eb448ed0a928e7e64b5f82a2ab51ec278fede4ddbff4eaba16469a7403f78dfeba1aba693b0132a528bc7c4ef072983cbbcc2592993230e40f
2024-06-04 16:16:03 -05:00
志宇
2d2656acfa
feat(electrum): re-export transaction_broadcast method
Also: update `wallet_electrum` example to use the method.
2024-06-04 12:24:41 +08:00
LLFourn
53fa35096f
refactor(electrum)!: put the tx cache in electrum
Previously there was a tx cache that you passed in as part of the sync
request. This seems bad and the example show'd that you should copy all
your transactions from the transaction graph into the sync request every
time you sync'd. If you forgot to do this then you would always download everything.

Instead just do a plain old simple cache inside the electrum client.
This way at least you only download transactions once. You can
pre-populate the cache with a method also and I did this in the examples.
2024-06-04 12:23:01 +08:00
Leonardo Lima
a03949adb0
feat: use Amount on calculate_fee, fee_absolute, fee_amount and others
- update to use `bitcoin::Amount` on `CreateTxError::FeeTooLow` variant.
- update to use `bitcoin::Amount` on `Wallet::calculate_fee()`.
- update to use `bitcoin::Amount` on `FeePolicy::fee_absolute()`.
- update to use `bitcoin::SignedAmount` on
  `CalculateFeeError::NegativeFee` variant.
- update to use `bitcoin::Amount` on `TxGraph::calculate_fee()`.
- update to use `bitcoin::Amount` on `PsbUtils::fee_amount()`
2024-06-03 13:19:16 -03:00
Steve Myers
50137b0425
refactor(wallet): rename get_balance() to balance() 2024-06-01 17:46:24 -05:00
Steve Myers
4a8452f9b8
Merge bitcoindevkit/bdk#1450: Bump bdk version to 1.0.0-alpha.12
108061dddbba99f03d7416a673135211ef94043b Bump bdk version to 1.0.0-alpha.12 (Steve Myers)

Pull request description:

  ### Description

  fixes #1449

  bdk_chain to 0.15.0
  bdk_bitcoind_rpc to 0.11.0
  bdk_electrum to 0.14.0
  bdk_esplora to 0.14.0
  bdk_persist to 0.3.0
  bdk_file_store to 0.12.0
  bdk_sqlite keep at 0.1.0
  bdk_testenv to 0.5.0
  bdk_hwi to 0.1.0
  bdk_wallet to 1.0.0-alpha.12

  ### Notes to the reviewers

  I also (hopefully) fixed the `bdk_hwi` crate so it can be published.

ACKs for top commit:
  ValuedMammal:
    ACK 108061dddbba99f03d7416a673135211ef94043b
  storopoli:
    ACK 108061dddbba99f03d7416a673135211ef94043b

Tree-SHA512: 2a80c51e254ca011b8e9bb72ad3d720dd8d09a3142e85cf230ffffad747257d91c45950cce64b049bab91f21c70c622f14d46def24ea78459497b42472a1fe48
2024-05-23 17:38:49 -05:00
Steve Myers
108061dddb
Bump bdk version to 1.0.0-alpha.12
bdk_chain to 0.15.0
bdk_bitcoind_rpc to 0.11.0
bdk_electrum to 0.14.0
bdk_esplora to 0.14.0
bdk_persist to 0.3.0
bdk_file_store to 0.12.0
bdk_sqlite keep at 0.1.0
bdk_testenv to 0.5.0
bdk_hwi to 0.1.0
bdk_wallet to 1.0.0-alpha.12
2024-05-23 11:15:30 -05:00
Steve Myers
a2d940132d
Merge bitcoindevkit/bdk#1393: fix(export): add tr descriptor
1b7c6df569a0ff9324bbda1f066938490109481d fix(export): add tr descriptor (rustaceanrob)

Pull request description:

  ### Description

  Resolves #860 by adding export of taproot descriptors

  ### Notes to the reviewers

  Allows export as Core accepts taproot.

  ### Changelog notice

  - Export taproot descriptors

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 1b7c6df569a0ff9324bbda1f066938490109481d

Tree-SHA512: 80bee93a1ec531717e79a5e7a91e840532ae4d3daf677a207bc53162c69410e47db4893024b3eccfd848f1628062e7c49f0e92ebeb7230e2ebb9b47eb84b9e56
2024-05-23 10:19:01 -05:00
Steve Myers
2a055de555
Merge bitcoindevkit/bdk#1386: Remove TxBuilder allow_shrinking() and unneeded context param
096b8ef781b21e7da690b9ca2e4b326880d6ac0b fix(wallet): remove TxBuilder::allow_shrinking function and TxBuilderContext (Steve Myers)

Pull request description:

  ### Description

  Remove wallet::TxBuilder::allow_shrinking() and unneeded TxBuilder context param.

  Fixes #1374

  ### Notes to the reviewers

  The allow_shrinking function was the only one using the TxBuilder FeeBump context and it's useful to have CreateTx context  functions available for building FeeBump transactions, see updated tests.

  ### Changelog notice

  Changed

  - Removed TxBuilder::allow_shrinking() function.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

Top commit has no ACKs.

Tree-SHA512: f4f05ce4cfaced9e61eebc0ebfe77a299fae13df4459fc26c90657297a1347a5d16f22b4e1c8b9b10458cfec80ca3b5d698eee11c7a560fd83f94a1ac7101a86
2024-05-23 10:08:45 -05:00
Steve Myers
096b8ef781
fix(wallet): remove TxBuilder::allow_shrinking function and TxBuilderContext 2024-05-23 09:45:49 -05:00
志宇
2eea0f4e90
Merge bitcoindevkit/bdk#1128: feat: add bdk_sqlite crate implementing PersistBackend
475c5024ecc5d288f35fabb8fab2b62dbf67653b feat(sqlite): add bdk_sqlite crate implementing PersistBackend backed by a SQLite database (Steve Myers)
b8aa76cd050bc3c2eac776ecbd9b4e2ab3e2590e feat(wallet): use the new `CombinedChangeSet` of `bdk_persist` (志宇)
0958ff56b20c1325a7da5d5f21e7ac836c601f1f feat(persist): introduce `CombinedChangeSet` (志宇)
54942a902d3203ee59731f35d2a1c402ac626878 ci: bump build_docs rust version to nightly-2024-05-12 (Steve Myers)
d975a48e7c519a703441e74058321021957b177f docs: update README MSRV pinning to match CI (Steve Myers)

Pull request description:

  ### Description

  Add "bdk_sqlite_store" crate implementing `PersistBackend` backed by a SQLite database.

  ### Notes to the reviewers

  In addition to adding a SQLite based `PersistenceBackend` this PR also:

  * add  `CombinedChangeSet` in `bdk_persist` and update `wallet` crate to use it.
  * updates the `wallet/tests` to also use this new sqlite store crate.
  * updates `example-crates/wallet_esplora_async` to use this new sqlite store crate.
  * fixes out of date README instructions for MSRV.
  * bumps the ci `build_docs` job to rust `nightly-2024-05-12`.

  ### Changelog notice

  Changed

  - Update Wallet to use CombinedChangeSet for persistence.

  Added

  - Add  CombinedChangeSet in bdk_persist crate.
  - Add bdk_sqlite crate implementing SQLite based PersistenceBackend storage for CombinedChangeSet.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  evanlinjin:
    ACK 475c5024ecc5d288f35fabb8fab2b62dbf67653b

Tree-SHA512: 72565127994fbfff34d7359e1d36d6f13e552995bb7ea61dd38ba5329b0d15e500fa106214a83fd870f1017dc659ff1bb8fc71bc6aad0a793730ec7f23179d8c
2024-05-23 22:34:24 +08:00
Steve Myers
475c5024ec
feat(sqlite): add bdk_sqlite crate implementing PersistBackend backed by a SQLite database 2024-05-23 08:59:45 -05:00
志宇
b8aa76cd05
feat(wallet): use the new CombinedChangeSet of bdk_persist 2024-05-22 23:02:55 -05:00
志宇
0958ff56b2
feat(persist): introduce CombinedChangeSet
It is a good idea to have common changeset types stored in
`bdk_persist`. This will make it convenient for persistence crates and
`bdk_wallet` interaction.
2024-05-22 23:02:54 -05:00
Steve Myers
54942a902d
ci: bump build_docs rust version to nightly-2024-05-12 2024-05-22 23:02:52 -05:00
Steve Myers
d975a48e7c
docs: update README MSRV pinning to match CI 2024-05-22 23:02:51 -05:00
志宇
2f059a1588
Merge bitcoindevkit/bdk#1443: fix(electrum): Fix fetch_prev_txout
af15ebba94f6d96a4d266fbbdee7c49150f80b96 fix(electrum): Fix `fetch_prev_txout` (valued mammal)

Pull request description:

  Previously we inserted every `TxOut` of a previous tx at the same outpoint, which is incorrect because an outpoint only points to a single `TxOut`. Now just get the `TxOut` corresponding to the txin prevout and insert it with its outpoint.

  ### Notes to the reviewers

  The bug in question was demonstrated in a discord comment https://discord.com/channels/753336465005608961/1239693193159639073/1239704153400414298 but I don't think we've opened an issue yet. Essentially, because of a mismatch between the outpoint and txout stored in TxGraph, we weren't summing the inputs correctly which caused `calculate_fee` to fail with `NegativeFee` error.

  fixes #1419

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] I've added tests to reproduce the issue which are now passing

ACKs for top commit:
  LagginTimes:
    ACK af15ebba94f6d96a4d266fbbdee7c49150f80b96
  evanlinjin:
    ACK af15ebba94f6d96a4d266fbbdee7c49150f80b96

Tree-SHA512: c3a2c374069b0863076784856d90c7760b8f411e4881c3e42367015542b02ea6010c37745fb6dde95422af7222b7939ec51bc0fd1f63f816813c2159a17e08e5
2024-05-15 20:35:02 +08:00
valued mammal
af15ebba94
fix(electrum): Fix fetch_prev_txout
Previously we inserted every TxOut of a previous tx
at the same outpoint, which is incorrect because an outpoint
only points to a single TxOut. Now just get the TxOut
corresponding to the txin prevout and insert it with
its outpoint.
2024-05-14 10:50:02 -04:00
rustaceanrob
1b7c6df569
fix(export): add tr descriptor 2024-05-13 09:41:27 -10:00
Steve Myers
7607b49283
Merge bitcoindevkit/bdk#1326: chore: rename bdk crate to bdk_wallet
f6781652b7a4833b220e0853cd6e290bb5fc0136 chore: rename bdk crate to bdk_wallet (Steve Myers)

Pull request description:

  ### Description

  Fixes #1305 .

  ### Notes to the reviewers

  Once this properly builds, even before all reviews is done, I will publish it to crates.io to reserve the name.

  ### Changelog notice

  Changed

  - Renamed `bdk` crate to `bdk_wallet`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: 437c79d9d41721bc9cffd3be81e898068378803dcde6b4106d33bf34ffa756d090dce36d15d4ecd232e5b55ce09c393e6956fc0af4b8477886dabb506b679256
2024-05-13 12:25:08 -05:00
Steve Myers
f6781652b7
chore: rename bdk crate to bdk_wallet 2024-05-13 12:10:58 -05:00
Steve Myers
7876c8fd06
Merge bitcoindevkit/bdk#1437: Bump bdk version to 1.0.0-alpha.11
db9fdccc18c418cbbdf39ef4e912416796d63860 Bump bdk version to 1.0.0-alpha.11 (Steve Myers)

Pull request description:

  ### Description

  fixes #1435

  bdk_chain to 0.14.0
  bdk_bitcoind_rpc to 0.10.0
  bdk_electrum to 0.13.0
  bdk_esplora to 0.13.0
  bdk_file_store to 0.11.0
  bdk_testenv to 0.4.0
  bdk_persist to 0.2.0

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  ValuedMammal:
    ACK db9fdccc18c418cbbdf39ef4e912416796d63860
  storopoli:
    ACK db9fdccc18c418cbbdf39ef4e912416796d63860

Tree-SHA512: 804475927461a4bcf37786313123a0a0cc68390af6c556111551dc126a06614296eb657a8a5662a36cf4569ab332f5f9285c99c5f1992d93f43568e881961895
2024-05-10 17:23:21 -05:00
Steve Myers
db9fdccc18
Bump bdk version to 1.0.0-alpha.11
bdk_chain to 0.14.0
bdk_bitcoind_rpc to 0.10.0
bdk_electrum to 0.13.0
bdk_esplora to 0.13.0
bdk_file_store to 0.11.0
bdk_testenv to 0.4.0
bdk_persist to 0.2.0
2024-05-10 14:05:40 -05:00
Steve Myers
63e3bbe820
Merge bitcoindevkit/bdk#1403: Update bdk_electrum crate to use sync/full-scan structs
b45897e6fe2f7e67f5d75ec6f983757b28c5ec19 feat(electrum): update docs and simplify logic of `ElectrumExt` (志宇)
92fb6cb37387fb0b9fe5329e772f0d928a33e116 chore(electrum): do not use `anyhow::Result` directly (志宇)
b2f3cacce6081f3bf6e103d1d2ca0707c545a67e feat(electrum): include option for previous `TxOut`s for fee calculation (Wei Chen)
c0d7d60a582b939324bb48ec8c5035020ec90699 feat(chain)!: use custom return types for `ElectrumExt` methods (志宇)
2945c6be88b3bf5105afeb8addff4861f0458b41 fix(electrum): fixed `sync` functionality (Wei Chen)
9ed33c25ea01278b0a47c8ecd5ea6fa33119a977 docs(electrum): fixed `full_scan`, `sync`, and crate documentation (Wei Chen)
b1f861b932afd5e490c0814b1921b97cc2f1d912 feat: update logging of electrum examples (志宇)
a6fdfb2ae4caa1cdd23aa5e5ffaf02716473a98e feat(electrum)!: use new sync/full-scan structs for `ElectrumExt` (志宇)
653e4fed6d16698bc5859c1e4afdcee7b3d83dad feat(wallet): cache txs when constructing full-scan/sync requests (志宇)
58f27b38eb2093bb9b715b7e0ebd1619ecad74ee feat(chain): introduce `TxCache` to `SyncRequest` and `FullScanRequest` (志宇)
721bb7f519131ca295a00efa2d242b4923e2bddd fix(chain): Make `Anchor` type in `FullScanResult` generic (志宇)
e3cfb84898cfa79d4903cf276fc69ffb0605b4d4 feat(chain): `TxGraph::insert_tx` reuses `Arc` (志宇)
2ffb65618afb7382232a3c08a077dd1109005071 refactor(electrum): remove `RelevantTxids` and track txs in `TxGraph` (Wei Chen)

Pull request description:

  Fixes #1265
  Possibly fixes #1419

  ### Context

  Previous changes such as

  * Universal structures for full-scan/sync (PR #1413)
  * Making `CheckPoint` linked list query-able (PR #1369)
  * Making `Transaction`s cheaply-clonable (PR #1373)

  has allowed us to simplify the interaction between chain-source and receiving-structures (`bdk_chain`).

  The motivation is to accomplish something like this ([as mentioned here](https://github.com/bitcoindevkit/bdk/issues/1153#issuecomment-1752263555)):
  ```rust
  let things_I_am_interested_in = wallet.lock().unwrap().start_sync();
  let update = electrum_or_esplora.sync(things_i_am_interested_in)?;
  wallet.lock().unwrap().apply_update(update)?:
  ```

  ### Description

  This PR greatly simplifies the API of our Electrum chain-source (`bdk_electrum`) by making use of the aforementioned changes. Instead of referring back to the receiving `TxGraph` mid-sync/scan to determine which full transaction to fetch, we provide the Electrum chain-source already-fetched full transactions to start sync/scan (this is cheap, as transactions are wrapped in `Arc`s since #1373).

  In addition, an option has been added to include the previous `TxOut` for transactions received from an external wallet for fee calculation.

  ### Changelog notice

  * Change `TxGraph::insert_tx` to take in anything that satisfies `Into<Arc<Transaction>>`. This allows us to reuse the `Arc` pointer of what is being inserted.
  * Add `tx_cache` field to `SyncRequest` and `FullScanRequest`.
  * Make `Anchor` type in `FullScanResult` generic for more flexibility.
  * Change `ElectrumExt` methods to take in `SyncRequest`/`FullScanRequest` and return `SyncResult`/`FullScanResult`. Also update electrum examples accordingly.
  * Add `ElectrumResultExt` trait which allows us to convert the update `TxGraph` of `SyncResult`/`FullScanResult` for `bdk_electrum`.
  * Added an option for `full_scan` and `sync` to also fetch previous `TxOut`s to allow for fee calculation.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  ValuedMammal:
    ACK b45897e6fe2f7e67f5d75ec6f983757b28c5ec19
  notmandatory:
    ACK b45897e6fe2f7e67f5d75ec6f983757b28c5ec19

Tree-SHA512: 1e274546015e7c7257965b36079ffe0cb3c2c0b7c2e0c322bcf32a06925a0c3e1119da1c8fd5318f1dbd82c2e952f6a07f227a9b023c48f506a62c93045d96d3
2024-05-10 12:33:09 -05:00
志宇
b45897e6fe
feat(electrum): update docs and simplify logic of ElectrumExt
Helper method docs are updated to explain what they are updating. Logic
is simplified as we do not need to check whether a tx exists already in
`update_graph` before inserting it.
2024-05-10 16:40:55 +08:00
志宇
92fb6cb373
chore(electrum): do not use anyhow::Result directly 2024-05-10 14:54:29 +08:00
Wei Chen
b2f3cacce6
feat(electrum): include option for previous TxOuts for fee calculation
The previous `TxOut` for transactions received from an external
wallet may be optionally added as floating `TxOut`s to `TxGraph`
to allow for fee calculation.
2024-05-10 14:54:29 +08:00
志宇
c0d7d60a58
feat(chain)!: use custom return types for ElectrumExt methods
This is more code, but a much more elegant solution than having
`ElectrumExt` methods return `SyncResult`/`FullScanResult` and having an
`ElectrumResultExt` extention trait.
2024-05-10 14:54:29 +08:00
Wei Chen
2945c6be88
fix(electrum): fixed sync functionality 2024-05-10 14:54:28 +08:00
Wei Chen
9ed33c25ea
docs(electrum): fixed full_scan, sync, and crate documentation 2024-05-10 14:54:28 +08:00
志宇
b1f861b932
feat: update logging of electrum examples
* Syncing with `example_electrum` now shows progress as a percentage.
* Flush stdout more aggressively.
2024-05-10 14:54:28 +08:00
志宇
a6fdfb2ae4
feat(electrum)!: use new sync/full-scan structs for ElectrumExt
`ElectrumResultExt` trait is also introduced that adds methods which can
convert the `Anchor` type for the update `TxGraph`.

We also make use of the new `TxCache` fields in
`SyncRequest`/`FullScanRequest`. This way, we can avoid re-fetching full
transactions from Electrum if not needed.

Examples and tests are updated to use the new `ElectrumExt` API.
2024-05-10 14:54:28 +08:00
志宇
653e4fed6d
feat(wallet): cache txs when constructing full-scan/sync requests 2024-05-10 14:11:20 +08:00
志宇
58f27b38eb
feat(chain): introduce TxCache to SyncRequest and FullScanRequest
This transaction cache can be provided so the chain-source can avoid
re-fetching transactions.
2024-05-10 14:11:19 +08:00
志宇
721bb7f519
fix(chain): Make Anchor type in FullScanResult generic 2024-05-10 14:11:19 +08:00
志宇
e3cfb84898
feat(chain): TxGraph::insert_tx reuses Arc
When we insert a transaction that is already wrapped in `Arc`, we should
reuse the `Arc`.
2024-05-10 14:11:19 +08:00
Wei Chen
2ffb65618a
refactor(electrum): remove RelevantTxids and track txs in TxGraph
This PR removes `RelevantTxids` from the electrum crate and tracks
transactions in a `TxGraph`. This removes the need to separately
construct a `TxGraph` after a `full_scan` or `sync`.
2024-05-10 14:11:18 +08:00
Steve Myers
fb7ff298a4
Merge bitcoindevkit/bdk#1203: Include the descriptor in keychain::Changeset
86711d4f46f467c651238ad3804fdbe1d22a8600 doc(chain): add section for non-recommended K to descriptor assignments (Daniela Brozzoni)
de53d721913537f56281a134270eafd356f908ad test: Only the highest ord keychain is returned (Daniela Brozzoni)
9d8023bf56a693f1cb2ba340ed024c654307c069 fix(chain): introduce keychain-variant-ranking to `KeychainTxOutIndex` (志宇)
6c8748124fd40e0fee37f78ca30457441b13fbcb chore(chain): move `use` in `indexed_tx_graph.rs` so clippy is happy (志宇)
537aa03ae0f8bec4dc799d33738e9bb7977bdac1 chore(chain): update test so clippy does not complain (志宇)
ed117de7a5b1756482b2e6487855b80e97c597ba test(chain): applying changesets one-by-one vs aggregate should be same (志宇)
6a3fb849e86e0bc21086519ae0201b95ddde5bf4 fix(chain): simplify `Append::append` impl for `keychain::ChangeSet` (志宇)
1d294b734dd6f4639075cba271e2b40f437f998f fix: Run tests only if the miniscript feature is.. ..enabled, enable it by default (Daniela Brozzoni)
0e3e136f6fa7215f6391dbcc1c4781262111ce64 doc(bdk): Add instructions for manually inserting... ...secret keys in the wallet in Wallet::load (Daniela Brozzoni)
76afccc555feff084867d6f9406e4e74bee938cc fix(wallet): add expected descriptors as signers after creating from wallet::ChangeSet (Steve Myers)
4f05441a00b921efd661da0dff94d9c28e38b70d keychain::ChangeSet includes the descriptor (Daniela Brozzoni)
8ff99f27dfe45643bf401409ca72429a9b812873 ref(chain): Define test descriptors, use them... ...everywhere (Daniela Brozzoni)
b9902936a0d17498eec8866233d89b2882d0af8f ref(chain): move `keychain::ChangeSet` into `txout_index.rs` (志宇)

Pull request description:

  Fixes #1101

  - Moves keychain::ChangeSet inside `keychain/txout_index.rs` as now the `ChangeSet` depends on miniscript
  - Slightly cleans up tests by introducing some constant descriptors
  - 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.

  ### Changelog notice

  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 `BTreeSet` instead of `&BTreeSet`
  - `KeychainTxOutIndex::keychains` returns a `impl Iterator` instead of
        `&BTreeMap`
  - `KeychainTxOutIndex::txouts` doesn't return a ExactSizeIterator anymore
  - `KeychainTxOutIndex::last_revealed_indices` returns a `BTreeMap`
        instead of `&BTreeMap`
  - `KeychainTxOutIndex::add_keychain` has been renamed to `KeychainTxOutIndex::insert_descriptor`, and now it returns a ChangeSet
  - `KeychainTxOutIndex::reveal_next_spk` returns Option
  - `KeychainTxOutIndex::next_unused_spk` returns Option
  - `KeychainTxOutIndex::unbounded_spk_iter` returns Option
  - `KeychainTxOutIndex::next_index` returns Option
  - `KeychainTxOutIndex::reveal_to_target` returns Option
  - `KeychainTxOutIndex::revealed_keychain_spks` returns Option
  - `KeychainTxOutIndex::unused_keychain_spks` returns Option
  - `KeychainTxOutIndex::last_revealed_index` returns Option
  - `KeychainTxOutIndex::keychain_outpoints` returns Option
  - `KeychainTxOutIndex::keychain_outpoints_in_range` returns Option
  - `KeychainTxOutIndex::last_used_index` returns None if the keychain has never been used, or if it doesn't exist

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  evanlinjin:
    ACK 86711d4f46f467c651238ad3804fdbe1d22a8600

Tree-SHA512: 4b1c9a31951f67b18037b7dd9837acbc35823f21de644ab833754b74d20f5373549f81e66965ecd3953ebf4f99644c9fd834812acfa65f9188950f1bda17ab60
2024-05-09 13:18:57 -05:00
Daniela Brozzoni
86711d4f46
doc(chain): add section for non-recommended K to descriptor assignments 2024-05-09 14:40:19 +08:00
Steve Myers
86408b90a5
Merge bitcoindevkit/bdk#1430: ci: Pin clippy to rust 1.78.0
de2763a4b88e65b1c67a06148b4f9e012e561c5a ci: Pin clippy to rust 1.78.0 (valued mammal)

Pull request description:

  This PR pins clippy check in CI to the rust 1.78 toolchain, which prevents new lints in stable releases from interrupting the usual workflow. Because rust versions are released on a predictable schedule, we can revisit this setting in the future as needed (say 3-6 months).

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [ ] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK de2763a4b88e65b1c67a06148b4f9e012e561c5a
  storopoli:
    ACK de2763a4b88e65b1c67a06148b4f9e012e561c5a
  notmandatory:
    ACK de2763a4b88e65b1c67a06148b4f9e012e561c5a
  oleonardolima:
    ACK de2763a4b88e65b1c67a06148b4f9e012e561c5a

Tree-SHA512: 73cad29a5ff437290aca8f85a011c4f5fc4d9ff5755f3d3ef9fa1820f5631eda857b1a67955adfc6ef98145958c674cc09f7613b96f38cc30c75a656d872edbc
2024-05-08 19:37:06 -05:00
Daniela Brozzoni
de53d72191
test: Only the highest ord keychain is returned 2024-05-08 15:49:51 +02:00
志宇
9d8023bf56
fix(chain): introduce keychain-variant-ranking to KeychainTxOutIndex
This fixes the bug with changesets not being monotone. Previously, the
result of applying changesets individually v.s. applying the aggregate
of changesets may result in different `KeychainTxOutIndex` states.

The nature of the changeset allows different keychain types to share the
same descriptor. However, the previous design did not take this into
account. To do this properly, we should keep track of all keychains
currently associated with a given descriptor. However, the API only
allows returning one keychain per spk/txout/outpoint (which is a good
API).

Therefore, we rank keychain variants by `Ord`. Earlier keychain variants
have a higher rank, and the first keychain will be returned.
2024-05-08 15:49:50 +02:00
志宇
6c8748124f
chore(chain): move use in indexed_tx_graph.rs so clippy is happy 2024-05-08 15:49:48 +02:00
志宇
537aa03ae0
chore(chain): update test so clippy does not complain 2024-05-08 15:49:47 +02:00
志宇
ed117de7a5
test(chain): applying changesets one-by-one vs aggregate should be same 2024-05-08 15:49:46 +02:00
志宇
6a3fb849e8
fix(chain): simplify Append::append impl for keychain::ChangeSet
We only need to loop though entries of `other`. The logic before was
wasteful because we were also looping though all entries of `self` even
if we do not need to modify the `self` entry.
2024-05-08 15:49:45 +02: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
0e3e136f6f
doc(bdk): Add instructions for manually inserting...
...secret keys in the wallet in Wallet::load
2024-05-08 15:49:43 +02:00
Steve Myers
76afccc555
fix(wallet): add expected descriptors as signers after creating from wallet::ChangeSet 2024-05-08 15:49:42 +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
志宇
b9902936a0
ref(chain): move keychain::ChangeSet into txout_index.rs
We plan to record `Descriptor` additions into persistence. Hence, we
need to add `Descriptor`s to the changeset. This depends on
`miniscript`. Moving this into `txout_index.rs` makes sense as this is
consistent with all the other files. The only reason why this wasn't
this way before, is because the changeset didn't need miniscript.

Co-Authored-By: Daniela Brozzoni <danielabrozzoni@protonmail.com>
2024-05-08 13:23:27 +02:00
Steve Myers
66abc73c3d
Merge bitcoindevkit/bdk#1423: fix(persist): add default feature to enable bdk_chain/std
a577c22b12f4edf0b2f2f266fb13656caf1d21c4 fix(persist): add default feature to enable bdk_chain/std (Steve Myers)

Pull request description:

  ### Description

  This PR adds a `default` feature to `bdk_persist` so it can be build on its own.  Once #1422 is done we can remove the `default`again.

  ### Notes to the reviewers

  I need to be able to build `bdk_persist` on its own so I can publish it to crates.io.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  ValuedMammal:
    ACK a577c22b12f4edf0b2f2f266fb13656caf1d21c4
  oleonardolima:
    ACK a577c22b12f4edf0b2f2f266fb13656caf1d21c4
  storopoli:
    ACK a577c22b12f4edf0b2f2f266fb13656caf1d21c4

Tree-SHA512: 8b07a9e4974dec8812ca19ce7226dcaece064270a0be8b83d3c326fdf1e89b051eb0bd8aa0eda9362b2c8233ecd6003b70c92ee046603973d8d40611418c3841
2024-05-07 19:32:09 -05:00
valued mammal
de2763a4b8
ci: Pin clippy to rust 1.78.0 2024-05-07 09:55:14 -04:00
志宇
dcd2d4741d
Merge bitcoindevkit/bdk#1411: feat: update keychain::Balance to use bitcoin::Amount
22aa534d7648e5808414ea3adfcfb702572bd6c9 feat: use `Amount` on `TxBuilder::add_recipient` (Leonardo Lima)
d5c0e7200cba0c3b4d3e3fbea168cd07ee6c1d2c feat: use `Amount` on `spk_txout_index` and related (Leonardo Lima)
8a33d98db977a07e130ad57fa9c658a5c90d4a4b feat: update `wallet::Balance` to use `bitcoin::Amount` (Leonardo Lima)

Pull request description:

  fixes #823

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  It's being used on `Balance`, and throughout the code, an `u64` represents the amount, which relies on the user to infer its sats, not millisats, or any other representation.

  It updates the usage of `u64` on `Balance`, and other APIs:
  - `TxParams::add_recipient`
  - `KeyChainTxOutIndex::sent_and_received`, `KeyChainTxOutIndex::net_value`
  -  `SpkTxOutIndex::sent_and_received`, `SpkTxOutIndex::net_value`

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  It updates some of the APIs to expect the `bitcoin::Amount`, but it does not update internal usage of u64, such as `TxParams` still expects and uses `u64`, please see the PR comments for related discussion.

  ### Changelog notice

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  - Changed the `keychain::Balance` struct fields to use `Amount` instead of `u64`.
  - Changed the `add_recipient` method on `TxBuilder` implementation to expect `bitcoin::Amount`.
  - Changed the `sent_and_received`, and `net_value` methods on `KeyChainTxOutIndex` to expect `bitcoin::Amount`.
  - Changed the `sent_and_received`, and `net_value` methods on `SpkTxOutIndex` to expect `bitcoin::Amount`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK 22aa534d7648e5808414ea3adfcfb702572bd6c9

Tree-SHA512: c4e8198d96c0d66cc3d2e4149e8a56bb7565b9cd49ff42113eaebd24b1d7bfeecd7124db0b06524b78b8891ee1bde1546705b80afad408f48495cf3c02446d02
2024-05-06 20:23:48 +08:00
志宇
23538c4039
Merge bitcoindevkit/bdk#1414: chore: clean up electrsd and anyhow dev dependencies
f6218e4741a4b036d33a9f075ce5feb484e9bd87 chore: reexport crates in `TestEnv` (Wei Chen)
125959976f63a1e12fc139f048dc2856e993efe5 chore: remove `anyhow` dev dependency from `electrum`, `esplora`, and `bitcoind_rpc` (Wei Chen)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Reexports `electrsd` in `TestEnv` to remove the `electrsd` dev depedency out of `bdk_electrum` and `bdk_esplora`.
  Credit to @ValuedMammal for the idea.

  Since `bitcoind` reexports `anyhow`, this dev dependency was also removed from `bdk_electrum`, `bdk_esplora`, and `bdk_bitcoind_rpc`. `bitcoind`, `bitcoincore_rpc` and `electrum_client` were also reexported for convenience.

  ### Changelog notice

  * Change `bdk_testenv` to re-export internally used crates.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK f6218e4741a4b036d33a9f075ce5feb484e9bd87

Tree-SHA512: c7645eb91d08d4ccb80982a992f691b5a8c0df39df506f6b361bc6f2bb076d62cbe5bb5d88b4c684c36e22464c0674f21f6ef4e23733f89b03aa12ec43a67cba
2024-05-06 20:12:23 +08:00
志宇
a9f7377934
Merge bitcoindevkit/bdk#1427: docs(esplora): fixed full_scan and sync documentation
f6dc6890c37752e80c86c68ae3ca3cc4fac6245e docs(esplora): fixed `full_scan` and `sync` documentation (Wei Chen)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Fixed documentation for `full_scan` and `sync` in `bdk_esplora`.

  ### Changelog notice

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->
  * Updated documentation for `full_scan` and `sync` in `bdk_esplora`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK f6dc6890c37752e80c86c68ae3ca3cc4fac6245e
  storopoli:
    ACK f6dc6890c37752e80c86c68ae3ca3cc4fac6245e

Tree-SHA512: 900fb1a2839379af867a6effad32ec4bdfb897330a72ee1e1ec203299e7f3d5fae576550aeed8fd93c5c70a13ad2b0e898033d8b45b490319b5d74216b93f332
2024-05-06 20:09:31 +08:00
Wei Chen
f6dc6890c3
docs(esplora): fixed full_scan and sync documentation 2024-05-06 16:51:19 +08:00
Leonardo Lima
22aa534d76
feat: use Amount on TxBuilder::add_recipient 2024-05-05 12:07:07 -03:00
Leonardo Lima
d5c0e7200c
feat: use Amount on spk_txout_index and related
- update `wallet.rs` fns: `sent_and_received` fn
- update `keychain` `txout_index` fn: `sent_and_received and `net_value`
2024-05-05 12:07:01 -03:00
Wei Chen
f6218e4741
chore: reexport crates in TestEnv 2024-05-05 19:28:18 +08:00
Wei Chen
125959976f
chore: remove anyhow dev dependency from electrum, esplora, and bitcoind_rpc 2024-05-05 19:28:18 +08: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
志宇
2703cc6e78
Merge bitcoindevkit/bdk#1417: test(wallet): add thread safety test
db4734747240d2e1cc72bbfd7be6c49baa8d2967 test(wallet): add thread safety test (Rob N)

Pull request description:

  ### Description

  `Wallet` auto-implements `Send` and `Sync` after removing the generic. This test is a compile time error if there are changes to `Wallet` in the future that make it unsafe to send between threads. See #1387 for discussion.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK db4734747240d2e1cc72bbfd7be6c49baa8d2967

Tree-SHA512: 490e666bc503f15286268db7e5e2f75ee44ad2f80251d6f7a01af2a435023b87607eee33623712433ea8d27511be63c6c1e9cad4159b3fe66a4644cfa9e344fb
2024-05-04 20:24:30 +08:00
Rob N
db47347472
test(wallet): add thread safety test 2024-05-02 08:43:02 -10:00
Steve Myers
a577c22b12
fix(persist): add default feature to enable bdk_chain/std 2024-05-02 13:30:13 -05:00
Daniela Brozzoni
fbe17820dc
Merge bitcoindevkit/bdk#1420: Bump bdk version to 1.0.0-alpha.10
2cda9f44ee1807898e4f2afffc95774839fee678 Bump bdk version to 1.0.0-alpha.10 (Daniela Brozzoni)

Pull request description:

  ### Description

  bdk_chain to 0.13.0
  bdk_bitcoind_rpc to 0.9.0
  bdk_electrum to 0.12.0
  bdk_esplora to 0.12.0
  bdk_file_store to 0.10.0
  bdk_testenv to 0.3.0
  bdk_persist to 0.2.0

  ### Checklists
  #### All Submissions:
  - [x] I've signed all my commits
  - [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  - [x] I ran cargo fmt and cargo clippy before committing

ACKs for top commit:
  storopoli:
    ACK 2cda9f44ee1807898e4f2afffc95774839fee678

Tree-SHA512: 7d3e5f2c9b9da13713e3bb1e6a11d07e9c381221c837a002aefb780698b1d45d64f2582bd0445ecdf7432bf3fe0ba5d6dadd43aa413cf4e5e557f7334a02fa06
2024-05-02 17:54:26 +02:00
Daniela Brozzoni
2cda9f44ee
Bump bdk version to 1.0.0-alpha.10
bdk_chain to 0.13.0
bdk_bitcoind_rpc to 0.9.0
bdk_electrum to 0.12.0
bdk_esplora to 0.12.0
bdk_file_store to 0.10.0
bdk_testenv to 0.3.0
bdk_persist to 0.2.0
2024-05-02 17:34:03 +02:00
Daniela Brozzoni
b6909e133b
Merge bitcoindevkit/bdk#1421: fix: Cargo clippy lints
a5fb7fdf505a53b5865ed83d53745e7efa5e7818 fix: Cargo clippy lints after rust 1.78 (Daniela Brozzoni)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Caught when trying to release (#1420), clippy failed randomly although it worked on master, this happened because rust 1.78 had just been release and we use clippy stable. IMHO we should pin the clippy version in CI and bump it manually at each new rust release.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK a5fb7fdf505a53b5865ed83d53745e7efa5e7818

Tree-SHA512: c803366367576224f9e9690cdee2c0161fc083550355415f9174e93ada2f597440f54ac966bb3ebecdc916824d43de17ac72801e4ef0f75c8a1df640fe40df6d
2024-05-02 15:44:06 +02:00
Daniela Brozzoni
a5fb7fdf50
fix: Cargo clippy lints after rust 1.78 2024-05-02 15:24:21 +02:00
志宇
08fac47c29
Merge bitcoindevkit/bdk#1413: Introduce universal sync/full-scan structures for spk-based syncing
c0374a0eeb155f1cb4f9d99223f6bc65d24f7df8 feat(chain): `SyncRequest` now uses `ExactSizeIterator`s (志宇)
0f94f24aaf6374fe2d7c2abf32a870d3849fb8cc feat(esplora)!: update to use new sync/full-scan structures (志宇)
4c52f3e08e85e73db379ee3411cceb8dbcec92e1 feat(wallet): make wallet compatible with sync/full-scan structures (志宇)
cdfec5f90726f2313963c3a71e5d18bb10624736 feat(chain): add sync/full-scan structures for spk-based syncing (志宇)

Pull request description:

  Fixes #1153
  Replaces #1194

  ### Description

  Introduce universal structures that represent sync/full-scan requests/results.

  ### Notes to the reviewers

  This is based on #1194 but is different in the following ways:
  * The functionality to print scan/sync progress is not reduced.
  * `SyncRequest` and `FullScanRequest` is simplified and fields are exposed for more flexibility.

  ### Changelog notice

  * Add universal structures for initiating/receiving sync/full-scan requests/results for spk-based syncing.
  * Updated `bdk_esplora` chain-source to make use of new universal sync/full-scan structures.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  notmandatory:
    tACK c0374a0eeb155f1cb4f9d99223f6bc65d24f7df8

Tree-SHA512: c2ad66d972a6785079bca615dfd128edcedf6b7a02670651a0ab1ce5b5174dd96f54644680eedbf55e3f1955fe5c34f632eadbd3f71d7ffde658753c6c6d42be
2024-05-01 14:59:01 +08:00
志宇
ed3ccc1a9d
Merge bitcoindevkit/bdk#1412: Add new crate bdk-persist
81de8f60516899fad2ec99cbd15d6b8d02385ebb feat(bdk-persist): extract persistence traits to new crate (Rob N)

Pull request description:

  ### Description

  #1387 introduced `anyhow` as a dependency to remove generics from `Wallet`. Introducing a new crate for persistence types removes the dependency on `anyhow` for `bdk_chain`. Resolves #1409, as well as removing the old documentation for "tracker".

  ### Notes to the reviewers

  Open for any comments.

  ### Changelog notice

  - Introduce `bdk-persist` crate

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK 81de8f60516899fad2ec99cbd15d6b8d02385ebb

Tree-SHA512: 29b192b13f3951cc67c06bec7f788d8d7a4aeaf2ffcbf9476d4a6567529d284a93594c8d94b69741a68a9aadfdc9f6c4178084a2298c505e8e0d505219400382
2024-04-29 16:39:05 +08:00
志宇
c0374a0eeb
feat(chain): SyncRequest now uses ExactSizeIterators
This allows the caller to track sync progress.
2024-04-27 20:40:08 +08:00
Rob N
81de8f6051
feat(bdk-persist): extract persistence traits to new crate 2024-04-26 16:21:54 -10:00
志宇
0f94f24aaf
feat(esplora)!: update to use new sync/full-scan structures 2024-04-26 15:09:21 +08:00
志宇
4c52f3e08e
feat(wallet): make wallet compatible with sync/full-scan structures
* Changed `Wallet::apply_update` to also take in anything that
  implements `Into<Update>`. This allows us to directly apply a
  `FullScanResult` or `SyncResult`.
* Added `start_full_scan` and `start_sync_with_revealed_spks` methods to
  `Wallet`.

Co-authored-by: Steve Myers <steve@notmandatory.org>
2024-04-26 12:55:48 +08:00
志宇
cdfec5f907
feat(chain): add sync/full-scan structures for spk-based syncing
These structures allows spk-based chain-sources to have a universal API.

Co-authored-by: Steve Myers <steve@notmandatory.org>
2024-04-26 12:55:47 +08:00
志宇
8e73998cfa
Merge bitcoindevkit/bdk#1380: Simplified EsploraExt API
96a9aa6e63474dbd93a2ef969eef5b07c79e6491 feat(chain): refactor `merge_chains` (志宇)
2f22987c9e924800f8682b2dcbdde60fd26b069a chore(chain): fix comment (志宇)
daf588f016ec3118c875db8ed6b55fa03683f0f6 feat(chain): optimize `merge_chains` (志宇)
77d35954c1f3a18f767267e9097f63ca11c709ec feat(chain)!: rm `local_chain::Update` (志宇)
1269b0610efb7bd86d92a909800f9330568c797a test(chain): fix incorrect test case (志宇)
72fe65b65f297ebb7160eee6859c46e29c2d9528 feat(esplora)!: simplify chain update logic (志宇)
eded1a7ea0c6a4b9664826df4f77b714cbad0bcc feat(chain): introduce `CheckPoint::insert` (志宇)
519cd75d23fbb72321b0b189dca12afbfd78c0c7 test(esplora): move esplora tests into src files (志宇)
a6e613e6b978b995abf6c92a16df0300b113aa2c test(esplora): add `test_finalize_chain_update` (志宇)
494d253493f1bc914adba16a28ccf1bc0a0f4ec8 feat(testenv): add `genesis_hash` method (志宇)
886d72e3d541d088320bbdad6804057f32aca684 chore(chain)!: rm `missing_heights` and `missing_heights_from` methods (志宇)
bd62aa0fe199d676710c9909617198d62f4897c0 feat(esplora)!: remove `EsploraExt::update_local_chain` (志宇)
1e997939837e9c1f0c087d6d28ac12e373c8c05f feat(testenv): add `make_checkpoint_tip` (志宇)

Pull request description:

  Fixes #1354

  ### Description

  Built on top of both #1369 and #1373, we simplify the `EsploraExt` API by removing the `update_local_chain` method and having `full_scan` and `sync` update the local chain in the same call. The `full_scan` and `sync` methods now takes in an additional input (`local_tip`) which provides us with the view of the `LocalChain` before the update. These methods now return structs `FullScanUpdate` and `SyncUpdate`.

  The examples are updated to use this new API. `TxGraph::missing_heights` and `tx_graph::ChangeSet::missing_heights_from` are no longer needed, therefore they are removed.

  Additionally, we used this opportunity to simplify the logic which updates `LocalChain`. We got rid of the `local_chain::Update` struct (which contained the update `CheckPoint` tip and a `bool` which signaled whether we want to introduce blocks below point of agreement). It turns out we can use something like `CheckPoint::insert` so the chain source can craft an update based on the old tip. This way, we can make better use of `merge_chains`' optimization that compares the `Arc` pointers of the local and update chain (before we were crafting the update chain NOT based on top of the previous local chain). With this, we no longer need the `Update::introduce_older_block` field since the logic will naturally break when we reach a matching `Arc` pointer.

  ### Notes to the reviewers

  * Obtaining the `LocalChain`'s update now happens within `EsploraExt::full_scan` and `EsploraExt::sync`. Creating the `LocalChain` update is now split into two methods (`fetch_latest_blocks` and `chain_update`) that are called before and after fetching transactions and anchors.
  * We need to duplicate code for `bdk_esplora`. One for blocking and one for async.

  ### Changelog notice

  * Changed `EsploraExt` API so that sync only requires one round of fetching data. The `local_chain_update` method is removed and the `local_tip` parameter is added to the `full_scan` and `sync` methods.
  * Removed `TxGraph::missing_heights` and `tx_graph::ChangeSet::missing_heights_from` methods.
  * Introduced `CheckPoint::insert` which allows convenient checkpoint-insertion. This is intended for use by chain-sources when crafting an update.
  * Refactored `merge_chains` to also return the resultant `CheckPoint` tip.
  * Optimized the update `LocalChain` logic - use the update `CheckPoint` as the new `CheckPoint` tip when possible.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  LLFourn:
    ACK 96a9aa6e63474dbd93a2ef969eef5b07c79e6491

Tree-SHA512: 3d4f2eab08a1fe94eb578c594126e99679f72e231680b2edd4bfb018ba1d998ca123b07acb2d19c644d5887fc36b8e42badba91cd09853df421ded04de45bf69
2024-04-22 17:45:01 +08:00
志宇
96a9aa6e63
feat(chain): refactor merge_chains
`merge_chains` now returns a tuple of the resultant checkpoint AND
changeset. This is arguably a more readable/understandable setup.

To do this, we had to create `CheckPoint::apply_changeset` which is kept
as a private method.

Thank you @ValuedMammal for the suggestion.

Co-authored-by: valuedvalued mammal <valuedmammal@protonmail.com>
2024-04-22 17:39:06 +08:00
志宇
2f22987c9e
chore(chain): fix comment 2024-04-22 10:39:37 +08:00
志宇
9800f8d88e
Merge bitcoindevkit/bdk#1408: Fix: enable blocking-https-rustls feature on esplora client
d3a14d411d2a1a37f07e42c28eae3a1836aec14d fix: enable blocking-https-rustls feature on esplora client (thunderbiscuit)

Pull request description:

  The [`blocking` feature on the rust-esplora-client library](https://github.com/bitcoindevkit/rust-esplora-client/blame/master/Cargo.toml#L35) changed from ureq to minreq, which does not come with https enabled by default, breaking previously working code that simply enabled the `blocking` feature on the `bdk_esplora` crate.

  This change will enable what is currently the "default https" [flag for the minreq library](https://docs.rs/minreq/latest/minreq/#https-or-https-rustls) when using the `blocking` feature on bdk_esplora, reverting that breaking change.

  ### Notes to the reviewers

  Another way we could do this (let me know if this is preferable) is to add a new feature called `blocking-https-rustls`:
  ```rust
  blocking = ["esplora-client/blocking"]
  blocking-https-rustls = ["esplora-client/blocking-https-rustls"]
  ```

  ### Changelog notice
  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  storopoli:
    ACK d3a14d411d2a1a37f07e42c28eae3a1836aec14d
  evanlinjin:
    ACK d3a14d411d2a1a37f07e42c28eae3a1836aec14d

Tree-SHA512: d25495186ceba2fcd04bc9ff0aebfb32ac5db6885ef8e4df1e304c5ee5264f6161821e06d29367d2837afcc64a53f1553e7c0bb065e6a2e46dc08b8e04c2ad8e
2024-04-20 16:01:20 +08:00
志宇
e0bcca32b1
Merge bitcoindevkit/bdk#1402: [wallet] Improve address API
d39b319ddf6bf3365d5d01841a8d366c6231db06 test(wallet): Test wallet addresses (valued mammal)
a266b4718f7839759a3e615805931041b67b8e91 chore(wallet)!: Remove enum AddressIndex (valued mammal)
d87874780b4a4c7be282381ae1102c028f3ae581 refactor(wallet)!: Remove method get_address (valued mammal)
d3763e5e37569cea0860217fba980ab0389e4e64 feat(wallet): Add new address methods (valued mammal)

Pull request description:

  Improvements to the wallet address API, see commit messages for details.

  ### Notes to the reviewers

  The logic of getting addresses is roughly the same as before when using `AddressIndex`, following this mapping:

  - `New` -> `reveal_next_address`
  - `LastUnused` -> `next_unused_address` (assuming this is what `LastUnused` really means)
  - `Peek` -> `peek_address`

  Wondering whether it makes sense to expose [`is_used`](358e842dcd/crates/chain/src/keychain/txout_index.rs (L236)) for Wallet as well.

  fixes #898

  ### Changelog notice

  Added:

  - Added Wallet methods:
    - `peek_address`
    - `reveal_next_address`
    - `next_unused_address`
    - `reveal_addresses_to`
    - `list_unused_addresses`
    - `mark_used`
    - `unmark_used`

  Removed:

  - Removed Wallet methods:
    - `get_address`
    - `get_internal_address`
    - `try_get_address`
    - `try_get_internal_address`

  - Removed type AddressIndex

  ### Checklists

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  ### Feature

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] This pull request breaks the existing API
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK d39b319ddf6bf3365d5d01841a8d366c6231db06

Tree-SHA512: ab7f3031f552ee6ea58ae4f3c5412bbedc0ea63e662fe9fa402de0f68a50448521be1e118e89f70bf970d5bf44ea1dc66bbeeff3e9312bae966bebd3072a7073
2024-04-20 15:42:25 +08:00
valued mammal
d39b319ddf
test(wallet): Test wallet addresses
Adds test coverage for Wallet methods `reveal_addresses_to`,
`mark_used`, and `unmark_used`
2024-04-20 15:12:41 +08:00
valued mammal
a266b4718f
chore(wallet)!: Remove enum AddressIndex 2024-04-20 15:12:39 +08:00
valued mammal
d87874780b
refactor(wallet)!: Remove method get_address
As this is now made redundant by the newly added
wallet address methods.
2024-04-20 15:10:36 +08:00
valued mammal
d3763e5e37
feat(wallet): Add new address methods
Introduce a new API for getting addresses from the Wallet that
reflects a similiar interface as the underlying indexer
`KeychainTxOutIndex` in preparation for removing `AddressIndex` enum.

Before this change, the only way to get an address was via the methods
`try_get{_internal}_address` which required a `&mut` reference to the
wallet, matching on the desired AddressIndex variant. This is too
restrictive since for example peeking or listing unused addresses
shouldn't change the state of the wallet. Hence we provide separate
methods for each use case which makes for a more efficient API.
2024-04-20 15:02:55 +08:00
志宇
f00de9e0c1
Merge bitcoindevkit/bdk#1387: fix(wallet): remove the generic from wallet
e51af49ffa951e14203ac2b465ade351dd90f6cd fix(wallet): remove generic from wallet (Rob N)

Pull request description:

  ### Description

  The `PersistenceBackend` uses generics to describe errors returned while applying the change set to the persistence layer. This change removes generics wherever possible and introduces a new public error enum. Removing the generics from `PersistenceBackend` errors is the first step towards #1363

  *Update*: I proceeded with removing the generics from `Wallet` by introducing a `Box<dyn PersistenceBackend>` .

  ### Notes to the reviewers

  This one sort of blew up in the number of changes due to the use of generics for most of the `Wallet` error variants. The generics were only used for the persistence errors, so I removed the generics from higher level errors whenever possible. The error variants of `PersistenceBackend` may also be more expressive, but I will level that up for discussion and make any changes required.

  ### Changelog notice

  - Changed `PersistenceBackend` errors to depend on the `anyhow` crate.
  - Remove the generic `T` from `Wallet`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK e51af49ffa951e14203ac2b465ade351dd90f6cd

Tree-SHA512: 8ce4f1c495310e16145555f4a6a29a0f42cf8944eda68004595c3532580767f64f779185022147a00d75001c40d69fdf8f8de2d348eb68484b170d2a181117ff
2024-04-20 14:54:33 +08:00
thunderbiscuit
d3a14d411d
fix: enable blocking-https-rustls feature on esplora client 2024-04-19 11:45:39 -04:00
志宇
52f3955557
Merge bitcoindevkit/bdk#1324: [chain] Make KeychainTxOutIndex more range based
fac228337c79e1a7c406500c177e049e7f9f5da7 feat(chain)!: make `KeychainTxOutIndex` more range based (LLFourn)

Pull request description:

  KeychainTxOut index should try and avoid "all" kind of queries. There may be subranges of interest. If the user wants "all" they can just query "..".

  The ideas is that KeychainTxOutIndex should be designed to be able to incorporate many unrelated keychains that can be managed in the same index. We should be able to see the "net_value" of a transaction to a specific subrange. e.g. imagine a collaborative custody service that manages all their user descriptors inside the same `KeychainTxOutIndex`. One user in their service may pay another so when you are analyzing how much a transaction is spending for a particular user you need to do analyze a particular sub-range.

  ### Notes to the reviewers

  - I didn't change `unused_spks` to follow this rule because I want to delete that method some time in the future. `unused_spks` is being used in the examples for syncing but it shouldn't be (the discussion as to why will probably surface in #1194).
  - I haven't applied this reasoning to the methods that return `BTreeMap`s e.g. `all_unbounded_spk_iters`. It probably should be but I haven't made up my mind yet.

  This probably belongs after #1194

  ### Changelog notice

  - `KeychainTxOutIndex` methods modified to take ranges of keychains instead.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  evanlinjin:
    ACK fac228337c79e1a7c406500c177e049e7f9f5da7

Tree-SHA512: ec1e75f19d79f71de4b6d7748ef6da076ca92c2f3fd07e0f0dc88e091bf80c61268880ef78be4bed5e0dbab2572e22028f868f33e68a67d47813195d38d78ba5
2024-04-18 15:39:39 +08:00
LLFourn
fac228337c
feat(chain)!: make KeychainTxOutIndex more range based
`KeychainTxOutIndex` should try and avoid "all" kind of queries.
There may be subranges of interest. If the user wants "all" they can
just query "..".
2024-04-18 15:31:14 +08:00
志宇
daf588f016
feat(chain): optimize merge_chains 2024-04-17 14:06:44 +08:00
志宇
77d35954c1
feat(chain)!: rm local_chain::Update
The intention is to remove the `Update::introduce_older_blocks`
parameter and update the local chain directly with `CheckPoint`.

This simplifies the API and there is a way to do this efficiently.
2024-04-17 10:57:50 +08:00
志宇
1269b0610e
test(chain): fix incorrect test case 2024-04-17 10:45:19 +08:00
志宇
72fe65b65f
feat(esplora)!: simplify chain update logic
Co-authored-by: LLFourn <lloyd.fourn@gmail.com>
2024-04-16 19:40:28 +08:00
志宇
eded1a7ea0
feat(chain): introduce CheckPoint::insert
Co-authored-by: LLFourn <lloyd.fourn@gmail.com>
2024-04-16 19:28:41 +08:00
志宇
519cd75d23
test(esplora): move esplora tests into src files
Since we want to keep these methods private.
2024-04-16 19:28:38 +08:00
志宇
a6e613e6b9
test(esplora): add test_finalize_chain_update
We ensure that calling `finalize_chain_update` does not result in a
chain which removed previous heights and all anchor heights are
included.
2024-04-16 18:01:51 +08:00
志宇
494d253493
feat(testenv): add genesis_hash method
This gets the genesis hash of the env blockchain.
2024-04-16 18:01:51 +08:00
志宇
886d72e3d5
chore(chain)!: rm missing_heights and missing_heights_from methods
These methods are no longer needed as we can determine missing heights
directly from the `CheckPoint` tip.
2024-04-16 18:01:50 +08:00
志宇
bd62aa0fe1
feat(esplora)!: remove EsploraExt::update_local_chain
Previously, we would update the `TxGraph` and `KeychainTxOutIndex`
first, then create a second update for `LocalChain`. This required
locking the receiving structures 3 times (instead of twice, which
is optimal).

This PR eliminates this requirement by making use of the new `query`
method of `CheckPoint`.

Examples are also updated to use the new API.
2024-04-16 18:01:47 +08:00
志宇
1e99793983
feat(testenv): add make_checkpoint_tip
This creates a checkpoint linked list which contains all blocks.
2024-04-16 17:51:02 +08:00
Rob N
e51af49ffa
fix(wallet): remove generic from wallet 2024-04-15 10:33:34 -10:00
Steve Myers
ee21ffeee0
Merge bitcoindevkit/bdk#1404: Bump bdk version to 1.0.0-alpha.9
5f238d8e672047ac2766550aa3ed97e05e7b2531 Bump bdk version to 1.0.0-alpha.9 (Steve Myers)

Pull request description:

  ### Description

  Bump bdk version to 1.0.0-alpha.9

  bdk_chain to 0.12.0
  bdk_bitcoind_rpc to 0.8.0
  bdk_electrum to 0.11.0
  bdk_esplora to 0.11.0
  bdk_file_store to 0.9.0
  bdk_testenv to 0.2.0

  fixes #1399

  ### Notes to the reviewers

  I also removed unneeded version for bdk_testenv in dev-dependencies, see https://github.com/bitcoindevkit/bdk/pull/1177#discussion_r1545945973.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 5f238d8e672047ac2766550aa3ed97e05e7b2531

Tree-SHA512: 7ede94a6476a6b8c49a16b0aad147030eab23e26b9c4cadb1dd319fb8562ae325640f506f2d6dab0e85b0ee7f6955ac298ec1f70264704dc7f9a9492f8794f38
2024-04-15 15:10:23 -05:00
Steve Myers
5f238d8e67
Bump bdk version to 1.0.0-alpha.9
bdk_chain to 0.12.0
bdk_bitcoind_rpc to 0.8.0
bdk_electrum to 0.11.0
bdk_esplora to 0.11.0
bdk_file_store to 0.9.0
bdk_testenv to 0.2.0
2024-04-12 11:43:25 -05:00
Steve Myers
358e842dcd
Merge bitcoindevkit/bdk#1177: Upgrade bitcoin/miniscript dependencies
984c758f964f8fee687d21885b43b0b4705f318c Upgrade miniscript/bitcoin dependency (Tobin C. Harding)

Pull request description:

  Upgrade:

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

  Fix: #1196

ACKs for top commit:
  ValuedMammal:
    ACK 984c758f964f8fee687d21885b43b0b4705f318c
  notmandatory:
    ACK 984c758f964f8fee687d21885b43b0b4705f318c
  oleonardolima:
    ACK 984c758f964f8fee687d21885b43b0b4705f318c
  storopoli:
    ACK 984c758f964f8fee687d21885b43b0b4705f318c

Tree-SHA512: d64d530e93cc36688ba07d3677d5c1689b61f246f05d08092bbf86ddbba8a5ec49648e6825b950ef17729dc064da50d50b793475a288862a0461976876807170
2024-04-12 10:58:19 -05:00
志宇
c7f87b50e4
Merge bitcoindevkit/bdk#1397: Introduce proptesting, starting with CheckPoint::range
446b045161ebad3fbdf0ea96e8ff6f9da8ad212c test(chain): introduce proptest for `CheckPoint::range` (志宇)

Pull request description:

  ### Description

  This is based on #1369. It made sense for me to introduce the `CheckPoint::range` test as a proptest. I think we should also start introducing it for other methods too.

  ### Changelog notice

  * Added proptest for `CheckPoint::range`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

Top commit has no ACKs.

Tree-SHA512: 2d8aad5a1ad152413fbc716fed4a47ad621e723928c5331728da2fbade995ebd677acfa05d2e7639d74d0f66e0971c72582d9cd562ea008b012774057b480d62
2024-04-12 13:29:44 +08:00
志宇
446b045161
test(chain): introduce proptest for CheckPoint::range
Ensure that `CheckPoint::range` returns expected values by comparing
against values returned from a primitive approach.

I think it is a good idea to start writing proptests for this crate.
2024-04-11 21:43:21 +08:00
志宇
62619d3a4a
Merge bitcoindevkit/bdk#1385: Fix last seen unconfirmed
a2a64ffb6e92baf46a912f36294f3f4f521a528a fix(electrum)!: Remove `seen_at` param from `into_tx_graph` (valued mammal)
37fca35ddede6cbc9d9428a2722eff82a405b1b2 feat(tx_graph): Add method update_last_seen_unconfirmed (valued mammal)

Pull request description:

  A method `update_last_seen_unconfirmed` is added for `TxGraph` that allows inserting a `seen_at` time for all unanchored transactions.

  fixes #1336

  ### Changelog notice

  Changed:
  - Methods `into_tx_graph` and `into_confirmation_time_tx_graph`for `RelevantTxids` are changed to no longer accept a `seen_at` parameter.

  Added:
  - Added method `update_last_seen_unconfirmed` for `TxGraph`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK a2a64ffb6e92baf46a912f36294f3f4f521a528a

Tree-SHA512: 9011e63314b0e3ffcd50dbf5024f82b365bab1cc834c0455d7410b682338339ed5284caa721ffc267c65fa26d35ff6ee86cde6052e82a6a79768547fbb7a45eb
2024-04-11 21:33:14 +08: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
valued mammal
a2a64ffb6e
fix(electrum)!: Remove seen_at param from into_tx_graph
and `into_confirmation_time_tx_graph`, since now it makes
sense to use `TxGraph::update_last_seen_unconfirmed`.

Also, use `update_last_seen_unconfirmed` in examples for
electrum/esplora. We show how to update the last seen
time for transactions by calling `update_last_seen_unconfirmed`
on the graph update returned from a blockchain source, passing
in the current time, before applying it to another `TxGraph`.
2024-04-06 12:04:27 -04:00
valued mammal
37fca35dde
feat(tx_graph): Add method update_last_seen_unconfirmed
That accepts a `u64` as param representing the latest timestamp
and internally calls `insert_seen_at` for all transactions in
graph that aren't yet anchored in a confirmed block.
2024-04-06 11:50:37 -04:00
志宇
53791eb6c5
Merge bitcoindevkit/bdk#1369: feat(chain): add get and range methods to CheckPoint
53942cced492138174638a8087b08f643a8d41ad chore(chain)!: rm `From<LocalChain> for BTreeMap<u32, BlockHash>` (志宇)
2d1d95a6850a5bab9c5bf369a498fe090852cd93 feat(chain): impl `PartialEq` on `CheckPoint` (志宇)
9a62d56900a33a519dd0165ccdb91711917772f3 feat(chain): add `get` and `range` methods to `CheckPoint` (志宇)

Pull request description:

  Partially fixes #1354

  ### Description

  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.

  ### Notes to the reviewers

  Please refer to the conversation in #1354 for more details. In summary, both `TxGraph::missing_heights` and `tx_graph::ChangeSet::missing_heights_from` are problematic in their own ways. Additionally, it's a better API for chain sources if we only need to lock our receiving structures twice (once to obtain initial state and once for applying the update). Instead of relying on methods such as `EsploraExt::update_local_chain` to get relevant checkpoints, we can use these query methods instead. This allows up to get rid of `::missing_heights`-esc methods and remove the need to lock receiving structures in the middle of the sync.

  ### Changelog notice

  * Added `get` and `range` methods to `CheckPoint` (and in turn, `LocalChain`). This simulates an API where we have implemented a skip list of checkpoints (to implement in the future). This is a better API because we can query for any height or height range with just a checkpoint tip instead of relying on a separate checkpoint index (which needs to live in `LocalChain`).
  * Changed `LocalChain` to have a faster `Eq` implementation. We now maintain an xor value of all checkpoint block hashes. We compare this xor value to determine whether two chains are equal.
  * Added `PartialEq` implementation for `CheckPoint` and `local_chain::Update`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  LLFourn:
    ACK 53942cced492138174638a8087b08f643a8d41ad

Tree-SHA512: 90ef8047fe1265daa54c9dfe8a8c520685c898a50d18efd6e803707fcb529d0790d20373c9e439b9c7ff301db32b47453020cae7db4da2ea64eba895aa047f30
2024-04-06 10:23:46 +08:00
志宇
53942cced4
chore(chain)!: rm From<LocalChain> for BTreeMap<u32, BlockHash>
I don't think this was ever used. The only possible usecase I can think
of is for tests, but I don't think that is a strong enough incentive for
us to keep this.
2024-04-05 16:36:00 +08:00
志宇
2d1d95a685
feat(chain): impl PartialEq on CheckPoint
We impl `PartialEq` on `CheckPoint` instead of directly on `LocalChain`.
We also made the implementation more efficient.
2024-04-05 16:36:00 +08: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
志宇
2bb654077d
Merge bitcoindevkit/bdk#1345: fix: remove deprecated max_satisfaction_weight
798ed8ced25156049126645435127a22245e916f fix: remove deprecated `max_satisfaction_weight (Jose Storopoli)

Pull request description:

  ### Description
  Continuation of #1115.
  Closes #1036.

  * Change deprecated `max_satisfaction_weight` to `max_weight_to_satisfy`
  * Remove `#[allow(deprecated)]` flags

  ### Notes to the reviewers

  I've changed all `max_satisfaction_weight()` to `max_weight_to_satisfy()` in `Wallet.get_available_utxo()` and `Wallet.build_fee_bump()`. Checking the docs on the `miniscript` crate for `max_weight_to_satisfy` has the following note:

  We are testing if the underlying descriptor `is.segwit()` or `.is_taproot`,
  then adding 4WU if true or leaving as it is otherwise.

  Another thing, we are not testing in BDK tests for legacy (pre-segwit) descriptors.
  Should I also add them to this PR?

  ### Changelog notice
  ### Fixed
  Replace the deprecated `max_satisfaction_weight` from `rust-miniscript` to `max_weight_to_satisfy`.

  ### Checklists
  #### All Submissions:
  * [x]  I've signed all my commits
  * [x]  I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x]  I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:
  * [ ]  This pull request breaks the existing API
  * [ ]  I've added tests to reproduce the issue which are now passing
  * [x]  I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK 798ed8ced25156049126645435127a22245e916f

Tree-SHA512: 60babecee13c24915348ddb64894127a76a59d9421d52ea37acc714913685d57cc2be1904f9d0508078dd1db1f7d7dad83a734af5ee981801ca87de2e9984429
2024-04-02 19:21:51 +08:00
志宇
19304c13ec
Merge bitcoindevkit/bdk#1373: Wrap transactions as Arc<Transaction> in TxGraph
8ab58af093ff295b86c3f8189aa96dea313092c4 feat(chain)!: wrap `TxGraph` txs with `Arc` (志宇)

Pull request description:

  ### Description

  This PR makes `TxGraph` store transactions as `Arc<Transaction>`.

  `Arc<Transaction>` can be shared between the chain-source and receiving structures. This allows the chain-source to keep the already-fetched transactions (save bandwith) and have a shared pointer to the transaction (save memory).

  Our current logic to avoid re-fetching transactions is to refer back to the receiving structures. However, this means an additional round of locking our receiving structures.

  ### Notes to the reviewers

  This will make more sense once I update the esplora/electrum chain sources to make use of both #1369 and this PR. The result would be chain sources which would only require locking the receiving structures twice (once for initiating the update, and once for applying the update).

  ### Changelog notice

  * Changed `TxGraph` to store transactions as `Arc<Transaction>`. This allows chain-sources to cheaply keep a copy of already-fetched transactions.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  LLFourn:
    ACK 8ab58af093ff295b86c3f8189aa96dea313092c4
  notmandatory:
    ACK 8ab58af093ff295b86c3f8189aa96dea313092c4

Tree-SHA512: 81d7ad35fed7f253a3b902f09a41aaef2877f6201d4f6e78318741bf00e4b898a8000d878ffcbfe75701094ce3e9021bd718b190a655331a9e11f0ad66bdb02f
2024-03-31 17:50:31 +08:00
Jose Storopoli
798ed8ced2
fix: remove deprecated `max_satisfaction_weight
- Change deprecated `max_satisfaction_weight` to `max_weight_to_satisfy`
- Remove `#[allow(deprecated)]` flags
- updates the calculations in TXIN_BASE_WEIGHT and P2WPKH_SATISFACTION_SIZE

Update crates/bdk/src/wallet/coin_selection.rs

Co-authored-by: ValuedMammal <valuedmammal@protonmail.com>
2024-03-29 06:27:39 -03:00
Steve Myers
b5557dce70
Merge bitcoindevkit/bdk#1389: Bump bdk version to 1.0.0-alpha.8
7b97c956c7abdd6415ccdda79c26cf212e15cb4e Bump bdk version to 1.0.0-alpha.8 (Steve Myers)

Pull request description:

  ### Description

  Bump versions:

  bdk version to 1.0.0-alpha.8
  bdk_bitcoind_rpc to 0.7.0
  bdk_electrum to 0.10.0
  bdk_esplora to 0.10.0
  bdk_file_store to 0.8.0
  bdk_hwi to 0.2.0

  fixes #1388

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 7b97c956c7abdd6415ccdda79c26cf212e15cb4e

Tree-SHA512: 32286f33f8fe595f79ef6b9450c7906dee15b5c93ad62435025f4fb1446f9ee8c6147190d628b95e21b8f36c02ca3f8b86b8a5e8cab3835773750967f9e36489
2024-03-27 11:20:57 -05:00
Steve Myers
7b97c956c7
Bump bdk version to 1.0.0-alpha.8
bdk_bitcoind_rpc to 0.7.0
bdk_electrum to 0.10.0
bdk_esplora to 0.10.0
bdk_file_store to 0.8.0
bdk_hwi to 0.2.0
2024-03-27 15:13:57 +08:00
志宇
e5aa4fe9e6
Merge bitcoindevkit/bdk#1391: Fix cargo manifest for bdk_testenv
25800139124a37608c9da0a6ad76c22795f110d6 chore(testenv): fix cargo manifest (志宇)

Pull request description:

  ### Description

  This will make the `bdk_testenv` crate actually publishable.

  ### Changelog notice

  * Fix cargo manifest of `bdk_testenv`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  LLFourn:
    ACK 25800139124a37608c9da0a6ad76c22795f110d6

Tree-SHA512: 52707450473713490cb1115af06747dc4d6f78cf4bf877cd3a246064af11786b5a89829731e911ffba19a71db9b19a60ad5b12f20871d57b296427761707d826
2024-03-27 15:12:52 +08:00
志宇
2580013912
chore(testenv): fix cargo manifest 2024-03-27 14:58:46 +08:00
Steve Myers
380bc4025a
Merge bitcoindevkit/bdk#1351: fix: define and document stop_gap
7c1861aab9a76f2ba4a2ae372a16c9669a33f5de fix: define and document `stop_gap` (Jose Storopoli)

Pull request description:

  ### Description

  - changes the code implementation to "the maximum number of consecutive unused addresses" in esplora async and blocking extensions.
  - for all purposes treats `stop_gap = 0` as `stop_gap = 1`.
  - renames `past_gap_limit` to `gap_limit_reached` to indicate we want to break once the gap limit is reached and not go further in `full_scan`, as suggested in https://github.com/bitcoindevkit/bdk/issues/1227#issuecomment-1859040463
  - change the tests according to the new implementation.
  - add notes on what `stop_gap` means and links to convergent definition in other Bitcoin-related software.

  Closes #1227.

  ### Notes to the reviewers

  We can iterate over the wording and presentation of the `stop_gap` definition
  and details.

  ### Changelog notice

  - BREAKING: change `stop_gap` definition and effects in `full_scan`
    to reflect the common definitions in most Bitcoin-related software.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 7c1861aab9a76f2ba4a2ae372a16c9669a33f5de

Tree-SHA512: d9bc5f8ebace47fa33f023ceddb3df5629ad3e7fa130a407311a0303ac59810e6527254efb9075f9e87bf37bec8655c4726eb9cb99f6b038fbeb742f79e995c0
2024-03-26 19:03:04 -05:00
Jose Storopoli
7c1861aab9
fix: define and document stop_gap
- changes the code implementation to "the maximum number of consecutive unused addresses"
  in esplora async and blocking extjensions.
- treat `stop_gap = 0` as `stop_gap = 1` for all purposes.
- renames `past_gap_limit` to `gap_limit_reached` to indicate we want to break once the gap
  limit is reached and not go further in `full_scan`, as suggested in
  https://github.com/bitcoindevkit/bdk/issues/1227#issuecomment-1859040463
- change the tests according to the new implementation.
- add notes on what `stop_gap` means and links to convergent definition in other
  Bitcoin-related software.

Closes #1227
2024-03-26 12:44:03 -03: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
志宇
80e190b3e7
Merge bitcoindevkit/bdk#1171: chore: extract TestEnv into separate crate
7c9ba3cfc855dc0845476fe923dac4e47cb5c06a chore(electrum,testenv): move `test_reorg_is_detected_in_electrsd` (志宇)
2462e9041599f395673f9b14f0b618877832f099 chore(esplora): rm custom WASM target spec test dependency (志宇)
04d0ab5a978fbfd45a5c795f9142ff4a9ba29ee3 test(electrum): added scan and reorg tests Added scan and reorg tests to check electrum functionality using `TestEnv`. (Wei Chen)
4edf533b678cb21f4c29ded22692e607ff75e2cd chore: extract `TestEnv` into separate crate `TestEnv` is extracted into its own crate to serve as a framework for testing other block explorer APIs. (Wei Chen)
6e648fd5afa188290b05f8e050ba69fe5f8b80e4 chore: update MSRV dependency for nightly docs (Wei Chen)

Pull request description:

  ### Description

  `TestEnv` is extracted into its own crate with `electrsd` support added so that `TestEnv` can also serve `esplora` and `electrum`.
  The tests in the `esplora` crate have also been updated to use `TestEnv`.

  The `tx_can_become_unconfirmed_after_reorg()` test in `test_electrum` suggests that the electrum issue where a reorged tx would be stuck at confirmed does not exist anymore.

  ### Notes to the reviewers

  The code for `tx_can_become_unconfirmed_after_reorg()` was adapted from the same test in `bitcoind_rpc/test_emitter`. This electrum version of the test requires extra review, as I am uncertain if I used the API efficiently.

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 7c9ba3cfc855dc0845476fe923dac4e47cb5c06a

Tree-SHA512: 36c6501e477abb7ae68073b6f4776f1f69f8964010ab758aa3677aae96df10f2cb632421872cacd73b37123d6db8a9dbefb5b6416e0dd524b712bf3fc56b7139
2024-03-23 18:37:38 +08:00
志宇
7c9ba3cfc8
chore(electrum,testenv): move test_reorg_is_detected_in_electrsd 2024-03-23 18:28:49 +08:00
志宇
2462e90415
chore(esplora): rm custom WASM target spec test dependency
None of the `bdk_esplora` tests can run under WASM anyway since we
depend on `electrsd`.
2024-03-23 17:57:27 +08:00
Wei Chen
04d0ab5a97
test(electrum): added scan and reorg tests
Added scan and reorg tests to check electrum functionality using
`TestEnv`.
2024-03-22 17:59:35 +08:00
Wei Chen
4edf533b67
chore: extract TestEnv into separate crate
`TestEnv` is extracted into its own crate to serve as a framework
for testing other block explorer APIs.
2024-03-22 17:59:35 +08:00
Wei Chen
6e648fd5af
chore: update MSRV dependency for nightly docs 2024-03-22 17:59:35 +08:00
志宇
a837cd349b
Merge bitcoindevkit/bdk#1378: Update bdk README
06d7dc5c3a890f0a141de4cf6f421fe766d99ec3 doc(bdk): Update bdk README (vmammal)

Pull request description:

  fixes #1044

  ### Notes

  The code snippet is a compile fail because variables `txout` and `outpoint` are not initialized. Any other suggestions are welcome.

  There is still some old commented code in the file that's probably not needed unless we want to provide another example snippet, say for getting new address info.

  * [x] Fix broken links
  * [x] Use a new unused tprv
  * [ ] Try to make persistence example make sense, or maybe just do away with it

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 06d7dc5c3a890f0a141de4cf6f421fe766d99ec3

Tree-SHA512: 09a671bc6bea574d7a4b42b64718380ee71a0c5d36c6b7ca1dc19a2c567de510b27ccc91fe05e7178bf31c562db66bc64f660415de5bb2f32f369b13c44ad3d2
2024-03-22 15:10:21 +08:00
志宇
0eb1ac2bcb
Merge bitcoindevkit/bdk#1310: Remove extra taproot fields when finalizing PSBT
5840ce473e430de4c4e3698734e9667cc476fee4 fix(bdk): Remove extra taproot fields when finalizing Psbt (vmammal)
8c78a42163dee06b640f46d74255df37dbc53873 test(psbt): Fixup test_psbt_multiple_internalkey_signers (vmammal)

Pull request description:

  We currently allow removing `partial_sigs` from a finalized PSBT, which is relevant to non-taproot inputs, however taproot related PSBT fields were left in place despite the recommendation of BIP371 to remove them once the `final_script_witness` is constructed. This can cause confusion for parsers that encounter extra taproot metadata in an already satisfied input.

  Fix this by introducing a new member to SignOptions `remove_taproot_extras`, which when true will remove extra taproot related data from a PSBT upon successful finalization. This change makes removal of all taproot extras the default but configurable.

  fixes #1243

  ### Notes to the reviewers

  If there's a better or more descriptive name for `remove_taproot_extras`, I'm open to changing it.

  ### Changelog notice

  Fixed an [issue](https://github.com/bitcoindevkit/bdk/issues/1243) finalizing taproot inputs following BIP371

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  <!-- * [ ] This pull request breaks the existing API -->
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK 5840ce473e430de4c4e3698734e9667cc476fee4

Tree-SHA512: 69f022c6f736500590e36880dd2c845321464f89af6a2c67987d1c520f70a298328363cade0f55f270c4e7169e740bd4ada752ec2c75afa02b6a5a851f9030c3
2024-03-22 12:39:10 +08:00
志宇
6e8a4a8966
Merge bitcoindevkit/bdk#1216: Migrate to bitcoin::FeeRate
475a77219a6e7649c91b7cfeb44871cee9d0f374 refactor(bdk)!: Remove trait Vbytes (vmammal)
0d64beb040e885d653adb901dc49482f9daafddf chore: organize some imports (vmammal)
89608ddd0fd582d011f7b7ae8bbeb63dee6a3b99 refactor(bdk): display CreateTxError::FeeRateTooLow in sat/vb (vmammal)
09bd86e2d82020d5f4079c5d234888a9eed50489 test(bdk): initialize all feerates from `u64` (vmammal)
004957dc2969171b7a37ce92d2cdb0e8f22b6da5 refactor(bdk)!: drop FeeRate from bdk::types (vmammal)

Pull request description:

  ### Description

  This follows a similar approach to #1141 namely to remove `FeeRate` from `bdk::types` and instead defer to the upstream implementation for all fee rates. The idea is that making the switch allows BDK to benefit from a higher level abstraction, leaving the implementation details largely hidden.

  As noted in #774, we should avoid extraneous conversions that can result in deviations in estimated transaction size and calculated fee amounts, etc. This would happen for example whenever calling a method like `FeeRate::to_sat_per_vb_ceil`. The only exception I would make is if we must return a fee rate error to the user, we might prefer to display it in the more familiar sats/vb, but this would only be useful if the rate can be expressed as a float.

  ### Notes to the reviewers

  `bitcoin::FeeRate` is an integer whose native unit is sats per kilo-weight unit. In order to facilitate the change, a helper method `feerate_unchecked` is added and used only in wallet tests and psbt tests as necessary to convert existing fee rates to the new type. It's "unchecked" in the sense that we're not checking for integer overflow, because it's assumed we're passing a valid fee rate in a unit test.

  Potential follow-ups can include:
  - [x] Constructing a proper `FeeRate` from a `u64` in all unit tests, and thus obviating the need for the helper `feerate_unchecked` going forward.
  - [x] Remove trait `Vbytes`.
  - Consider adding an extra check that the argument to `TxBuilder::drain_to` is within "standard" size limits.
  - Consider refactoring `coin_selection::select_sorted_utxos` to be efficient and readable.

  closes #1136

  ### Changelog notice

  - Removed `FeeRate` type. All fee rates are now rust-bitcoin [`FeeRate`](https://docs.rs/bitcoin/latest/bitcoin/blockdata/fee_rate/struct.FeeRate.html).
  - Removed trait `Vbytes`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 475a77219a6e7649c91b7cfeb44871cee9d0f374

Tree-SHA512: 511dab8aa7a65d2b15b160cb4feb96964e8401bb04cda4ef0f0244524bf23a575b3739783a14b90d2dccc984b3f30f5dabfb0a890ffe7c897c2dc23ba301bcaf
2024-03-22 12:34:25 +08:00
vmammal
475a77219a
refactor(bdk)!: Remove trait Vbytes
The only place this is being used is a unit test that is
easily refactored. For size conversions prefer methods
on e.g. `Weight`.
2024-03-21 23:32:00 -04:00
vmammal
0d64beb040
chore: organize some imports 2024-03-21 23:32:00 -04:00
vmammal
89608ddd0f
refactor(bdk): display CreateTxError::FeeRateTooLow in sat/vb
Also modify a unit test `test_bump_fee_low_fee_rate` to
additionally assert the expected error message
2024-03-21 23:32:00 -04:00
vmammal
09bd86e2d8
test(bdk): initialize all feerates from u64
This makes the helper `feerate_unchecked` now redundant but
still usable.
2024-03-21 23:32:00 -04:00
vmammal
004957dc29
refactor(bdk)!: drop FeeRate from bdk::types
Adopt `bitcoin::FeeRate` throughout
2024-03-21 23:32:00 -04:00
Lloyd Fournier
fc637a7bcc
Merge pull request #1384 from evanlinjin/file_store_clippy_happy
Explicitly state that we truncate file for `create_new`
2024-03-22 11:48:34 +11:00
志宇
ec1c5f4cf8
chore(file_store): explicitly state that we truncate file for create_new
This makes clippy happy.
2024-03-22 07:41:17 +08:00
vmammal
06d7dc5c3a
doc(bdk): Update bdk README 2024-03-14 23:00:55 -04:00
Steve Myers
c01983d02a
Merge bitcoindevkit/bdk#1365: Bump bdk version to 1.0.0-alpha.7
fef70d5e8fe1903aa532897e1093b1b972e08055 Bump version to 1.0.0-alpha.7 (Steve Myers)

Pull request description:

  Bump bdk version to 1.0.0-alpha.7

  bdk_chain to 0.11.0
  bdk_bitcoind_rpc to 0.6.0
  bdk_electrum to 0.9.0
  bdk_esplora to 0.9.0
  bdk_file_store to 0.7.0

  fixes #1364

ACKs for top commit:
  danielabrozzoni:
    ACK fef70d5e8fe1903aa532897e1093b1b972e08055

Tree-SHA512: 94ba5cad102d89122897436390d4ababf49a19cf97f4118c0804b3288955dd591b543d4605268dcc1967f34e523a0c4058b06f9cd74c7e8c4394e902abc17022
2024-03-04 21:46:47 -06:00
Steve Myers
fef70d5e8f
Bump version to 1.0.0-alpha.7
bdk_chain to 0.11.0
bdk_bitcoind_rpc to 0.6.0
bdk_electrum to 0.9.0
bdk_esplora to 0.9.0
bdk_file_store to 0.7.0
2024-03-02 11:05:30 -06:00
Steve Myers
c3544c9b8c
Merge bitcoindevkit/bdk#1349: Fix KeychainTxOutIndex::lookahead_to_target
b290b2950221578d73c3194a1accfd080f83631a test(chain): change test case comments to docstring (志宇)
c151d8fd230fb87f27aadb965157f94f01f021a2 fix(chain): `KeychainTxOutIndex::lookahead_to_target` (志宇)

Pull request description:

  ### Description

  This method was not used (so it was untested) and it was not working. This fixes it.

  The old implementation used `.next_store_index` which returned the keychain's last index stored in `.inner` (which include lookahead spks). This is WRONG because `.replenish_lookahead` needs the difference from last revealed.

  ### Changelog notice

  Fix `KeychainTxOutIndex::lookahead_to_target`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] I've added tests to reproduce the issue which are now passing

ACKs for top commit:
  notmandatory:
    ACK b290b2950221578d73c3194a1accfd080f83631a

Tree-SHA512: af50c6af18b6b57494cfa37f89b0236674fa331091d791e858f67b7d0b3a1e4e11e7422029bd6a2dc1c795914cdf6d592a14b42a62ca7c7c475ba6ed37182539
2024-03-02 10:43:05 -06:00
vmammal
5840ce473e
fix(bdk): Remove extra taproot fields when finalizing Psbt
We currently allow removing `partial_sigs` from a finalized Psbt,
which is relevant to non-taproot inputs, however taproot related Psbt
fields were left in place despite the recommendation of BIP371 to remove
them once the `final_script_witness` is constructed. This can cause
confusion for parsers that encounter extra taproot metadata in an
already satisfied input.

Fix this by introducing a new member to SignOptions
`remove_taproot_extras`, which when true will remove extra taproot
related data from a Psbt upon successful finalization. This change
makes removal of all taproot extras the default but configurable.

test(wallet): Add test
`test_taproot_remove_tapfields_after_finalize_sign_option`
that checks various fields have been cleared for taproot
Psbt `Input`s and `Output`s according to BIP371.
2024-02-28 17:24:09 -05:00
志宇
b290b29502
test(chain): change test case comments to docstring 2024-02-28 05:47:25 -03:00
vmammal
8c78a42163
test(psbt): Fixup test_psbt_multiple_internalkey_signers
to verify the signature of the input and ensure the right internal
key is used to sign. This fixes a shortcoming of a previous
version of the test that relied on the result of `finalize_psbt`
but would have erroneously allowed signing with the wrong key.
2024-02-23 11:19:47 -03:00
Daniela Brozzoni
d77a7f2ff1
Merge bitcoindevkit/bdk#1344: tx_builder: Relax generic constraints on TxBuilder
2efa299d0486e0b08376a062e86c6ca8e03916da tx_builder: Relax generic constraints on TxBuilder (Steven Roose)

Pull request description:

  Closes https://github.com/bitcoindevkit/bdk/issues/1312

ACKs for top commit:
  danielabrozzoni:
    ACK 2efa299d0486e0b08376a062e86c6ca8e03916da

Tree-SHA512: 6bfe052c22697eb910cf1f3d453e89f4432159fa017b38532d097cdc07b7a7c3b986be658b81e51acdb54cab999345ab463184e80c8eacefc73d77748c018992
2024-02-22 16:32:42 +01:00
Steve Myers
3d44ffaef2
Merge bitcoindevkit/bdk#1357: ci: Remove jobserver pin
2647aff4bc030e3b63287d353fb6293ab2f1442c ci: Remove jobserver pin (Daniela Brozzoni)

Pull request description:

ACKs for top commit:
  evanlinjin:
    ACK 2647aff4bc030e3b63287d353fb6293ab2f1442c

Tree-SHA512: bb3821c44a1d4fb7a84b8e548b9545c74b4ae84feca4d434791c041618dc9a2f03d8c3a64183844fb5b19dfbfa1c19716191e9810d443d6ddc449f171317a20e
2024-02-21 18:45:44 -06:00
Steven Roose
2efa299d04
tx_builder: Relax generic constraints on TxBuilder 2024-02-21 12:47:56 +00:00
Daniela Brozzoni
2647aff4bc
ci: Remove jobserver pin
It is not needed anymore. Discovered in #1344
2024-02-21 13:24:31 +01:00
志宇
c151d8fd23
fix(chain): KeychainTxOutIndex::lookahead_to_target 2024-02-17 23:36:02 +08:00
志宇
2c324d3759
Merge bitcoindevkit/bdk#1325: Add map_anchors for TxGraph
5489f905a434ecc06867603c7c421e3e50d993ca feat(chain): add `map_anchors` for `TxGraph` and `ChangeSet` (Antonio Yang)
022d5a21cff6c46fb869f8fd538b4026e531ee57 test(chain) use `Anchor` generic on `init_graph` (Antonio Yang)

Pull request description:

  ### Description
  Fix #1295

  ### Checklists
  #### All Submissions:
  * [X] I've signed all my commits
  * [X] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [X] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK 5489f905a434ecc06867603c7c421e3e50d993ca
  LLFourn:
    ACK 5489f905a434ecc06867603c7c421e3e50d993ca

Tree-SHA512: c8327f2e7035a46208eb32c6da1f9f0bc3e8625168450c5b0b39f695268e42b0b9053b6eb97805b116328195d77af7ca9edb1f12206c50513fbe295dded542e7
2024-02-17 02:30:06 +08:00
Steve Myers
50c549b5ac
Merge bitcoindevkit/bdk#1347: Bump bdk version to 1.0.0-alpha.6
83798390108ef37443dbe2d6ec0d35a346e69957 Bump version to 1.0.0-alpha.6 (Steve Myers)

Pull request description:

  ### Description

  Fixes #1343

  Bump bdk version to 1.0.0-alpha.6, also bump:

  bdk_chain to 0.10.0
  bdk_bitcoind_rpc to 0.5.0
  bdk_electrum to 0.8.0
  bdk_esplora to 0.8.0
  bdk_file_store to 0.6.0

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    utACK 83798390108ef37443dbe2d6ec0d35a346e69957

Tree-SHA512: b16a8f88ab66ed78d6f6402d60acfa79b2371a12580a277f9bb3d3df212fb608a8305b6f5082bb280b9a18e209c70be0db38c893fff2f5c1f6085a99e3819479
2024-02-15 11:25:40 -06:00
Steve Myers
8379839010
Bump version to 1.0.0-alpha.6
bdk_chain to 0.10.0
bdk_bitcoind_rpc to 0.5.0
bdk_electrum to 0.8.0
bdk_esplora to 0.8.0
bdk_file_store to 0.6.0
2024-02-15 10:23:05 -06:00
Antonio Yang
5489f905a4
feat(chain): add map_anchors for TxGraph and ChangeSet 2024-02-13 21:29:12 +08:00
志宇
420e929463
Merge bitcoindevkit/bdk#1335: fix(chain): tx_graph::ChangeSet::is_empty
13ab5a835d59341e387fbbefec12fe4f48e5f3c8 chore(chain): Improve TxGraph::ChangeSet docs (LLFourn)
dbbd51424284a960a95c3801b02dc1973322725f fix(chain)!: rm duplicate `is_empty` method in tx graph changeset (志宇)
ae00e1ee7b95c622fc3992c0804dd4b4517efc7b fix(chain): tx_graph::ChangeSet::is_empty (LLFourn)

Pull request description:

  🙈

  ### Changelog notice

  - Fix bug in `tx_graph::ChangeSet::is_empty` where is returns true even when it wasn't empty

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing

ACKs for top commit:
  LLFourn:
    Self-ACK: 13ab5a835d59341e387fbbefec12fe4f48e5f3c8
  evanlinjin:
    ACK 13ab5a835d59341e387fbbefec12fe4f48e5f3c8

Tree-SHA512: b9f1f17fd2ed0f8e2337a8033e1cbd3e9f15b1ad4b32da3f0eb73a30913d6798e7a08d6b297d93bd08c2e1c388226e97648650ac636846b2c7aa95c3bcefbcfd
2024-02-11 17:49:21 +08:00
LLFourn
13ab5a835d
chore(chain): Improve TxGraph::ChangeSet docs 2024-02-10 09:13:08 +11:00
志宇
728e26f223
Merge bitcoindevkit/bdk#1334: Reorder fields in ConfirmationHeightAnchor fields so Ord DWIM
adc95137ac2e52f4d45c4ec778703001c95a362f fix(chain)! Re-order fields in anchors so Ord DWIM (LLFourn)

Pull request description:

  Something that is confirmed more recently should be greater than something that is confirmed earlier regardless of anchor.

ACKs for top commit:
  evanlinjin:
    ACK adc95137ac2e52f4d45c4ec778703001c95a362f

Tree-SHA512: 9a588b64afc7e20b35a9abb8c25b8b82858c0f89886320c0fc91f6c61592fccfa7fbaa3020a393b1d5fd79f71302a388255b69cb3726a38a0f2fdab8bb93769c
2024-02-10 04:17:30 +08:00
志宇
dbbd514242
fix(chain)!: rm duplicate is_empty method in tx graph changeset 2024-02-10 03:35:48 +08:00
LLFourn
ae00e1ee7b
fix(chain): tx_graph::ChangeSet::is_empty 2024-02-09 20:03:57 +11:00
LLFourn
adc95137ac
fix(chain)! Re-order fields in anchors so Ord DWIM 2024-02-09 13:48:19 +11:00
Antonio Yang
022d5a21cf
test(chain) use Anchor generic on init_graph 2024-02-08 15:45:42 +08:00
Daniela Brozzoni
7aca88474a
Merge bitcoindevkit/bdk#1308: feat(esplora): include previous TxOuts for fee calculation
552f11cb5f66a9366dbc05c801fcae043ebe5b82 feat(esplora): include previous `TxOut`s for fee calculation The previous `TxOut` for transactions received from an external wallet are added as floating `TxOut`s to `TxGraph` to allow for fee calculation. (Wei Chen)

Pull request description:

  ### Description

  Partially implements #1265.

  The previous `TxOut` for transactions received from an external wallet are added as floating `TxOut`s to `TxGraph` to allow for fee calculation.

  ### Notes to the reviewers

  Currently only the `esplora` portion of #1265 has been implemented.
  The `electrum` portion will potentially be done in a new PR, as discussed on the 1/30/24 Lib call.

  ### Checklists

  #### To Do:
  * [ ] Implement `electrum` portion of #1265.

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  evanlinjin:
    re-ACK 552f11cb5f66a9366dbc05c801fcae043ebe5b82
  danielabrozzoni:
    ACK 552f11cb5f66a9366dbc05c801fcae043ebe5b82

Tree-SHA512: 752a24ebd0b9ad7952c1b093ecb251473e346c77b860c1a80c73418130189227405a0f0d7652967cf8c7b89994e8c37df96cd52b52b6daff9cc8c88b5194069a
2024-02-05 12:44:58 +01:00
Daniela Brozzoni
b3278a4c29
Merge bitcoindevkit/bdk#1316: tx_builder: Support setting explicit nSequence for foreign inputs
9bb39a3a3fcdebeec53a8a771091954c845db7a5 Avoid a wildcard match in tx construction (Steven Roose)
9e098a5b6d0802eb39f3e200605b8576c77030eb tx_builder: Support setting explicit nSequence for foreign inputs (Steven Roose)

Pull request description:

  Fixes https://github.com/bitcoindevkit/bdk/issues/1315.

ACKs for top commit:
  evanlinjin:
    ACK 9bb39a3a3fcdebeec53a8a771091954c845db7a5
  danielabrozzoni:
    utACK 9bb39a3a3fcdebeec53a8a771091954c845db7a5

Tree-SHA512: 42c96a58a762fa8737402ebd0132ce20ce0359c996cee9feeecb0b84e6fb73305be1aec9429fb97ba932486f0b35ac5caed7b43656456c5fb053e55330a12d47
2024-02-05 12:36:11 +01:00
Wei Chen
552f11cb5f
feat(esplora): include previous TxOuts for fee calculation
The previous `TxOut` for transactions received from an external
wallet are added as floating `TxOut`s to `TxGraph` to allow for
fee calculation.
2024-02-05 17:01:11 +08:00
Steve Myers
d8f74dc5e4
Merge bitcoindevkit/bdk#1319: chore: typos
8d93fad778565f44cbcc053c7f51fbc27bebf99a chore: typos (Jose Storopoli)

Pull request description:

  More caught on by Nix CI in #1257.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK 8d93fad778565f44cbcc053c7f51fbc27bebf99a
  notmandatory:
    ACK 8d93fad778565f44cbcc053c7f51fbc27bebf99a

Tree-SHA512: 28e0316d457658266b2af1de76b114f87ce7485e386ddecd805dda1266a4e8645612c0fa6bc921c58daa4886558b32b538cccbb1644c96c3bab638dd7c42ee2b
2024-02-04 13:28:49 -06:00
Jose Storopoli
8d93fad778
chore: typos
More caught on by Nix CI in #1257.
2024-02-04 06:13:40 -03:00
Steven Roose
9bb39a3a3f
Avoid a wildcard match in tx construction 2024-02-02 02:03:55 +00:00
Steven Roose
9e098a5b6d
tx_builder: Support setting explicit nSequence for foreign inputs 2024-02-02 02:03:53 +00:00
志宇
c6b9ed3b76
Merge bitcoindevkit/bdk#1186: Clean up clippy allows
1c15cb2f9169bb08a4128c183eeeca80fff97ab7 ref(example_cli): Add new struct Init (vmammal)
89a7ddca7f6ed8c65ed0124774f3a868d08faf68 ref(esplora): `Box` a large `esplora_client::Error` (vmammal)
097d818d4c7fff12d72ce0ef10ceb9b575c154e1 ref(wallet): `Wallet::preselect_utxos` now accepts a `&TxParams` (vmammal)
f11d663b7efb98dd72fed903ade8c5e7af0b5a3a ref(psbt): refactor body of `get_utxo_for` to address `clippy::manual_map` (vmammal)
4679ca1df7209d2b356fbb8cbd675f07756d1301 ref(example_cli): add typedefs to reduce type complexity (vmammal)
64a90192d9d49c3df22d2b5f489ba20222fd941a refactor: remove old clippy allow attributes (vmammal)

Pull request description:

  closes #1127

  There are several instances in the code where we allow clippy lints that would otherwise be flagged during regular checks. It would be preferable to minimize the number of "clippy allow" attributes either by fixing the affected areas or setting a specific configuration in `clippy.toml`. In cases where we have to allow a particular lint, it should be documented why the lint doesn't apply.

  For context see https://github.com/bitcoindevkit/bdk/issues/1127#issuecomment-1784256647 as well as the commit message details.

  One area I'm unsure of is whether `Box`ing a large error in 4fc2216 is the right approach. Logically it makes sense to avoid allocating a needlessly heavy `Result`, but I haven't studied the implications or tradeoffs of such a change.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 1c15cb2f9169bb08a4128c183eeeca80fff97ab7

Tree-SHA512: 5fa3796a33678651414e7aad7ef8309b4cbe2a9ab00dce094964b40784edb2f46a44067785d95ea26f4cd88d593420485be94c9b09ac589f632453fbd8c94d85
2024-02-01 01:19:07 +08:00
vmammal
1c15cb2f91
ref(example_cli): Add new struct Init
for holding the items returned from `example_cli::init`
2024-01-31 11:50:41 -05:00
vmammal
89a7ddca7f
ref(esplora): Box a large esplora_client::Error
to address `clippy::result_large_err`. Clippy's default large-error-
threshold is 128. `esplora_client::Error` currently has size 272.
2024-01-31 11:50:41 -05:00
vmammal
097d818d4c
ref(wallet): Wallet::preselect_utxos now accepts a &TxParams
to reduce the number of required function args in order to satisfy
`clippy::too_many_arguments`
2024-01-31 11:50:40 -05:00
vmammal
f11d663b7e
ref(psbt): refactor body of get_utxo_for to address clippy::manual_map 2024-01-31 11:50:40 -05:00
vmammal
4679ca1df7
ref(example_cli): add typedefs to reduce type complexity
- Add typedefs to model the result of functions `planned_utxos`
and `init`

- Add new struct `CreateTxChange` to hold any change info
resulting from `create_tx`

These changes help resolve clippy::type_complexity
2024-01-31 11:50:40 -05:00
vmammal
64a90192d9
refactor: remove old clippy allow attributes
These lints either resolved themselves, or the code has changed such that
they no longer apply, hence they can be removed with no further changes.

`clippy::derivable_impls`
`clippy::needless_collect`
`clippy::almost_swapped`
2024-01-31 11:11:26 -05:00
Steve Myers
ba7624781d
Merge bitcoindevkit/bdk#1307: Bump version to 1.0.0-alpha.5
d597f4c761d10966c12ddaf59f4ed0d9ffdac21b Bump version to 1.0.0-alpha.5 (Steve Myers)

Pull request description:

  ### Description

  Bump version to 1.0.0-alpha.5

  bdk_chain to 0.9.0
  bdk_bitcoind_rpc to 0.4.0
  bdk_electrum to 0.7.0
  bdk_esplora to 0.7.0
  bdk_file_store to 0.5.0

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK d597f4c761d10966c12ddaf59f4ed0d9ffdac21b

Tree-SHA512: 36ba783083441ddd8d209ede35ff46832fd2532f588ddbff0e4e23fb336aff398f8ca612e2bfd5fa214d0f4c14a4dea9147b34724734cc43b752789765e7a447
2024-01-31 10:05:51 -06:00
Steve Myers
d597f4c761
Bump version to 1.0.0-alpha.5
bdk_chain to 0.9.0
bdk_bitcoind_rpc to 0.4.0
bdk_electrum to 0.7.0
bdk_esplora to 0.7.0
bdk_file_store to 0.5.0
2024-01-31 09:23:20 -06:00
Steve Myers
f099b42005
Merge bitcoindevkit/bdk#1306: Implement ElectrumExt for all that implements ElectrumApi
ce8c617c9d562a54728c6cafc0562a66bae56b3e feat(electrum): impl `ElectrumExt` for all that impl `ElectrumApi` (志宇)

Pull request description:

  ### Description

  Implement `ElectrumExt` for all that implements `ElectrumApi`.

  I realized this while looking into #1171.

  2196685cca/crates/electrum/tests/test_electrum.rs (L54-L55)

  Line 55 here should not be necessary.

  ### Changelog notice

  * Changed to implement `ElectrumExt` for all that implements `ElectrumApi`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK ce8c617c9d562a54728c6cafc0562a66bae56b3e

Tree-SHA512: d95193a9a356a0aa3f467db3b8c7bf2cfdf83afd520f5254721912cfe82355de1198256b90323e51ffdb0bf955ff923a9ceb8b4541d4a5ad2331ff0bf26ab937
2024-01-31 09:03:50 -06:00
志宇
ce8c617c9d
feat(electrum): impl ElectrumExt for all that impl ElectrumApi 2024-01-31 22:47:22 +08:00
Steve Myers
8ad52f720f
Merge bitcoindevkit/bdk#1267: Simplify Esplora::update_local_chain and add tests
c5afbaa95d7bc699981d6fe7f9964a41b7587d5c ci: update zstd-sys version to work with MSRV 1.63 (Steve Myers)
929b5ddb0c2e0dc7c346c08888201ac54efab84d refactor(esplora): better variable naming and docs (志宇)
216648bcfd2c622890bf7f50fb2eaa4396c42ed1 chore(esplora): Clarify consistency guarantees (LLFourn)
63fa710319f231f7f28d92cb49b0399f3250c9da fix(esplora): reuse returned height instead of zipping (志宇)
6f824cf325c6c882b00742d814be1d72602f05a6 test(esplora): introduce test cases for `update_local_chain` (志宇)
f05e8502e69a051af9869be6ba5ad9a376b25fc2 feat(esplora): greatly simplify `update_local_chain` (志宇)

Pull request description:

  Fixes #1199

  ### Description

  After a second look at the `update_local_chain` implementations, it was clear that they were over complicated. This PR simplifies the `EsploraExt::update_local_chain` method(s) of the `bdk_esplora` crate and adds a whole bunch of tests.

  ### Notes to the reviewers

  The description of #1199 is very brief, however @danielabrozzoni mentioned about potentially-problematic logic with `ASSUME_FINAL_DEPTH`. The logic was indeed convoluted and it did not need to be that way. This PR removes the need for `ASSUME_FINAL_DEPTH`.

  ### Changelog notice

  Fixed
  - Simplified `EsploraExt::update_local_chain` logic.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  ~* [ ] This pull request breaks the existing API~
  ~* [ ] I've added tests to reproduce the issue which are now passing~ (there are now lots of tests though)
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK c5afbaa95d7bc699981d6fe7f9964a41b7587d5c
  notmandatory:
    utACK c5afbaa95d7bc699981d6fe7f9964a41b7587d5c

Tree-SHA512: f588493a4643f0f68d3181f27adf91793d4e336be6e853a26289e0916ed83169e1067260b75e627f190842f691ec095e668c0b799ca80e7da2849dd28de32754
2024-01-31 08:37:15 -06:00
Steve Myers
c5afbaa95d
ci: update zstd-sys version to work with MSRV 1.63 2024-01-31 08:15:37 -06:00
志宇
929b5ddb0c
refactor(esplora): better variable naming and docs 2024-01-31 21:35:22 +08:00
志宇
070fffb95c
Merge bitcoindevkit/bdk#1279: Filter duplicate coins before coin selection
5299db34cb9117ad1b66a6afcb51f6ca7e1f0d95 fix(wallet): filter duplicates before coin selection (志宇)
d9501187ef3c4436b7baedb23a4d4f6b1f46a03d test(wallet): fix tests helpers to generate unique utxos (志宇)

Pull request description:

  Fixes #1240

  ### Description

  We now filter out duplicate coins before calling `CoinSelectionAlgorithm::coin_select`. If a UTXO exists in both `required_utxos` and `optional_utxos`, only the copy in `required_utxos` will be kept.

  Test helper methods are also updated to not create duplicate UTXOs.

  ### Changelog notice

  Fixed

  * Filter out duplicate UTXOs before calling `CoinSelectionAlgorithm::coin_select`. If a UTXO exists in both `required_utxos` and `optional_utxos`, only the copy in `required_utxos` will be kept.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  ~* [ ] This pull request breaks the existing API~
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    utACK 5299db34cb9117ad1b66a6afcb51f6ca7e1f0d95

Tree-SHA512: 9cb5517b7f74f89c06172efc344766b16b3216a25b1ebdd6eb84767a9e103124cead9eb0a7f3b5feb562fbb925517a9bf0404399de74b4e898982a5b3795aa04
2024-01-31 16:01:01 +08:00
LLFourn
216648bcfd
chore(esplora): Clarify consistency guarantees 2024-01-30 13:57:06 +11:00
志宇
5299db34cb
fix(wallet): filter duplicates before coin selection 2024-01-29 21:38:02 +08:00
志宇
8375bb8d39
Merge bitcoindevkit/bdk#1287: doc(store): update doc for Store::aggregate_changesets
3829fc18c7f2d16d2c72852bde4b4b70bff8e370 doc(store): update doc for `Store::aggregate_changesets` (vmammal)

Pull request description:

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 3829fc18c7f2d16d2c72852bde4b4b70bff8e370

Tree-SHA512: 55e3dea6db4e023edcd6f12e3c2e8f63c79654b178e01e2fb8b66f3a66399aabedb1d159cd015b78bc2166be6e640e0ed684e3571f2c4f2f6a53fa68d2ef9849
2024-01-29 20:54:31 +08:00
志宇
63fa710319
fix(esplora): reuse returned height instead of zipping 2024-01-29 17:51:03 +08:00
志宇
d4276a1c32
Merge bitcoindevkit/bdk#1290: doc(example_cli): add missing cli docs
c4d5f2ccd8435b9c424eec5ba35ba44a3383b04d doc(example_cli): add missing cli docs (vmammal)

Pull request description:

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK c4d5f2ccd8435b9c424eec5ba35ba44a3383b04d

Tree-SHA512: 43684abbb32570f07e0dc05ed07062bc7969cbe7c4fefe8ae7ebe41ac28aedfbba76ffc801bc4ddb3bf08a940ca81c128376dc3f6c76a04f1391e43c18e0d50b
2024-01-29 18:07:01 +09:00
志宇
6a03e0f209
Merge bitcoindevkit/bdk#1299: fix(file_store): rm lifetime from FileError
5611c9e42adb4106f48039e19ab0797b266c7fff fix(file_store): rm lifetime from `FileError` (志宇)

Pull request description:

  ### Description

  The lifetime on the error needed to be the same as the input magic bytes which was annoying.

  ### Changelog notice

  Fixed
  * Remove `bdk_file_store::FileError` lifetime.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  LLFourn:
    ACK 5611c9e42adb4106f48039e19ab0797b266c7fff

Tree-SHA512: 0eca5128c71c9adb10a712d169a2170b8cbb91678f93986957e86b26dbfed3ab19217a136b57328249a13a51cc06e6c424d58683d74a0fa3d29c22af04a95591
2024-01-29 17:52:12 +09:00
志宇
38b728ae52
Merge bitcoindevkit/bdk#1301: Fix ConfirmationTime conversion from ChainPosition
e687c27096e1c8f36c3a129dc6d92af9c5d05a30 fix(chain): convert to `ConfirmationTime` fix (志宇)

Pull request description:

  ### Description

  We forgot to include the `last_seen` when converting from `ChainPosition` to `ConfirmationTime`.

  ### Notes to the reviewers

  No brainer.

  ### Changelog notice

  * Fix `ConfirmationTime` conversion from `ChainPosition` to include the `last_seen`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  LLFourn:
    ACK e687c27096e1c8f36c3a129dc6d92af9c5d05a30

Tree-SHA512: 182f804309c7ea7f2a42911bc00d836ef48a8617c156b2275d6908b07f619b2466039f54728dd3ca2552f4cd11528a8733618f4ce6a4c88d7e88a05a3d82ffaf
2024-01-29 17:51:13 +09:00
Lloyd Fournier
d162208d95
Merge pull request #1296 from yukibtc/change-default-lookahead
chain: set `DEFAULT_LOOKAHEAD` to 25
2024-01-29 19:19:49 +11:00
志宇
e687c27096
fix(chain): convert to ConfirmationTime fix
We forgot to include the `last_seen` when converting from
`ChainPosition` to `ConfirmationTime`.
2024-01-29 17:14:23 +09:00
志宇
5611c9e42a
fix(file_store): rm lifetime from FileError
The lifetime on the error needed to be the same as the input magic bytes
which was annoying.
2024-01-26 01:13:00 +09:00
志宇
07116df541
Merge bitcoindevkit/bdk#1270: Improve performance of bdk_file_store::EntryIter
51bd01b3dd3d68c1628d74be9dc6d0f1cf1f15fe fix(file_store): recover file offset after read (志宇)
66dc34e75ab1ec2ae533bd540327721f6226eca1 refactor(file_store): Use BufReader but simplify (LLFourn)
c8717646700bdac0f1e13ec499481bd1fee30ffd test(file_store): `last_write_is_short` (志宇)
a3aa8b6682a3a13958fd5fbadc4074a1907a78db feat(file_store)!: optimize `EntryIter` by reducing syscalls (志宇)

Pull request description:

  ### Description

  `EntryIter` performance is improved by reducing syscalls. The underlying file reader is wrapped with `BufReader` (to reduce calls to `read` and `seek`).

  Two new tests are introduced. One ensures correct behavior when the last changeset write is too short. The other ensures the next write position is correct after a short read.

  ### Notes to the reviewers

  This is extracted from #1172 as suggested by https://github.com/bitcoindevkit/bdk/pull/1172#pullrequestreview-1817465627.

  ### Changelog notice

  Changed
  * `EntryIter` performance is improved by reducing syscalls.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  LLFourn:
    ACK 51bd01b3dd3d68c1628d74be9dc6d0f1cf1f15fe

Tree-SHA512: 9c25f9f2032cb2d551f3fe4ac62b856ceeb69a388f037b34674af366c55629a2eaa2b90b1ae4fbd425415ea8d02f44493a6c643b4b1a57f4507e87aa7ade3736
2024-01-25 23:50:25 +09:00
志宇
48b28e3abc
Merge bitcoindevkit/bdk#1294: Expose SpkIterator::new_with_range
8305e648494cbdd1f6438904ec367f8442fba606 feat(chain): expose `SpkIterator::new_with_range` (志宇)

Pull request description:

  ### Description

  This method is useful, I'm not sure why it is not public.

  I've also updated the docs and tests.

  ### Changelog notice

  Added
  * Expose `SpkIterator::new_with_range`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  danielabrozzoni:
    utACK 8305e648494cbdd1f6438904ec367f8442fba606
  LLFourn:
    ACK 8305e648494cbdd1f6438904ec367f8442fba606

Tree-SHA512: 26389bf65bea74742ebb4d170f3d21aeb02e5be1b3fd20ef16eb318393145809d2b21b96767ebb42acfd8dd789a82bb2d7b29ded24249dabf06bd1e6d23cf0cf
2024-01-25 20:57:10 +09:00
志宇
51bd01b3dd
fix(file_store): recover file offset after read
Because we use wrap the file with `BufReader` with the `EntryIter`, we
need to sync the `BufReader`'s position with the file's offset when we
drop the `EntryIter`. Therefore we have a custom drop impl for
`EntryIter`.
2024-01-25 17:19:42 +09:00
Yuki Kishimoto
285ff46a49
chain: set DEFAULT_LOOKAHEAD to 25 2024-01-23 09:44:38 +01:00
志宇
8305e64849
feat(chain): expose SpkIterator::new_with_range
Also update docs and add tests
2024-01-23 13:01:45 +08:00
LLFourn
66dc34e75a
refactor(file_store): Use BufReader but simplify 2024-01-23 11:41:00 +08:00
Daniela Brozzoni
fbd1d65618
Merge bitcoindevkit/bdk#1253: Remove deprecated checksum routines
ed91a4bdb49276057eb7458e1a94653553be24e7 Consolidate `calc_checksum_bytes_internal` routine (Sebastian Falbesoner)
179cfeff51cefda80c16fa4558ba039143a2ad2c Remove deprecated `get_checksum{,_bytes}` routines (Sebastian Falbesoner)

Pull request description:

  ### Description

  This PR removes the routines `get_checksum` and `get_checksum_bytes` (in the bdk crate, descriptor/checksum.rs), which have been deprecated in 0.24.0. Consequently, the routine `calc_checksum_bytes_internal` is consolidated into `calc_checksum_bytes`, as the boolean parameter `exclude_hash` is not needed anymore. See also the two TODOs in the touched file.

  ### Notes to the reviewers

  In the second commit, the signature of the function `calc_checksum_bytes` slightly changes, as the `desc` parameter now is declared as `mut`, in order to change the local variable within the function. My rust experience is rather limited, so I'm not sure if this is a problem for users. IIUC, this is comparable to changing a pass-by-value parameter in C++ from `const std::string desc` to `std::string desc`, which is relevant only for the function implementation, but doesn't change the interface.

  ### Changelog notice

  - Remove deprecated `get_checksum` and `get_checksum_bytes` routines

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK ed91a4bdb49276057eb7458e1a94653553be24e7

Tree-SHA512: a29ead57d0369b67e7e79734d7ddc26f42e7ee78b3a6a336cbf9dfa5579f55e7ddbc20b1662d4bedddd7b40a49511dc21c2652911f56d84c9663099b383e1084
2024-01-22 22:24:45 +01:00
vmammal
c4d5f2ccd8
doc(example_cli): add missing cli docs 2024-01-22 11:31:36 -05:00
Daniela Brozzoni
52c77b8451
Merge bitcoindevkit/bdk#1277: fix(readme): update examples
914db84824edf25418ab0b7b2df7bca84605d64d fix(readme): update examples (Jose Storopoli)

Pull request description:

  ### Description

  Some janitor cleaning in the README to update the `example-crates/`

  ### Notes to the reviewers

  None.

  ### Changelog notice

  - fix(readme): update example crates

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK 914db84824edf25418ab0b7b2df7bca84605d64d

Tree-SHA512: 9376e7ac816ebc4b0bd9652c2e357486e39c55f6542ef650087962b7a864655f7f70a6305b315363e3ed750ce4cea1a328b6a413c340aa94b693b130da2d36b5
2024-01-22 12:28:40 +01:00
Daniela Brozzoni
99661be5f3
Merge bitcoindevkit/bdk#1289: doc(electrum_ext): fix docs for `RelevantTxids::into_confirmation_tim…
cf0c3337446b1de19ad6be9e68f5a9cb848d5773 doc(electrum_ext): fix docs for `RelevantTxids::into_confirmation_time_tx_graph` (vmammal)

Pull request description:

  Note also, the bit referring to Electrum's API sounds more like a developer note, so I made it a regular code comment.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK cf0c3337446b1de19ad6be9e68f5a9cb848d5773

Tree-SHA512: 0ebd6a753c8a0c573510a4d866068cb6e1c7e356c43b20b5179331a1b7d567e4dfbf7012c63ba9b7b9566bf6564a2d957d12e54d5c0232b7be9869dfe0958e85
2024-01-22 12:20:28 +01:00
Jose Storopoli
914db84824
fix(readme): update examples 2024-01-22 08:08:24 -03:00
Daniela Brozzoni
f8f371c8d8
Merge bitcoindevkit/bdk#1291: doc(chain,esplora): minor documentation improvements
b6a58d4f9bab13be0f3518f556936fa77a6b7b39 doc(chain,esplora): minor documentation improvements (vmammal)

Pull request description:

  * Corrects an awkward use of the word 'an'
  * Adds missing backticks, brackets in a few places

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK b6a58d4f9bab13be0f3518f556936fa77a6b7b39

Tree-SHA512: 42f12f218a9849b6fc1c8da28c4d41ca86fcc9ea52311d28f67fadbec030b6cb6986774d89a30e7a2b5ee569b08c7cfa2af71bbb9b06efacfa685dbe95820f73
2024-01-22 12:01:45 +01:00
Daniela Brozzoni
232a172c32
Merge bitcoindevkit/bdk#1288: doc(esplora): fix broken link in README
7c0f4653b281b4288e92ed8cd45ead8abd104f52 doc(esplora): fix broken link in README (vmammal)

Pull request description:

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK 7c0f4653b281b4288e92ed8cd45ead8abd104f52

Tree-SHA512: 6e09a0b74c1a64bc9d0d0a067daf7766c4a46511c22b676251f61608d770d3ea2c1df81d4e9bbbee69720cad5cd2deb9b146cb7751277871f0cbf1be96efcc9f
2024-01-22 11:53:45 +01:00
志宇
8d916d7a10
Merge bitcoindevkit/bdk#1285: doc(wallet): improve docs for Wallet::sent_and_received
08b745ec9f16fa8ef18b0d9c92feb9d8ab87a184 doc(wallet): improve docs for `Wallet::sent_and_received` (vmammal)

Pull request description:

  Thank you @thunderbiscuit for raising this issue. I noticed this method borrows the language from `SpkTxOutIndex::sent_and_received`, which this PR doesn't touch. I think in general it's desirable that methods in `bdk_chain` crate would refer to some of the core structures directly.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 08b745ec9f16fa8ef18b0d9c92feb9d8ab87a184

Tree-SHA512: 7f1285c4baa5fb56fd65baa5585bd343338de9988b941618a2b9ab628d869563f6f71ce842f936e7e1fb6a56f2f1e50fc3deaff858e830b7039888e4e496ce9a
2024-01-19 23:38:26 +08:00
志宇
3fa44a58ec
Merge bitcoindevkit/bdk#1292: fix(store): Remove lifetime
e6433fb2c1526cff37e3a17cc71986759ebac30f feat(persist): Add stage_and_commit to Persist (LLFourn)
0bee46e75bc99112abc15de59984e6059ff874e5 fix(store): Remove lifetime (LLFourn)

Pull request description:

  Remove gratuitous use of lifetimes in the main persistence struct `Store`. Having lifetimes on this means that you have to keep the magic bytes alive longer than the database which is particularly offensive if you have to send the database to another thread. On top of that the bytes aren't even read.

ACKs for top commit:
  evanlinjin:
    ACK e6433fb2c1526cff37e3a17cc71986759ebac30f

Tree-SHA512: 7f6d9d60951a8ceaee30719d0771e15632c6fad0702294af15409c5df492669a07299874ef5ee34e3d75bdecbbd41df29bced3ff16b2360d5d5c7687ef677ffc
2024-01-19 23:28:56 +08:00
志宇
6f824cf325
test(esplora): introduce test cases for update_local_chain 2024-01-19 23:17:54 +08:00
志宇
f05e8502e6
feat(esplora): greatly simplify update_local_chain 2024-01-19 23:17:54 +08:00
志宇
25653d71b8
Merge bitcoindevkit/bdk#1172: Introduce block-by-block API to bdk::Wallet and add RPC wallet example
a4f28c079e3bc4500e8329aeed230d8100d38617 chore: improve LocalChain::apply_header_connected_to doc (LLFourn)
8ec65f0b8ef7d452a0bdba6760c46bd8511c91ff feat(example): add RPC wallet example (Vladimir Fomene)
a7d01dc39acb3ff7f4bc8e237c7862d019a91cd1 feat(chain)!: make `IndexedTxGraph::apply_block_relevant` more efficient (志宇)
e0512acf9476fa3fa7da9cc28a222432f974aad5 feat(bitcoind_rpc)!: emissions include checkpoint and connected_to data (志宇)
8f2d4d9d400e398b54cf1bad36057f3f8f4a69a4 test(chain): `LocalChain` test for update that is shorter than original (志宇)
9467cad55d68354fe037d57bceeee57c2032bd51 feat(wallet): introduce block-by-block api (Vladimir Fomene)
d3e5095df10d21ff5cb7f8ce4dab7922f3cb6e35 feat(chain): add `apply_header..` methods to `LocalChain` (志宇)
2b61a122ff40253f2e67c0ae6824ce881c9f12a1 feat(chain): add `CheckPoint::from_block_ids` convenience method (志宇)

Pull request description:

  ### Description

  Introduce block-by-block API for `bdk::Wallet`. A `wallet_rpc` example is added to demonstrate syncing `bdk::Wallet` with the `bdk_bitcoind_rpc` chain-source crate.

  The API of `bdk_bitcoind_rpc::Emitter` is changed so the receiver knows how to connect to the block emitted.

  ### Notes to the reviewers

  ### Changelog notice

  Added
  * `Wallet` methods to apply full blocks (`apply_block` and `apply_block_connected_to`) and a method to apply a batch of unconfirmed transactions (`apply_unconfirmed_txs`).
  * `CheckPoint::from_block_ids` convenience method.
  * `LocalChain` methods to apply a block header (`apply_header` and `apply_header_connected_to`).
  * Test to show that `LocalChain` can apply updates that are shorter than original. This will happen during reorgs if we sync wallet with `bdk_bitcoind_rpc::Emitter`.

  Fixed
  * `InsertTxError` now implements `std::error::Error`.

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  LLFourn:
    self-ACK: a4f28c079e3bc4500e8329aeed230d8100d38617
  evanlinjin:
    ACK a4f28c079e3bc4500e8329aeed230d8100d38617

Tree-SHA512: e39fb65b4e69c0a6748d64eab12913dc9cfe5eb8355ab8fb68f60a37c3bb2e1489ddd8f2f138c6470135344f40e3dc671928f65d303fd41fb63f577b30895b60
2024-01-19 23:07:35 +08:00
LLFourn
e6433fb2c1
feat(persist): Add stage_and_commit to Persist
In the example_cli we were not always committing (seemingly by mistake).
This then caused all the examples to have to compensate by manually
committing.
2024-01-19 11:28:56 +11:00
LLFourn
0bee46e75b
fix(store): Remove lifetime
Remove gratuitous use of lifetimes in the main persistence struct
2024-01-19 11:28:56 +11:00
vmammal
08b745ec9f
doc(wallet): improve docs for Wallet::sent_and_received 2024-01-18 10:24:20 -05:00
志宇
0a2a57060b
Merge bitcoindevkit/bdk#1282: Bump version to 1.0.0-alpha.4
d33acc14661326972b3ab3cf2b7cee4ca078f4da Bump version to 1.0.0-alpha.4 (Steve Myers)

Pull request description:

  ### Description

  Bump version to 1.0.0-alpha.4, also:

  bdk_chain to 0.8.0
  bdk_bitcoind_rpc to 0.3.0
  bdk_electrum to 0.6.0
  bdk_esplora to 0.6.0
  bdk_file_store to 0.4.0

  Fixes #1281.

  ### Notes to the reviewers

  Since the version of bdk_chain changed all crates that depend on it also need to have their versions bumped.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK d33acc14661326972b3ab3cf2b7cee4ca078f4da

Tree-SHA512: ffb5c05b45e9d646ef796bd894353e4b58c3aae3dcf0921dfb9fcae45020ed4fc82274a7497494d6259bfffff9c2f97c530d2cbe6ace578babd04852af461f3a
2024-01-18 19:22:56 +08:00
Steve Myers
d33acc1466
Bump version to 1.0.0-alpha.4
bdk_chain to 0.8.0
bdk_bitcoind_rpc to 0.3.0
bdk_electrum to 0.6.0
bdk_esplora to 0.6.0
bdk_file_store to 0.4.0
2024-01-18 19:07:37 +08:00
Daniela Brozzoni
d1ea0ef3d1
Merge bitcoindevkit/bdk#1286: doc, example(bdk): fix derivation path in mnemonic_to_descriptors
d494f63d08f60ce01c22ff08f7e88a80a7be2522 doc, example(bdk): fix derivation path in mnemonic_to_descriptors (vmammal)

Pull request description:

  This will help avoid confusion with mainnet descriptors.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK d494f63d08f60ce01c22ff08f7e88a80a7be2522

Tree-SHA512: f0450d171bc53085204280495f2954e20f4b64a73cfbcc9a0c3be131c0b04ad53e936c83fa83c89fbd1ed1c4edd680e8437550453f75056049d36f84cae1df43
2024-01-18 12:05:33 +01:00
Daniela Brozzoni
60abd87a32
Merge bitcoindevkit/bdk#1269: Revamp KeychainTxOutIndex API to be safer
71fff1613d1c167d180636857063e181f6acedf1 feat(chain): add txout methods to `KeychainTxOutIndex` (志宇)
83e7b7ec402bef27c3f83876f346ec2abd23eff1 docs(chain): improve `KeychainTxOutIndex` docs (志宇)
9294e30943f3f79bb36915d69652d9086323131f docs(wallet): improve docs for unbounded spk iterator methods (志宇)
b74c2e262255a39e9dc904aad469e307bf7d0151 fix(wallet): use efficient peek address logic (志宇)
81aeaba48a980a7e7add76ac2d24e896bedaa1d2 feat(chain): add `SpkIterator::descriptor` method (志宇)
c7b47af72f278ba73abea58db49cff1245428f97 refactor(chain)!: revamp `KeychainTxOutIndex` API (志宇)
705690ee8fddba8517d907183b7ddfeafb633609 feat(chain): make output of `SpkTxOutIndex::unused_spks` cloneable (志宇)

Pull request description:

  Closes #1268

  ### Description

  Previously `SpkTxOutIndex` methods can be called from `KeychainTxOutIndex` due to the `DeRef` implementation. However, the internal `SpkTxOut` will also contain lookahead spks resulting in an error-prone API.

  `SpkTxOutIndex` methods are now not directly callable from `KeychainTxOutIndex`. Methods of `KeychainTxOutIndex` are renamed for clarity. I.e. methods that return an unbounded spk iter are prefixed with `unbounded`.

  In addition to this, I also optimized the peek-address logic of `bdk::Wallet` using the optimized `<SpkIterator as Iterator>::nth` implementation.

  ### Notes to the reviewers

  This is mostly refactoring, but can also be considered a bug-fix (as the API before was very problematic).

  ### Changelog notice

  Changed
  * Wallet's peek-address logic is optimized by making use of `<SpkIterator as Iterator>::nth`.
  * `KeychainTxOutIndex` API is refactored to better differentiate between methods that return unbounded vs stored spks.
  * `KeychainTxOutIndex` no longer directly exposes `SpkTxOutIndex` methods via `DeRef`. This was problematic because `SpkTxOutIndex` also contains lookahead spks which we want to hide.

  Added
  * `SpkIterator::descriptor` method which gets a reference to the internal descriptor.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  ~* [ ] I've added tests for the new feature~
  * [x] I've added docs for the new feature

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK 71fff1613d1c167d180636857063e181f6acedf1

Tree-SHA512: f29c7d2311d0e81c4fe29b8f57c219c24db958194fad5de82bb6d42d562d37fd5d152be7ee03a3f00843be5760569ad29b848250267a548d7d15320fd5292a8f
2024-01-18 11:36:31 +01:00
志宇
71fff1613d
feat(chain): add txout methods to KeychainTxOutIndex
`txouts` and `txouts_in_tx` are exposed from `SpkTxOutIndex`, but
modified to remove nested unions.

Add `keychain_outpoints_in_range` that iterates over outpoints of a
given keychain derivation range.
2024-01-18 14:30:29 +08:00
vmammal
b6a58d4f9b
doc(chain,esplora): minor documentation improvements
* Corrects an awkward use of the word 'an'
* Adds missing backticks, brackets in a few places
2024-01-17 14:07:14 -05:00
vmammal
cf0c333744
doc(electrum_ext): fix docs for RelevantTxids::into_confirmation_time_tx_graph 2024-01-17 13:49:58 -05:00
vmammal
7c0f4653b2
doc(esplora): fix broken link in README 2024-01-17 13:45:35 -05:00
vmammal
3829fc18c7
doc(store): update doc for Store::aggregate_changesets 2024-01-17 13:41:23 -05:00
vmammal
d494f63d08
doc, example(bdk): fix derivation path in mnemonic_to_descriptors
This will help avoid confusion with mainnet descriptors.
2024-01-17 13:29:25 -05:00
志宇
83e7b7ec40
docs(chain): improve KeychainTxOutIndex docs
More clarity for revealed/lookahead spks and give usecases.
2024-01-17 13:30:28 +08:00
志宇
9294e30943
docs(wallet): improve docs for unbounded spk iterator methods 2024-01-17 13:29:16 +08:00
志宇
b74c2e2622
fix(wallet): use efficient peek address logic
Changes the peek address logic to use the optimized `Iterator::nth`
implementation of `SpkIterator`.

Additionally, docs are added for panics that will occur when the caller
requests for addresses with out-of-bound derivation indices (BIP32).
2024-01-17 11:17:25 +08:00
志宇
81aeaba48a
feat(chain): add SpkIterator::descriptor method
Otherwise there will be no way to view the descriptor of the
`SpkIterator`.
2024-01-17 11:17:25 +08:00
志宇
c7b47af72f
refactor(chain)!: revamp KeychainTxOutIndex API
Previously `SpkTxOutIndex` methods can be called from
`KeychainTxOutIndex` due to the `DeRef` implementation. However, the
internal `SpkTxOut` will also contain lookahead spks resulting in an
error-prone API.

`SpkTxOutIndex` methods are now not directly callable from
`KeychainTxOutIndex`. Methods of `KeychainTxOutIndex` are renamed for
clarity. I.e. methods that return an unbounded spk iter are prefixed
with `unbounded`.
2024-01-17 11:17:25 +08:00
志宇
d9501187ef
test(wallet): fix tests helpers to generate unique utxos 2024-01-16 22:43:31 +08:00
LLFourn
a4f28c079e
chore: improve LocalChain::apply_header_connected_to doc 2024-01-16 10:29:49 +11:00
Vladimir Fomene
8ec65f0b8e
feat(example): add RPC wallet example
Co-authored-by: Vladimir Fomene <vladimirfomene@gmail.com>
Co-authored-by: 志宇 <hello@evanlinjin.me>
2024-01-16 00:27:02 +08:00
志宇
a7d01dc39a
feat(chain)!: make IndexedTxGraph::apply_block_relevant more efficient
Previously, `apply_block_relevant` used `batch_insert_relevant` which
allows inserting non-topologically-ordered transactions. However,
transactions from blocks are always ordered, so we can avoid looping
through block transactions twice (as done in `batch_insert_relevant`).

Additionally, `apply_block_relevant` now takes in a reference to a
`Block` instead of consuming the `Block`. This makes sense as typically
very few of the transactions in the block are inserted.
2024-01-16 00:27:02 +08:00
志宇
e0512acf94
feat(bitcoind_rpc)!: emissions include checkpoint and connected_to data
Previously, emissions are purely blocks + the block height. This means
emitted blocks can only connect to previous-adjacent blocks. Hence, sync
must start from genesis and include every block.
2024-01-16 00:27:02 +08:00
志宇
8f2d4d9d40
test(chain): LocalChain test for update that is shorter than original 2024-01-16 00:27:02 +08:00
Vladimir Fomene
9467cad55d
feat(wallet): introduce block-by-block api
* methods `process_block` and `process_unconfirmed_txs` are added
* amend stage method docs

Co-authored-by: Vladimir Fomene <vladimirfomene@gmail.com>
Co-authored-by: 志宇 <hello@evanlinjin.me>
2024-01-16 00:27:02 +08:00
志宇
d3e5095df1
feat(chain): add apply_header.. methods to LocalChain
These are convenience methods to transform a header into checkpoints to
update the `LocalChain` with. Tests are included.
2024-01-16 00:27:00 +08:00
志宇
2b61a122ff
feat(chain): add CheckPoint::from_block_ids convenience method 2024-01-16 00:23:42 +08:00
Daniela Brozzoni
40f0765d30
Merge bitcoindevkit/bdk#1276: Add LocalChain::disconnect_from method
bf67519768d91b049bf3a47c234ff71a81d0ede9 feat(chain): add `LocalChain::disconnect_from` method (志宇)

Pull request description:

  Closes #1271

  ### Description

  Add a method for disconnecting a chain of blocks starting from the given `BlockId`.

  ### Notes to the reviewers

  I want to have this for https://github.com/utreexo/utreexod/pull/110

  ### Changelog notice

  Added
  * `LocalChain::disconnect_from` method to evict a chain of blocks starting from a given `BlockId`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  danielabrozzoni:
    ACK bf67519768d91b049bf3a47c234ff71a81d0ede9

Tree-SHA512: e6bd213b49b553355370994567722ad2c3460d11fcd81adc65a85e5d03822d3c38e4a4d7f967044991cf0187845467b67d035bf8904871f9fcc4ea61be761ef7
2024-01-15 13:56:59 +01:00
志宇
bf67519768
feat(chain): add LocalChain::disconnect_from method 2024-01-15 17:48:36 +08:00
Lloyd Fournier
b6422f7ffc
Merge pull request #1274 from evanlinjin/avoid_btreemap_append
Avoid using `BTreeMap::append`
2024-01-15 16:54:03 +11:00
志宇
eb1714aee0
fix(chain): avoid using BTreeMap::append
The implementation of `BTreeMap::append` is non-performant making
merging changesets very slow. We use `Extend::extend` instead.

Refer to:
https://github.com/rust-lang/rust/issues/34666#issuecomment-675658420
2024-01-15 13:36:32 +08:00
志宇
705690ee8f
feat(chain): make output of SpkTxOutIndex::unused_spks cloneable
This allows us to pass this to chain sources without calling
`Iterator::collect` first.
2024-01-13 20:07:02 +08:00
志宇
c871764670
test(file_store): last_write_is_short
This test simulates a situation where the last write to the db is short.

Aggregating the changeset after reopening the file should return an
error (which includes a partially-aggregated changeset) containing an
aggregation of changesets that were fully written.

At this point, the test re-writes the final changeset (and this time it
successfully writes in full).

The file should be recoverable with all changesets, including the last
one.
2024-01-13 17:51:41 +08:00
志宇
a3aa8b6682
feat(file_store)!: optimize EntryIter by reducing syscalls
* Wrap file reader with `BufReader`. This reduces calls to `read`.
* Wrap file reader with `CountingReader`. This counts the bytes read by
  the underlying reader. We can rewind without seeking first.
2024-01-13 16:07:43 +08:00
志宇
cd602430ee
Merge bitcoindevkit/bdk#1264: fix(example_electrum): init LocalChain from genesis
5b7794299308cd81a2ebbe0aa2b1be1d4c47680b fix(example_electrum): init LocalChain from genesis (vmammal)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  This should fix #1252

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 5b7794299308cd81a2ebbe0aa2b1be1d4c47680b

Tree-SHA512: bf049edb2ba22abb949dfd4cb38608589287f3f374f397c82f778b59c21010daa80b63ad85c442c4ee00a2608f89a8d50447b0db85d15caac7fd0b4fd8956e1a
2024-01-11 17:00:45 +08:00
志宇
264bb85efc
Merge bitcoindevkit/bdk#1261: Refactor reveal_to_target and next_store_index
761189ab2b679fbfee45b33435d66ed98a135e2a feat(chain): debug_assert non-wildcard desc. to only cache index 0 (志宇)
887e112e8f4ee5300bf09a0f3590861bff7fd053 ref(chain): Refactor reveal_to_target (Daniela Brozzoni)
21d88758262bfbc3d9d2109aac9883f23ab651c4 ref(chain): Refactor next_store_index (Daniela Brozzoni)

Pull request description:

  ### Description

  As a part of #1203, I found myself having to modify `reveal_to_target`, but had some troubles understanding exactly what the method was doing.

  This PR refactors `reveal_to_target` to be, in my opinion, a bit clearer. We now exist prematurely if `next_reveal_index` < `target_index`; this way, we don't need to keep track of `next_reveal_index`, as it would always be equal to `Some(target_index)`.
  As a part of trying to understand `reveal_to_target` I had to read through `next_store_index`, I slightly improved it for clarity reasons as well.

  ### Changelog notice

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 761189ab2b679fbfee45b33435d66ed98a135e2a

Tree-SHA512: 17f70bccbfa1cccf718ece0eeb61f4944c9108776cf1d606ef823ae9ff58bf52114750927ac99561644ece598f8131ee7f7605071d42c91e5e88e05035e74836
2024-01-11 11:00:50 +08:00
志宇
761189ab2b
feat(chain): debug_assert non-wildcard desc. to only cache index 0 2024-01-10 22:47:53 +01:00
vmammal
5b77942993
fix(example_electrum): init LocalChain from genesis 2024-01-09 21:04:36 -05:00
Steve Myers
f9dad51ae1
Merge bitcoindevkit/bdk#1263: Bump bdk_esplora and bdk_file_store versions for 1.0.0-alpha.3 release
8f6dad76efaa4af0ebb990ed83632f230fd10d94 Bump bdk_esplora and bdk_file_store versions for 1.0.0-alpha.3 release (Steve Myers)

Pull request description:

  ### Description

  These crates need to have their versions bumped because the version of bdk_chain was bumped to 0.7.0 with the 1.0.0-alpha.3 release.

  bdk_esplora to 0.5.0
  bdk_file_store to 0.3.0

  After this PR is merged I'll publish new versions of these crates to crates.io.

  ### Notes to the reviewers

  I should have done this as part of the 1.0.0-alpha.3 release process.  This problem was found when @thunderbiscuit started updating the bdk-ffi project to alpha.3 and we got type mismatch errors for bdk_chain types used in bdk_esplora.

ACKs for top commit:
  thunderbiscuit:
    ACK 8f6dad76efaa4af0ebb990ed83632f230fd10d94.

Tree-SHA512: 735094a5d78da082437118a38db085b12c26665c8cf8fd809d62dbe9a058ee04c59a165e454b3eb8baea4209330083a6a7bce8c303be1660f6593c80ccbe46b7
2024-01-09 19:28:05 -06:00
Steve Myers
8f6dad76ef
Bump bdk_esplora and bdk_file_store versions for 1.0.0-alpha.3 release
These crates need to have their versions bumped because the version of bdk_chain was bumped to 0.7.0 with the 1.0.0-alpha.3 release.

bdk_esplora to 0.5.0
bdk_file_store to 0.3.0
2024-01-09 15:06:08 -06:00
Daniela Brozzoni
887e112e8f
ref(chain): Refactor reveal_to_target
Simplify the `reveal_to_target` algorithm by exiting prematurely if
the `target_index` is already revealed.
Since the `reveal_to_index` variable was different from
`Some(target_index)` only if the target was already revealed, we can
getrid of the variable altogether.
2024-01-09 14:13:43 +01:00
Daniela Brozzoni
21d8875826
ref(chain): Refactor next_store_index
Rename `v` to `index` for better clarity, and add a comment explaining
the `range`
2024-01-09 14:13:42 +01:00
Steve Myers
6e6bad9223
Merge bitcoindevkit/bdk#1161: ref(hwi): Move hwi out of bdk
105d70e9743f651d141c6e0d901d60d583afd4d9 ref(hwi): Move hwi out of bdk (Daniela Brozzoni)

Pull request description:

  Fixes #872

  ### Description

  This commit moves the `hardwaresigner` outside of bdk and inside `bdk_hwi`

  ### Notes to the reviewers

  There are currently two issues with the code:
  - `TransactionSigner` dictates that `sign_transaction` must return a `SignerError` - but being `SignerError` defined inside of bdk, we can't modify it to include an hwi specific error! I don't know how we could fix this (other than getting rid of the trait altogether :)); for now I just added a `SignerError::Generic` variant, lmk if you have better ideas!
  - The hwi tests used the bdk utils to get a funded wallet for testing, which aren't available in `bdk_hwi`, which made me realize - maybe we should expose them so that we can use them across our crates, and also our users can use them to test their code?
  For now, I just left the test commented.

  ### Changelog notice

  - The old `hardwaresigner` module has been moved out of `bdk` and inside `bdk_hwi`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  ~~* [ ] I've added tests for the new feature~~
  * [x] I've added docs for the new feature

ACKs for top commit:
  notmandatory:
    reACK 105d70e9743f651d141c6e0d901d60d583afd4d9

Tree-SHA512: 9ae3cd035cc27bd7b2831e89c104f40771c6f165cb3bfe1a9052f820050fca7c19f4dd68f171c630a71a7d18ccdee5f94adbc497c6475bd257c2d01cc08109a1
2024-01-08 09:59:51 -06:00
Daniela Brozzoni
105d70e974
ref(hwi): Move hwi out of bdk
Fixes #872
2024-01-08 13:33:56 +01:00
Steve Myers
9efaead8f1
Merge bitcoindevkit/bdk#1255: Bump bdk version to 1.0.0-alpha.3
003271117cb347556cc82455558da40ef50a1156 Bump bdk version to 1.0.0-alpha.3 (Steve Myers)

Pull request description:

  ### Description

  - Bump bdk version to 1.0.0-alpha.3
  - Bump bdk_chain to 0.7.0
  - Bump bdk_bitcoin_rpc to 0.2.0
  - Bump bdk_electrum to 0.5.0

  ### Notes to the reviewers

  ### Changelog notice

  See #1254

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 003271117cb347556cc82455558da40ef50a1156

Tree-SHA512: ac0756f52436880fe633e9ecb83f3d53f485ccfa89a3a89aa51ee4ba5da5cee87f507da69a9e1271f8aaf4425f65d04fb201ea9a4f64bce18f96039ea3548d61
2024-01-07 11:02:12 -06:00
Steve Myers
1ff9d5ce8f
Merge bitcoindevkit/bdk#1259: Bump bip39 dependency to v2.0
8694624bd5f63b738448c250d7b1042f219636da Bump `bip39` to v2.0 (Elias Rohrer)

Pull request description:

  We previously bumped the `bip39` version to 2.0 [in the 0.2X release branch](https://github.com/bitcoindevkit/bdk/pull/875). Back then, bumping it in `master` was [assumed unnecessary](https://github.com/bitcoindevkit/bdk/pull/875#issuecomment-1483990088). It seems this was erroneous, as the current `1.0.1` dependency is present since https://github.com/bitcoindevkit/bdk/pull/793, which was merged before the bump in `release/0.27`.

  Here, we therefore bump the crate version in `master` after all.

ACKs for top commit:
  notmandatory:
    ACK 8694624bd5f63b738448c250d7b1042f219636da

Tree-SHA512: a109219bc97bb8e965e8b10e72439aa898b710d1d1a154801ce499ad47475a6b23448d85e0de3f306f990573d1fccdae7d587ed41676a01f91d66a719782eae1
2024-01-07 10:41:16 -06:00
Elias Rohrer
8694624bd5
Bump bip39 to v2.0
We previously bumped the `bip39` version to 2.0 in the 0.2X release
branch. Back then, bumping it in `master` was erroneously considered unnecessary.

Here, we therefore bump the crate version in `master` after all.
2024-01-07 17:09:02 +01:00
Steve Myers
003271117c
Bump bdk version to 1.0.0-alpha.3
Bump bdk_chain to 0.7.0
Bump bdk_bitcoin_rpc to 0.2.0
Bump bdk_electrum to 0.5.0
2024-01-06 15:08:40 -06:00
Steve Myers
f6418ba911
Merge bitcoindevkit/bdk#1258: fix(typos): existant -> existent
028caa9f8cd51afba0fdc81748fc8cf536c75cd0 fix(typos): existant -> existent (Jose Storopoli)

Pull request description:

  ### Description

  These typos are blocking the Nix typo CI in #1257

  ### Notes to the reviewers

  Blocking #1257

  ### Changelog notice

  - fix: typos in documentation
  -
  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 028caa9f8cd51afba0fdc81748fc8cf536c75cd0

Tree-SHA512: 0bd91efd0eec55fdc537824435552c968858a5b827179b3f9f3f37785db3fa92d3e6f0c73023de0c506224c81217c402d5afa8a2f768fecaf6a3c8378226d184
2024-01-06 14:29:10 -06:00
Jose Storopoli
028caa9f8c
fix(typos): existant -> existent
These typos are blocking the Nix typo CI in #1257
2024-01-06 14:13:56 -03:00
志宇
d71829914a
Merge bitcoindevkit/bdk#1256: cherry-pick feat(wallet)!: add NonEmptyDatabase variant to NewError
a1d34afa2455d93d23a36fd78d94aa79c7e493d1 feat(wallet)!: add `NonEmptyDatabase` variant to `NewError` (志宇)

Pull request description:

  ### Description

  `NewError` is the error type when constructing a wallet with `Wallet::new`. We want this to return an error when the database already contains data (in which case, the caller should use `load` or `new_or_load`).

  ### Notes to the reviewers

  This is cherry-picked from #1172 so that we can add it to the alpha.3 release.

  ### Changelog notice

  Change
  - Return `NonEmptyDatabase` error when constructing a wallet with `Wallet::new` if the file already contains data (in which case, the caller should use `load` or `new_or_load`).

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  evanlinjin:
    ACK a1d34afa2455d93d23a36fd78d94aa79c7e493d1

Tree-SHA512: 7c20171fa3d7dee5b1ac24f8a808781dbb0be0034951005e1e87acdf023123c01161e225b47b6d4484865889778c39549a3780f641227ddc0f84d1577d69f40a
2024-01-06 13:30:38 +08:00
志宇
a1d34afa24
feat(wallet)!: add NonEmptyDatabase variant to NewError
`NewError` is the error type when constructing a wallet with
`Wallet::new`. We want this to return an error when the database already
contains data (in which case, the caller should use `load` or
`new_or_load`).
2024-01-06 13:19:03 +08:00
Steve Myers
9cc03324f4
Merge bitcoindevkit/bdk#1235: Refactor/rename electrum_ext and esplora_ext to have sync and full_scan functions
de54e710ed04e3cb1632cf99dbc1c6f2374b0c6e refactor(esplora_ext): rename scan_txs to sync and scan_txs_with_keychains to full_scan (Steve Myers)
95d34854f46fd154eed35008954b25b82785b2d8 refactor(electrum_ext): rename scan_without_keychain to sync and scan to full_scan (Steve Myers)

Pull request description:

  ### Description

  fixes #1112

  Simple function renaming plus updated docs:

  1. electrum_ext: rename functions `scan_without_keychain` to `sync` and `scan` to `full_scan`
  2. esplora_ext: rename functions `scan_txs` to `sync` and `scan_txs_with_keychains` to `full_scan`

  ### Notes to the reviewers

  The esplora_ext changes were partially fixed in #1070 but I renamed again so the functions match names ~~suggested in #1112~~ agreed on in discord poll, `sync` and `full_scan`.

  ### Changelog notice

  Changed

  - electrum_ext: rename functions scan_without_keychain to sync and scan to full_scan
  - esplora_ext: rename functions scan_txs to sync and scan_txs_with_keychains to full_scan

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: d34516ecc513a194b679f73a1260d0cbc3d12b6a2e162d822e7381da0b3250aff319e85ed2fadec506e36f95a78a5cd79d0ab972da2b02928c074be17664da08
2024-01-05 21:44:17 -06:00
Steve Myers
de54e710ed
refactor(esplora_ext): rename scan_txs to sync and scan_txs_with_keychains to full_scan
removed txids and outpoints params from full_scan
2024-01-05 15:32:20 -06:00
Steve Myers
95d34854f4
refactor(electrum_ext): rename scan_without_keychain to sync and scan to full_scan
removed txids and outpoints params from full_scan
2024-01-05 15:31:12 -06:00
Sebastian Falbesoner
ed91a4bdb4
Consolidate calc_checksum_bytes_internal routine
Now that the deprecated `get_checksum{,_bytes}` routines are removed,
the checksum is always computed with ignored data after the first '#',
i.e. the boolean parameter `exclude_hash` is not needed anymore and
the functionality can be consolidated into `calc_checksum_bytes`.
2024-01-02 14:16:34 +01:00
Sebastian Falbesoner
179cfeff51
Remove deprecated get_checksum{,_bytes} routines
There are deprecated since 0.24.0, i.e. they can be removed now.
2024-01-02 14:15:27 +01:00
志宇
7eff024213
Merge bitcoindevkit/bdk#1229: Use a universal lookahead value for KeychainTxOutIndex and have a reasonable default
1def76f1f17fc876534c798883099c58de57c0fd chore: make clippy happy and bump clippy msrv (志宇)
c9467dcbb27bd497006846dcfcefb0c2cf8823c4 chore: improve documentation of lookahead (LLFourn)
bc796f412acdc3d2cd96f7aec0f24fa47c1fe889 fix(example): bitcoind_rpc_polling now initializes local_chain properly (志宇)
4fd539b6470f7f771e3b5e09e3287952fa7a1825 feat(chain)!: `KeychainTxOutIndex` uses a universal lookahead (Antoine Poinsot)

Pull request description:

  ### Description

  The `bdk::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.

  To fix this, we have also decided to change `KeychainTxOutIndex` to have a default lookahead. Additionally, we have simplified the `KeychainTxOutIndex` API to have a single `lookahead` that is ONLY set at construction `KeychainTxOutIndex::new(lookahead: u32) -> Self`. This avoids the footguns of having methods which allows the caller to decrease the `lookahead` (which will panic).

  ### Notes to the reviewers

  ~A way to set this value externally is introduced in #1172. This PR only aims to use a saner default than 0. `1_000` is the value used by the Bitcoin Core wallet, and that seems reasonable to me.~

  Edit: we should NOT allow setting the `lookahead` value after-the-fact. Instead, the `lookahead` should be provided to the wallet's constructor.

  @evanlinjin: I don't think additional tests are necessary as no additional features are added, and the surface area of the API is decreased. The original tests already thoroughly test the `lookahead` concept.

  ### Checklists

  #### All Submissions:

  *(This section was updated as this PR changed from being a simple setting to introducing a new method.)*

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing
  ~* [ ] I've added tests~
  * [x] I've added docs

ACKs for top commit:
  LLFourn:
    ACK 1def76f1f17fc876534c798883099c58de57c0fd

Tree-SHA512: b4c3be8a4f2ac4877cf3f05852147e7dd1daeb02d3bc40895f02fd2a58e584f1dc0735b524153ff0875380ac93c0b4c31e516873d7a9b0027fdbbb5fe7970ff2
2023-12-29 20:39:48 +08:00
志宇
1def76f1f1
chore: make clippy happy and bump clippy msrv 2023-12-29 19:57:48 +08:00
LLFourn
c9467dcbb2
chore: improve documentation of lookahead 2023-12-29 16:40:48 +11:00
志宇
bc796f412a
fix(example): bitcoind_rpc_polling now initializes local_chain properly
Previously, the genesis block is not initialized properly. Thank you
@notmandatory for identifying this bug.
2023-12-28 12:51:11 +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
志宇
01698ae5ec
Merge bitcoindevkit/bdk#1246: Fix: apply loaded changeset to indexed_graph when loading a wallet from persistence
f4863c6314904ddd5da586fed0abb8f04ccee396 fix(wallet): apply loaded changeset to indexed_graph (thunderbiscuit)

Pull request description:

  ### Description
  This PR applies the tx_graph from the changeset when loading a wallet from persistence. This ensures among other things that the revealed keychain indices get picked up by the new wallet. A test for this has been added/modified from an old test.

  ### Notes to the reviewers

  ### Changelog notice
  Fix: loading a wallet from persistence now restores keychain indices.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK f4863c6314904ddd5da586fed0abb8f04ccee396

Tree-SHA512: c8502077ba25e6fb953829b020b396774aa0569f7272e7818f30ddabed9d1d8ce791729bebc92b9ec1059028399495cb79ea147cf900f25aace94045dd7290a6
2023-12-26 12:13:54 +08:00
thunderbiscuit
f4863c6314
fix(wallet): apply loaded changeset to indexed_graph 2023-12-20 21:55:22 -05:00
志宇
b5612f269a
Merge bitcoindevkit/bdk#1247: ci: pin home dependency to 0.5.5 and check_clippy to rust stable version
e7fbc8bcf36de110e88095dba8be0c62e2c8e0ef ci: run clippy_check with rust stable (Steve Myers)
2251b8d41661deb5d8ef7b98abef55efe6437180 ci: pin home version to 0.5.5 for 1.63 MSRV (Steve Myers)

Pull request description:

  ### Description

  Fixed 1.63 MSRV error by pinning `home` dependency to `0.5.5`, and `clippy` error by changing `check_clippy` job to using rust `stable` version.

  ### Notes to the reviewers

  It's OK to use rust `stable` version for clippy because we already have a `clippy.toml` file to tell it which version of the clippy rules to check against.

  ### Changelog notice

  None

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK e7fbc8bcf36de110e88095dba8be0c62e2c8e0ef

Tree-SHA512: 4e9e12488d44a940ea80ecc32ae74dade13d04d5088cb2206271401a2d77b56407af36482df952354b187a52b83631dcdf53bd60d9084a910f4be278059df93b
2023-12-21 10:42:23 +08:00
Steve Myers
e7fbc8bcf3
ci: run clippy_check with rust stable 2023-12-20 11:23:34 -06:00
Steve Myers
2251b8d416
ci: pin home version to 0.5.5 for 1.63 MSRV 2023-12-20 11:19:48 -06:00
Steve Myers
b13505c1c3
Merge bitcoindevkit/bdk#1188: doc: Improve TxGraph & co docs
0adff9c35f109a15740212b4dce74c03950c85ed doc: Improve TxGraph & co docs (Daniela Brozzoni)

Pull request description:

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    Re-ACK 0adff9c35f109a15740212b4dce74c03950c85ed

Tree-SHA512: 83adffeddf6c8ddb7b5e57a0fa2e5cffaf75cdeea59be0a6c5e94dcd5a7f98328db8e2a620edc753e60ea3382282908c75d34783a280348cfd105a37982c762b
2023-12-13 17:08:38 -06:00
Daniela Brozzoni
0adff9c35f
doc: Improve TxGraph & co docs 2023-12-13 10:12:12 +01:00
Steve Myers
908b0f9f5e
Merge bitcoindevkit/bdk#1183: Bump MSRV to 1.63.0
169385bb5ba0fe6ad3ed4fbbad431904582c7eb7 ci: change MSRV to 1.63.0 (Steve Myers)

Pull request description:

  ### Description

  fixes #331

  ### Notes to the reviewers

  We won't merge this PR until LDK merges lightningdevkit/rust-lightning#2681.

  There are alot of clippy checks to fix at 1.63.0 so I left the clippy MSRV at 1.57.0 for now.

  ### Changelog notice

  Changed

  - MSRV is now 1.63.0 for bdk, chain, and bitcoind_rpc crates

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 169385bb5ba0fe6ad3ed4fbbad431904582c7eb7

Tree-SHA512: ad69038173b4f050b57f637fc06a4153cf76929992cfea77e3f25d1e66be102bd2f83a46401a7e3245e9cc54602210c95b75a578f18c5c8b55d1e7229e92197f
2023-12-11 20:11:15 -06:00
Steve Myers
169385bb5b
ci: change MSRV to 1.63.0 2023-12-08 15:18:49 -06:00
Steve Myers
f741122ffb
Merge bitcoindevkit/bdk#1158: doc(bdk): Clarify the absolute_fee docs
0ecc0280c032301dc638e75e54a8691d66d50274 doc(bdk): Clarify the absolute_fee, fee_rate docs (Daniela Brozzoni)

Pull request description:

  Fixes #1066

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 0ecc0280c032301dc638e75e54a8691d66d50274

Tree-SHA512: 152e48b86c21d4fad711abf76dd8fdc0e8955030331005c1ba6ff0c866c52870161f91ec740838f8238c5ad1c620e06212099308a55d130699cb18e4666e3f3f
2023-12-05 07:35:01 -06:00
Steve Myers
959b4f8172
Merge bitcoindevkit/bdk#1179: build(esplora): Add async-https-rustls flag to esplora client
6817ca9bcbff957efb58f96886a30b6bd87c0cde ci: pin hyper-rustls version to 0.24.0 for 1.57 MSRV (thunderbiscuit)
4ee41dbc402121d14ffa099863bf35329851c1e4 build(esplora): Add async-https-rustls flag to esplora client (thunderbiscuit)

Pull request description:

  ### Description
  The bdk_esplora crate currently doesn't expose the [`async-https-rustls` flag offered by the rust-esplora-client](ef1925e1ee/Cargo.toml (L44)) crate and instead requires users to build using the `default-tls` flag on reqwest, which uses the platform-specific openssl library when compiling. This creates complications for cross-compilation, notably for our Android builds that currently support 3 architectures (`arm64-v8a`, `armeabi-v7a`, and `x86_64`). In order to solve this we can either compile the openssl libraries for each of the platforms we want to support, or use the rustls-tls version of reqwest. The second options is much easier and requires less fiddling with the internals of the Android native development kit and cross-compilation rabbit holes.

  Before we merge this I want to make sure I understand the tradeoffs between the `native-tls` and the `rustls-tls` and confirm that there are not potential issues there, but from what I understand they should provide the same functionality/security, and because these are already available/exposed in reqwest and rust-esplora-client, I think this should be a fairly straightforward additional feature we offer.

  ### Changelog notice
  ```txt
  Added:
    - New async-https-rustls feature flag for the bdk_esplora crate, allowing to compile rust-esplora-client using rustls-tls instead of the default native-tls.
  ```

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 6817ca9bcbff957efb58f96886a30b6bd87c0cde
  realeinherjar:
    ACK 6817ca9bcb
  danielabrozzoni:
    ACK 6817ca9bcbff957efb58f96886a30b6bd87c0cde

Tree-SHA512: 1d417da7cf85e157d71f56442a06e817e8741822d7bff9089f7fbb70ff8b4854f1f52befbc348b849e9c98cae848b792d426cd5bf551e7a9089b15467d28efdd
2023-12-04 22:30:12 -06:00
志宇
55b680c194
Merge bitcoindevkit/bdk#1225: esplora: fix incorrect gap limit check in blocking client
43aed386bc33f8dfca53ea2ec166dea1ce3d42d3 esplora: also test the gap limit bounds in the async client (Antoine Poinsot)
cb713e5b8c74181518e8cfcd4095c862bc73f014 esplora: also fix the gap limit check in the async client (Antoine Poinsot)
2c4e90a76fea51cb7381242f55b1ca0f02e20d4e esplora: scan gap limit bounds testing (Antoine Poinsot)
18bd3296170e64aee6870cd96dde52a0078bbcb1 esplora: fix incorrect gap limit check in blocking client (Antoine Poinsot)

Pull request description:

  The gap limit was checked such as if the last_index was not None but the last_active_index was, we'd consider having reached it. But the last_index is never None for this check. This effectively made it so the gap limit was always 1: if the first address isn't used last_active_index will be None and we'd return immediately.

  Fix this by avoiding error-prone Option comparisons and correctly checking we've reached the gap limit before breaking out of the loop.

ACKs for top commit:
  danielabrozzoni:
    ACK 43aed386bc33f8dfca53ea2ec166dea1ce3d42d3
  evanlinjin:
    ACK 43aed386bc33f8dfca53ea2ec166dea1ce3d42d3

Tree-SHA512: c6a172e0627380add56aec79e7fe36c0358e092b59f0bea8885d3524e65c10336291943efe6aeb5cc83f90c4f2146ed63215e56e08583d703b6ab57284487f03
2023-11-27 09:40:50 +08:00
Antoine Poinsot
43aed386bc
esplora: also test the gap limit bounds in the async client 2023-11-24 12:21:16 +01:00
Antoine Poinsot
cb713e5b8c
esplora: also fix the gap limit check in the async client 2023-11-24 12:21:14 +01:00
Antoine Poinsot
2c4e90a76f
esplora: scan gap limit bounds testing 2023-11-24 12:21:13 +01:00
Antoine Poinsot
18bd329617
esplora: fix incorrect gap limit check in blocking client
The gap limit was checked such as if the last_index was not None but the
last_active_index was, we'd consider having reached it. But the
last_index is never None for this check. This effectively made it so the
gap limit was always 1: if the first address isn't used
last_active_index will be None and we'd return immediately.

Fix this by avoiding error-prone Option comparisons and correctly
checking we've reached the gap limit before breaking out of the loop.
2023-11-24 12:21:12 +01:00
Daniela Brozzoni
9e681b39fb
Merge bitcoindevkit/bdk#1190: Add Wallet::list_output method
278210bb8918923005e80968df3dfcc3372c0a5c docs(bdk): clarify `insert_txout` docs (志宇)
6fb45d8a735ec8db9142489d86107de192e0fa9c test(bdk): add `test_list_output` (志宇)
e803ee901002cae4db5ebf3544eb42c6cf81e5e2 feat(bdk): add `Wallet::list_output` method (志宇)
82632897aaa4ea0ac24803f58fbd13d6dc9c4357 refactor(bdk)!: rename `LocalUtxo` to `LocalOutput` (志宇)

Pull request description:

  Fixes #1184

  ### Description

  Introduce `Wallet::list_output` method that lists all outputs (both spent and unspent) in a consistent history.

  ### Changelog notice

  - Rename `LocalUtxo` to `LocalOutput`.
  - Add `Wallet::list_output` method.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  notmandatory:
    re-ACK 278210bb8918923005e80968df3dfcc3372c0a5c
  danielabrozzoni:
    ACK 278210bb8918923005e80968df3dfcc3372c0a5c

Tree-SHA512: 151af0e05e55d9c682271ef0c7a82e189531db963f65aa62c2ba0507f203dde39ab7561521c56e72c26830828e94ff96b7bd7e3f46082b23f79c5e0f89470136
2023-11-21 16:54:21 +01:00
thunderbiscuit
6817ca9bcb
ci: pin hyper-rustls version to 0.24.0 for 1.57 MSRV 2023-11-20 20:02:31 -05:00
Steve Myers
73862be3ba
Merge bitcoindevkit/bdk#1204: chore: remove bdk dependency on log and dev dependency on env_logger
02fa34089623ea43e9c62003e3b829d10dec5a14 chore: remove bdk dependency on log and dev dependency on env_logger (Steve Myers)

Pull request description:

  ### Description

  As suggested by @TheBlueMatt we shouldn't use the `log` crate because even though it is a rust-lang project is may depend on some other crates that aren't as well maintained. Since we were only use `log` in a few places and not it any other bdk workspace projects except the `bdk` package I removed it.

  ### Notes to the reviewers

  For consistency I also removed the `env_logger` from the dev dependencies since it was only being used in a few places in a couple examples and println! is adequate for examples.

  ### Changelog notice

  None

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: beb9e4d465112090093590c45e3e5e2286a99a819312512eb3e5b40d0eade9740314bb8e45a2ad3fa0a4c86e32711d2ef8f966842815874b9315fd0b63bc7283
2023-11-20 15:37:34 -08:00
Steve Myers
02fa340896
chore: remove bdk dependency on log and dev dependency on env_logger 2023-11-20 15:18:29 -08:00
thunderbiscuit
4ee41dbc40
build(esplora): Add async-https-rustls flag to esplora client 2023-11-20 16:16:27 -05:00
志宇
278210bb89
docs(bdk): clarify insert_txout docs
Inserted txouts will not be shown in `list_unspent` or `list_output`.
2023-11-21 05:06:53 +08:00
志宇
6fb45d8a73
test(bdk): add test_list_output 2023-11-21 04:38:04 +08:00
志宇
e803ee9010
feat(bdk): add Wallet::list_output method 2023-11-21 04:38:03 +08:00
志宇
82632897aa
refactor(bdk)!: rename LocalUtxo to LocalOutput 2023-11-21 04:35:00 +08:00
Steve Myers
46d39beb2c
Merge bitcoindevkit/bdk#1028: Add CreateTxError and use as error type for TxBuilder::finish()
00ec19ef2d59b6268424105f3d1947ab637b8c0c ci: fix MSRV pinning for rustls 0.21.9 (Steve Myers)
77f9977c02683071748f5fd6d07bde4b2d1f4a12 feat(wallet): Add infallible Wallet get_address(), get_internal_address functions (Steve Myers)
9e7d99e3bf9687251930c9a6bc5f1fe6a7c78bcb refactor(bdk)!: add context specific error types, remove top level error mod (Steve Myers)

Pull request description:

  ### Description

  To remove some places where there were `.expect("TODO")` I added a new `CreateTxError` type which is returned from `TxBuilder::finish()`. I also updated related tests and doc tests.

  Fixes https://github.com/bitcoindevkit/bdk/issues/996#issuecomment-1621036206

  Also added fallible `Wallet::try_get_address()` and `try_get_internal_address()`  to return `Result` with a possible `D:WriteError` when a PersistBackend is used. This should fix #996.

  I removed catch-all bdk::Error and replaced usages with new types and updated related functions, fixes #994.

  ### Notes to the reviewers

  ~~I didn't add all possible bdk::Error types that `Wallet::create_tx()` and `TxBuilder::finish()` functions might throw. It's probably not too much more work but will take a bit more research so I want to make sure this is the right general approach first.~~

  I added `anyhow` to the dev-dependencies so I could remove some `.expect()` lines from the docs tests and make the examples closer to what an end user should do.  I also used the `anyhow!()` macro to replace a few places that were using the `bdk::Error::Generic` in example code.

  I also moved the module level error.rs file to wallet/error.rs so no one would be tempted to make any new catch all errors and to make it clear that all the errors in it are wallet module related.

  ### Changelog notice

  Changed

  - Updated bdk module to use new context specific error types
    - wallet: MiniscriptPsbtError, CreateTxError, BuildFeeBumpError error enums
    - coin_selection: module Error enum
  - Renamed fallible Wallet address functions to try_get_address() and try_get_internal_address()

  Removed

  - Removed catch-all top level bdk::Error enum
  - Removed impl_error macro

  Added

  -  Added infallible Wallet get_address(), get_internal_address functions

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

Top commit has no ACKs.

Tree-SHA512: a87c0856d71f9c945d12b6de6d368f49bd62d73886ac46ac83d00ddb81f2c38c5233ba053e40c76dea73ee7bfc19dac510eec5d7c9026ae50a2dc7308ac4786f
2023-11-16 12:36:49 -06:00
Steve Myers
00ec19ef2d
ci: fix MSRV pinning for rustls 0.21.9 2023-11-16 11:56:09 -06:00
Steve Myers
77f9977c02
feat(wallet): Add infallible Wallet get_address(), get_internal_address functions
refactor!(wallet)!: rename fallible Wallet try_get_address(), try_get_internal_address functions
2023-11-16 11:18:11 -06:00
Steve Myers
9e7d99e3bf
refactor(bdk)!: add context specific error types, remove top level error mod
refactor(bdk)!: remove impl_error macro
refactor(wallet)!: add MiniscriptPsbtError, CreateTxError, BuildFeeBumpError error enums
refactor(coin_selection)!: add module Error enum
test(bdk): use anyhow dev-dependency for all tests
2023-11-16 10:24:35 -06:00
Daniela Brozzoni
cc552c5f91
Merge bitcoindevkit/bdk#1220: chore: fix typos and remove unused speculos dockerfiles
27a63abd1e7c87aaf3e07f8023370887a270c61a chore: typos fixed (Einherjar)

Pull request description:

  ### Description

  Fixes the typos and remove unused speculos dockerfiles that was done in #1165.
  Moving these changes into this PR to be merged first.
  Then, we can rebase #1165 and make it only related to CI and Nix.
  (Maybe do a big squash 😄)

  ## Note to Reviewers

  About the speculos stuff, we are not using them, removed in #793,
  more specifically in 3f5a78ae3b1e6c3f0a6acc98bb2445c895cfd743.

  ### Changelog notice

  - Fix typos in codebase and docs
  - Remove unused CI tests with hardware signer Dockerfiles

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK 27a63abd1e7c87aaf3e07f8023370887a270c61a

Tree-SHA512: a01101d0741e2b0e1d1254b5cae670c5a936bb0b89332c102feb57d58d2b9ae995ed4436068b0dc5fae73dbe22431c3143d6e04cdc12eab991bd726cfd2fbe25
2023-11-16 14:32:28 +01:00
Einherjar
27a63abd1e
chore: typos fixed 2023-11-16 07:25:20 -06:00
Steve Myers
bc8d6a396b
Merge bitcoindevkit/bdk#1178: LocalChain with hardwired genesis block
f1b112e8f9563c2afb9097911ee5e1afbbc55d22 docs(bitcoind_rpc): update docs for `Emitter::new` (志宇)
9a250baf6203a077fcfc03c3f6b386d5fba03d60 chore: make clippy happy (志宇)
79b84bed0ec399a375490c2c0f16c6ea3f5969b6 feat(bdk): changeset's `Append` impl checks that network is consistent (志宇)
06a956ad20ca5f1dcd108e45a1a1fed924128cdb feat!: change `load_from_persistence` to return an option (志宇)
c3265e2514070bd4da92ca343fe884e13e831360 test(bdk): add tests for wallet constructor methods (志宇)
96f1d94e2c8378d820a59e5ceafe686477243bf8 test(file_store): add construction method tests (志宇)
1886dc4fe743408132c3257afc1cacbb4d964105 chore(examples): use `Wallet::new_or_load` method where appropriate (志宇)
24994a3ed47aacf203ca0b456eb22f4b93ec58a8 feat(file_store)!: have separate methods for creating and opening Store (志宇)
d294e2e3189dc14efe5b9916cf83f5e7f8592c64 feat(wallet)!: add `new_or_load` methods (志宇)
7c6cbc4d9f7349e769594151936b3e2947b79d00 chore(file_store): rm empty test file (志宇)
6cf3963c6cfeacc8cd9d59bdb0bafded5022baaf feat(bdk)!: have separate methods for creating and loading `Wallet` (志宇)
7d5f31f6cc323241e866c136656f9674e0bf7c53 feat(chain, file_store): add `is_empty` method to `PersistBackend` trait (志宇)
5998a228191caccfaeac2b38ed4f319994b944c1 feat!: `LocalChain` with hardwired genesis checkpoint (志宇)

Pull request description:

  closes #1079
  closes #1107

  ### Description

  Many methods of `TxGraph` require a `chain_tip: BlockId` input to use against a `ChainOracle` implementation. This is used to ask the `ChainOracle` implementation whether a certain block exists in the chain identified by the `chain_tip`. This guarantees that the `TxGraph` methods will return a consistent history of transactions.

  However, the `ChainOracle` trait's `get_chain_tip` method returns an option of `BlockId`. It becomes unclear what to do when `get_chain_tip` returns `None`.

  This PR changes the `ChainOracle::get_chain_tip` method to always return a `BlockId` (no `Option`). `LocalChain` now hardwires the genesis block in order to implement `ChainOracle`.

  `bdk::Wallet` and `bdk_file_store::Store` are changed to have separate constructor methods for initializing a fresh instance and recovering a previous instance from persistence.

  ### Notes to the reviewers

  ### Changelog notice

  - Changed `ChainOracle::get_chain_tip` method to return a `BlockId` instead of an `Option` of a `BlockId`.
  - Refactored `LocalChain` so that the genesis `BlockId` is hardwired. This way, the `ChainOracle::get_chain_tip` implementation can always return a tip.
  - Add `is_empty` method to `PersistBackend`. This returns true when there is no data in the persistence.
  - Changed `Wallet::new` to initialize a fresh wallet only.
  - Added `Wallet::load` to restore an instance of a wallet.
  - Replaced `Store::new` with separate methods to create/open the database file.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

Top commit has no ACKs.

Tree-SHA512: 31b75fb53cc451f1fce7e409f1112c43973db7e8b5b31640e01e5b52089683b60320565427d6ea0478ff4c8680dbdb9272fdab08aef69d30f257da52e731e1a3
2023-11-15 18:07:47 -06:00
志宇
f1b112e8f9
docs(bitcoind_rpc): update docs for Emitter::new 2023-11-16 07:23:56 +08:00
志宇
9a250baf62
chore: make clippy happy 2023-11-16 07:17:16 +08:00
志宇
79b84bed0e
feat(bdk): changeset's Append impl checks that network is consistent 2023-11-16 07:07:49 +08:00
志宇
06a956ad20
feat!: change load_from_persistence to return an option
`PersistBackend::is_empty` is removed. Instead, `load_from_persistence`
returns an option of the changeset. `None` means persistence is empty.
This is a better API than a separate method. We can now differentiate
between a persisted single changeset and nothing persisted.

`Store::aggregate_changeset` is refactored to return a `Result` instead
of a tuple. A new error type (`AggregateChangesetsError`) is introduced
to include the partially-aggregated changeset in the error. This is a
more idiomatic API.
2023-11-16 07:07:49 +08:00
志宇
c3265e2514
test(bdk): add tests for wallet constructor methods 2023-11-16 07:07:49 +08:00
志宇
96f1d94e2c
test(file_store): add construction method tests 2023-11-16 07:07:48 +08:00
志宇
1886dc4fe7
chore(examples): use Wallet::new_or_load method where appropriate 2023-11-16 07:07:48 +08:00
志宇
24994a3ed4
feat(file_store)!: have separate methods for creating and opening Store 2023-11-16 07:07:48 +08:00
志宇
d294e2e318
feat(wallet)!: add new_or_load methods
These methods try to load wallet from persistence and initializes the
wallet instead if non-existant.

An internal helper method `create_signers` is added to reuse code.
Documentation is also improved.
2023-11-16 07:07:48 +08:00
志宇
7c6cbc4d9f
chore(file_store): rm empty test file 2023-11-16 07:04:08 +08:00
志宇
6cf3963c6c
feat(bdk)!: have separate methods for creating and loading Wallet
`Wallet::new` now creates a new wallet. `Wallet::load` loads an existing
wallet. The network type is now recoverable from persistence. Error
types have been simplified.
2023-11-16 07:04:08 +08:00
志宇
7d5f31f6cc
feat(chain, file_store): add is_empty method to PersistBackend trait 2023-11-16 07:01:56 +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
Steve Myers
d6a0cf0795
Merge commit 'refs/pull/1121/head' of github.com:bitcoindevkit/bdk 2023-11-14 11:51:48 -06:00
Einherjar
6e27e66738
feat: add dependabot
Fixes #1118.
Adds `dependabot.yml` to `.github/` to check for `"github-action"`
updates on a `"weekly"` basis.
This does not touch Rust code or Cargo workflows.

It will  create PRs and we would need to approve them
(they would be subject to the same merge policy)
to instantiate the proposed dependabots into `master`.
2023-11-14 11:26:52 -06:00
Daniela Brozzoni
f382fa9230
Merge bitcoindevkit/bdk#1202: fix(chain): filter coinbase tx not in best chain
991cb77b6fbeedbf52d1bd9aa6b3d680f8269969 fix(chain): filter coinbase tx not in best chain (Wei Chen)

Pull request description:

  ### Description

  Fixes #1144.
  Coinbase transactions cannot exist in the mempool and be unconfirmed. `TxGraph::try_get_chain_position` should always return `None` for coinbase transactions not anchored in best chain.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 991cb77b6fbeedbf52d1bd9aa6b3d680f8269969
  danielabrozzoni:
    ACK 991cb77b6fbeedbf52d1bd9aa6b3d680f8269969

Tree-SHA512: 9e06d8404708eee050c96807a876a470303f4983666c82c56c17d97c2d4b72784e75271279fd393c53a6a967a352aea1ef2762da71ac4bb58f7a0c2f05354948
2023-11-14 14:58:46 +01:00
Daniela Brozzoni
e71770f93e
Merge bitcoindevkit/bdk#1206: chore: rename ConfirmationTimeAnchor to ConfirmationTimeHeightAnchor
0112c67b6031b55a6c73f797db52d64a1b4ee38a chore: rename `ConfirmationTimeAnchor` to `ConfirmationTimeHeightAnchor` (Wei Chen)

Pull request description:

  ### Description

  Closes #1187.
  An `Anchor` implementation that records both height and time should have both attributes included in the name.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 0112c67b6031b55a6c73f797db52d64a1b4ee38a

Tree-SHA512: 024cbc83c8aca36baeaf2ce36979d62f235ffea7702e7ac8d4e7669cbc1730f7e1469ba78bf3da6c5a14abedbf1a9e832bdd66fdaa154ad2bef29cb187e1c504
2023-11-14 14:52:30 +01:00
Daniela Brozzoni
298f6cb1e8
ci: Pin jobserver after cc
Since now only cc depends on jobserver, it should be pinned after we pin cc
2023-11-13 19:06:54 +01:00
Daniela Brozzoni
3fdab87ee7
Merge bitcoindevkit/bdk#1200: fix(bdk): Check if we're using the correct internal key before signing
e553231eae45dc6d263a1fce2a3a9c46f6af2510 fix(bdk): Check if we're using the correct... ...internal key before signing (Daniela Brozzoni)

Pull request description:

  ### Description

  Fixes #1142

  We would previously sign with whatever x_only_pubkey we had in hand, without first checking if it was the right key or not. This effectively meant that adding multiple taproot PrivateKey signers would produce unbroadcastable transactions.

  ### Changelog notice

  - Fix a bug related to taproot signing with internal keys. We would previously sign with the first private key we had, without checking if it was the correct internal key or not.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK e553231eae45dc6d263a1fce2a3a9c46f6af2510

Tree-SHA512: c4abbcd27935b8ce80a70b6e0843507866e3d075939f0b01504c090929ed96b4b9c6fee599f701e69960a6c86175682cc6d7f8cc4c3fb1d08a74b7563f8ca145
2023-11-13 10:09:02 +01:00
Daniela Brozzoni
855c61a6ab
Merge bitcoindevkit/bdk#1145: fix(electrum): fixed chain sync issue
1010efd8d68e886cc46f0ac2f016630b670ea73c fix(electrum): fixed chain sync issue (Wei Chen)

Pull request description:

  ### Description

  This may or may not fix #1125.
  Fixed what appeared to be a logic error in `construct_update_tip` in `electrum_ext.rs` that caused the local chain tip to always be a block behind the newest confirmed block.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK 1010efd8d68e886cc46f0ac2f016630b670ea73c - although I've been able to reproduce the issue in #1125, I'm convinced that this PR fixes at least a bug, as demonstrated in #1171 (yet to be reviewed and merged).

Tree-SHA512: 92790e9072d17be74d2cd24bec3503e1ad5d97f728ee81490eeb09ac3f8d4a3a7e8d9628e943bc801246d5bfd345152c11d5dbe25246f5a57b3118727d3ae315
2023-11-13 09:36:10 +01:00
Wei Chen
0112c67b60
chore: rename ConfirmationTimeAnchor to ConfirmationTimeHeightAnchor
An `Anchor` implementation that records both height and time should have
both attributes included in the name.
2023-11-12 21:31:47 +08:00
Wei Chen
1010efd8d6
fix(electrum): fixed chain sync issue
Fixed a logic error in `construct_update_tip` in `electrum_ext.rs` that caused
the local chain tip to always be a block behind the newest confirmed block.
2023-11-11 20:52:37 +08:00
Wei Chen
991cb77b6f
fix(chain): filter coinbase tx not in best chain
Coinbase transactions cannot exist in the mempool and be unconfirmed.
`TxGraph::try_get_chain_position` should always return `None` for coinbase
transactions not anchored in best chain.
2023-11-11 02:55:58 +08:00
Daniela Brozzoni
e553231eae
fix(bdk): Check if we're using the correct...
...internal key before signing

Fixes #1142

We would previously sign with whatever x_only_pubkey we had in hand,
without first checking if it was the right key or not. This effectively
meant that adding multiple taproot PrivateKey signers would produce
unbroadcastable transactions.
2023-11-10 18:25:46 +01:00
Daniela Brozzoni
0a7b60f0f7
Merge bitcoindevkit/bdk#1109: Further improve unconfirmed tx conflict resolution
afbf83c8b0d5c97495e6ceaa39963415edef6911 chain(fix): conflict resolution for txs with same last_seen (Wei Chen)

Pull request description:

  ### Description

  Fixes #1102. If a conflicting tx has the same `last_seen`, then we check lexicographical sorting of txids.

  ### Notes to the reviewers

  The tests for this fix exist in the `TxTemplate` structure in #1064 which may need to be merged first.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK afbf83c8b0d5c97495e6ceaa39963415edef6911

Tree-SHA512: 91b8fbff305b715247501b861ab7ea9e9d9ef99248b05d14e01aacf7e64ad7826f35773e8998cf421dbd04f663714026084c6e817ac5365bce4844c8ea3b7e3f
2023-11-09 10:07:18 +01:00
Daniela Brozzoni
0ecc0280c0
doc(bdk): Clarify the absolute_fee, fee_rate docs
Fixes #1066
2023-11-09 09:00:49 +01:00
Wei Chen
afbf83c8b0
chain(fix): conflict resolution for txs with same last_seen
The tx conflict `Scenario` test for unconfirmed txs with the same
last_seen has been amended for its corresponding conflict
resolution bug fix.
2023-11-09 05:46:09 +08:00
志宇
2f2f138595
Merge bitcoindevkit/bdk#1182: chore: fix MSRV for flate2
95250fc44ed1372e77995d04ac2b380e0cb126a0 ci(chain): downgrade hashbrown dependency to 0.9.1 to fix ahash related MSRV issue (Steve Myers)
f17df1e1338c63cb79b5f9b2223dba347244c432 ci: more fixed dependencies for MSRV 1.57.0 (Vladimir Fomene)

Pull request description:

ACKs for top commit:
  notmandatory:
    ACK 95250fc44ed1372e77995d04ac2b380e0cb126a0
  realeinherjar:
    ACK 95250fc44ed1372e77995d04ac2b380e0cb126a0
  evanlinjin:
    ACK 95250fc44ed1372e77995d04ac2b380e0cb126a0

Tree-SHA512: ad090713d97cf778598bb4acee200d7acbc987fe74964f171cc9939149251bddce9474b750371df26d3f6548780f4db2c17b3fe2cf5f6d627c808d682c929918
2023-11-06 11:15:16 +08:00
Steve Myers
95250fc44e
ci(chain): downgrade hashbrown dependency to 0.9.1 to fix ahash related MSRV issue 2023-11-03 21:51:04 -05:00
Vladimir Fomene
f17df1e133
ci: more fixed dependencies for MSRV 1.57.0 2023-11-03 21:50:11 -05:00
Steve Myers
3569acca0b
chore: add meta data to bitcoind_rpc crate 2023-10-12 09:33:34 -05:00
Steve Myers
2e4bc3c5e2
Bump bdk version to 1.0.0-alpha.2
Bump bdk_chain to 0.6.0
Bump bdk_electrum to 0.4.0
Bump bdk_esplora to 0.4.0
2023-10-11 17:30:36 -05:00
Daniela Brozzoni
6ebdd195e2
Merge bitcoindevkit/bdk#1164: ref(chain): Rename direct_conflicts_of_tx to direct_conflitcs
d5c87c49a82c5cd3a4558e61fe9984f0ae8c6cb7 ref(chain): Rename direct_conflicts_of_tx to... ...direct_conflitcs (Daniela Brozzoni)
009408d24361235c1d85b7d147983cff7b0fc191 ci: Pin jobserver to 0.1.26 to keep MSRV (Daniela Brozzoni)

Pull request description:

  Fixes #1138

  ### Changelog notice

  - rename `TxGraph::direct_conflicts_of_tx` to `TxGraph::direct_conflicts`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK d5c87c49a82c5cd3a4558e61fe9984f0ae8c6cb7

Tree-SHA512: 10072c65025d5fcc5d90c61ecba1dad53bcd10929326ab18ddadb21322841203aa5861adc9c5f200bbc57b0fe59dd4859dc3672870a0ad343fd8a660fd8aa40e
2023-10-10 17:16:54 +02:00
Daniela Brozzoni
d5c87c49a8
ref(chain): Rename direct_conflicts_of_tx to...
...direct_conflitcs

Fixes #1138
2023-10-10 16:44:51 +02:00
Daniela Brozzoni
009408d243
ci: Pin jobserver to 0.1.26 to keep MSRV 2023-10-10 16:44:50 +02:00
Steve Myers
38d69c947c
Merge bitcoindevkit/bdk#1041: Add bitcoind_rpc chain source module.
85c62532a55cfc94eade4d20ca3075dc4cd4882e docs(bitcoind_rpc): better `Emitter::mempool` explanation (志宇)
b69c13ddf6aa7cfb9be8c841b255e7f5f13ad328 example_bitcoind_rpc: tweaks (志宇)
5f34df8489fedae2aa3fd001036cc9ef6abe9a7a bitcoind_rpc!: bring back `CheckPoint`s to `Emitter` (志宇)
57590e0a1f2dad09a63fadb11f01e9f704cdcffb bitcoind_rpc: rm `BlockHash` from `Emitter::last_mempool_tip` (志宇)
6d4b33ef91a6c3e3443f6321cf3e3d186f77c595 chain: split `IndexedTxGraph::insert_tx` into 3 methods (志宇)
4f5695d43add3eab37ab12e897ac7c49f0d0787e chain: improvements to `IndexedTxGraph` and `TxGraph` APIs (志宇)
150d6f8ab6cd1eb1c9448d61e7bd71db0dd32a01 feat(example_bitcoind_rpc_polling): add example for RPC polling (志宇)
4f10463d9eaad9365b87dd99d49f0ddb8be673ee test(bitcoind_rpc): add no_agreement_point test (志宇)
a73dac2d91b29c4ba05f606f81e511fbf1f9ec7f test(bitcoind_rpc): initial tests for `Emitter` (志宇)
bb7424d11d3a4bd837ddde0f42f9abd93d56aee1 feat(bitcoind_rpc): introduce `bitcoind_rpc` crate (志宇)
240657b1674ad901c77090ee1fa96dc0d71e91d7 chain: add batch-insert methods for `IndexedTxGraph` (志宇)
43bc813c6498b5b021d70a6127ff7e57d7337813 chain: add helper methods on `CheckPoint` (志宇)
b3db5ca9df4302fddcd5474569849371f2be7e2d feat(chain): add `AnchorFromBlockPosition` trait (志宇)
f795a43cc72fdb4ef26ca349c4cb4f4bfd3b90b5 feat(example_cli): allow chain specific args in examples (志宇)

Pull request description:

  ### Description

  This PR builds on top of #1034 and adds the `bitcoind_rpc` chain-src module and example.

  ### Notes to the reviewers

  Don't merge this until #1034 is in!

  ### Changelog notice

  * Add `bitcoind_rpc` chain-source module.
  * Add `example_bitcoind_rpc` example module.
  * Add `AnchorFromBlockPosition` trait which are for anchors that can be constructed from a given block, height and position in block.
  * Add helper methods to `IndexedTxGraph` and `TxGraph` for batch operations and applying blocks directly.
  * Add helper methods to `CheckPoint` for easier construction from a block `Header`.

  ### Checklists

  * [x] Add test: we should detect when an initially-confirmed transaction is "unconfirmed" during a reorg.
  * [x] Improve `example_bitcoind_rpc`: add `live` command.
  * [x] Improve docs.
  * [x] Reintroduce `CheckPoint`.

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  notmandatory:
    Re ACK 85c62532a55cfc94eade4d20ca3075dc4cd4882e

Tree-SHA512: 88dbafbebaf227b18c69f2ea884e3e586bf9c11e5e450eb4872ade1d1ccd5cf1e33ce9930a6f5aa918baa3e92add7503858b039b8c9d553a281ad6d833f08a49
2023-10-09 15:49:57 -05:00
志宇
67eec36db4
Merge bitcoindevkit/bdk#1152: fix(wallet_esplora): missing_heights uses the graph update
b1461f05d05a0b9cf056a9604032468064ca1a05 fix(wallet_esplora): missing_heights uses the... ...graph update (Daniela Brozzoni)

Pull request description:

  Fixes #1151.

  When wallet_esplora_* was used to sync a wallet containing a transaction confirmed some time ago (more than 10-15 blocks ago), the transaction would be stuck in an "unconfirmed" state forever.

  At the first scan time, `update_local_chain` would just fetch the last 10 to 15 blocks (depending on the server used), and `tx_graph.missing_heights` wouldn't return the tx's confirmation block as it was called on the original, non-updated tx_graph.
  So, after the first scan, we would have a transaction in memory with an anchor that doesn't exist in our local_chain, and try_get_chain_position would return unconfirmed.

  When scanning again, missing_heights would find the missing anchor, but `update_local_chain` wouldn't include it as it's older than ASSUME_FINAL_DEPTH.

  The missing block would be downloaded every time, but never included in the local_chain, and the transaction would remain unconfirmed forever.

  Here we call missing_heights on the updated graph, so that it can correctly return the anchor height, and `update_local_chain` can fetch it and include it in the chain.

  ### Notes to the reviewers

  I'm not sure if this is the right approach, so I'm opening this PR to gather feedback. I still need to add tests, I'll do so once we decide if this is the right way to go or not.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  evanlinjin:
    ACK b1461f05d05a0b9cf056a9604032468064ca1a05

Tree-SHA512: ba0cf85929644ee737dbc77e6afec662845532de0f120917aa6000ca8f5db79d0cb3971bd92285b5c5b5d26042b60b6c8536f50c9bd49615e31f5da28e80a509
2023-10-10 01:15:30 +08:00
志宇
85c62532a5
docs(bitcoind_rpc): better Emitter::mempool explanation
Also better docs for `Emitter` fields.
2023-10-10 01:04:30 +08:00
志宇
b69c13ddf6
example_bitcoind_rpc: tweaks
* avoid holding mutex lock over io
* document `CHANNEL_BOUND` const
* use the `relevant` variant of `batch_insert_unconfirmed`
* print elapsed time in stdout for various updates
2023-10-10 01:04:30 +08:00
志宇
5f34df8489
bitcoind_rpc!: bring back CheckPoints to Emitter
* `bdk_chain` dependency is added. In the future, we will introduce a
  separate `bdk_core` crate to contain shared types.
* replace `Emitter::new` with `from_height` and `from_checkpoint`
  * `from_height` emits from the given start height
  * `from_checkpoint` uses the provided cp to find agreement point
* introduce logic that ensures emitted blocks can connect with
  receiver's `LocalChain`
* in our rpc example, we can now `expect()` chain updates to always
  since we are using checkpoints and receiving blocks in order
2023-10-09 22:14:04 +08:00
志宇
57590e0a1f
bitcoind_rpc: rm BlockHash from Emitter::last_mempool_tip
Instead of comparing the blockhash against the emitted_blocks map
to see whether the block is part of the emitter's best chain, we
reduce the `last_mempool_tip` height to the last agreement height
during the polling logic.

The benefits of this is we have tighter bounds for avoiding re-
emission. Also, it will be easier to replace `emitted_blocks` to
a `CheckPoint` (since we no longer rely on map lookup).
2023-10-09 22:14:04 +08:00
志宇
6d4b33ef91
chain: split IndexedTxGraph::insert_tx into 3 methods
Instead of inserting anchors and seen_at timestamp in the same method,
we have three separate methods. This makes the API easier to understand
and makes `IndexedTxGraph` more consistent with the `TxGraph` API.
2023-10-09 22:14:04 +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
志宇
150d6f8ab6
feat(example_bitcoind_rpc_polling): add example for RPC polling 2023-10-09 22:14:03 +08:00
志宇
4f10463d9e
test(bitcoind_rpc): add no_agreement_point test
Co-authored-by: Steve Myers <steve@notmandatory.org>
2023-10-09 22:14:03 +08:00
志宇
a73dac2d91
test(bitcoind_rpc): initial tests for Emitter 2023-10-09 22:14:03 +08:00
志宇
bb7424d11d
feat(bitcoind_rpc): introduce bitcoind_rpc crate 2023-10-09 22:14:03 +08:00
志宇
240657b167
chain: add batch-insert methods for IndexedTxGraph 2023-10-09 22:14:03 +08:00
志宇
43bc813c64
chain: add helper methods on CheckPoint
* `CheckPoint::from_header` allows us to construct a checkpoint from
  block header.
* `CheckPoint::into_update` transforms the cp into a
  `local_chain::Update`.
2023-10-09 22:14:03 +08:00
志宇
b3db5ca9df
feat(chain): add AnchorFromBlockPosition trait
This is useful for block-by-block chain sources. We can determine the
tx's anchor based on the block, block height and tx position in the
block.
2023-10-09 22:14:03 +08:00
志宇
f795a43cc7
feat(example_cli): allow chain specific args in examples
So you can pass in the esplora/electrum/bitcoind_rpc server details in
the example.

Co-authored-by: LLFourn <lloyd.fourn@gmail.com>
2023-10-09 22:14:02 +08:00
Daniela Brozzoni
b1461f05d0
fix(wallet_esplora): missing_heights uses the...
...graph update

Fixes #1151.
When wallet_esplora_* was used to sync a wallet containing a transaction
confirmed some time ago (more than 10-15 blocks ago), the transaction would
be stuck in an "unconfirmed" state forever.

At the first scan time, `update_local_chain` would just fetch the last 10 to
15 blocks (depending on the server used), and `tx_graph.missing_heights`
wouldn't return the tx's confirmation block as it was called on the
original, non-updated tx_graph.
So, after the first scan, we would have a transaction in memory with an
anchor that doesn't exist in our local_chain, and try_get_chain_position
would return unconfirmed.

When scanning again, missing_heights would find the missing anchor, but
`update_local_chain` wouldn't include it as it's older than
ASSUME_FINAL_DEPTH.

The missing block would be downloaded every time, but never included in
the local_chain, and the transaction would remain unconfirmed forever.

Here we call missing_heights on the updated graph, so that it can
correctly return the anchor height, and `update_local_chain` can
fetch it and include it in the chain.
2023-10-09 15:09:14 +02:00
Daniela Brozzoni
77cde96229
Merge bitcoindevkit/bdk#1157: chore: pin byteorder and webpki to fix MSRV
1db3f87a4850c11b010ceafeba8a64ee0e54e022 chore: pin `byteorder` and `webpki` to fix MSRV (志宇)

Pull request description:

  * pin `byteorder` to 1.4.3
  * pin `webpki` to 0.22.2
  * it's tokio:1.33.0 that needs to be pinned to 1.29.1
  * fix README MSRV comments

ACKs for top commit:
  danielabrozzoni:
    utACK 1db3f87a4850c11b010ceafeba8a64ee0e54e022

Tree-SHA512: 4c2dc009ea117dd7ca18c7a836eb2b169c68d6ccaf84f85bcc2d4a3bcb7b008ad99f1dadf933b20c9d6ca6cc761e89dbafa99f99e31776e291f480cd6a112b1d
2023-10-09 15:03:49 +02:00
志宇
1db3f87a48
chore: pin byteorder and webpki to fix MSRV
* pin `byteorder` to 1.4.3
* pin `webpki` to 0.22.2
* it's tokio:1.33.0 that needs to be pinned to 1.29.1
* fix README MSRV comments
2023-10-09 19:47:45 +08:00
志宇
4a65a12c4f
Merge bitcoindevkit/bdk#1104: refactor: use set_lookahead in set_lookahead_for_all
e89cf5a16a239d51ae9eb1857b55e7178e588b74 refactor: use set_lookahead in set_lookahead_for_all (Vladimir Fomene)

Pull request description:

  ### Description

  Use set_lookahead in set_lookahead_for_all.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  realeinherjar:
    ACK: e89cf5a16a239d51ae9eb1857b55e7178e588b74
  evanlinjin:
    ACK e89cf5a16a239d51ae9eb1857b55e7178e588b74

Tree-SHA512: 02d226be7adcfd5e23ecb9d17539b0e089cb55ddf9c6de980155960f8181f2d3ea3ac9a93b2c1b7e0a8d4e4c821d92f65405852c696c9a367193a42d60c1aac6
2023-10-08 03:49:33 +08:00
志宇
4ee11aae12
Merge bitcoindevkit/bdk#1064: Better tests for transaction conflict handling
6d601a7e885bfc627594b794b1a460be47799eea test(chain): Add test for conflicting transactions (Daniela Brozzoni)
48ca95b5412fd3719b749d33c85572941817e967 test(chain): Add test for walk_ancestors (Daniela Brozzoni)
59a2403e2802d27c51f2d30b5f8e1ed9f813dfcc test(chain): Introduce TxTemplate (Daniela Brozzoni)
6e511473a5e5730d5cad237c651c83dc4c5d8756 test(chain): add block_id! utility macro (Daniela Brozzoni)
62de55f12d910ac35180cbb3f0e4c4b353c44d11 fix(chain): Consider conflicting ancestors in... ...try_get_chain_pos (Daniela Brozzoni)
a3e8480ad9d41190da8de732dc8d00d636a0c911 doc(chain): Clarify direct_conflicts_of_tx's docs (Daniela Brozzoni)
4742d88ea322e43120fa96f6421a149294d26e3b feat(chain): Introduce TxAncestors, walk_ancestors (Daniela Brozzoni)
2f26eca607dc5de83a9bb12c33fa5336026ab3dd fix(chain): TxDescendants performs a BFS (Daniela Brozzoni)
486e0e143741a8c1312e7cb5258b3d43256dc9ec doc(chain): Fix typos (Daniela Brozzoni)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Fixes #1063.

  This PR introduces a new `TxTemplate` struct to test different transaction conflict scenarios in `TxGraph`.
  The following transaction conflict scenarios are tested:
  - 2 unconfirmed txs with different last_seens conflict. The most recent tx should be the only tx that appears in the list methods.
  - 3 unconfirmed txs with different last_seens conflict. The most recent tx should be the only tx that appears in the list methods.
  - An unconfirmed tx U conflicts with a tx anchored in orphaned block O. O has higher last_seen. O should be the only tx that appears in the list methods.
  - An unconfirmed tx U conflicts with a tx anchored in orphaned block O. U has higher last_seen. U should be the only tx that appears in the list methods.
  - Multiple unconfirmed txs conflict with a confirmed tx. None of the unconfirmed txs should appear in the list methods.
  - B and B' conflict. C spends B. B' is anchored in best chain. B and C should not appear in the list methods.
  - B and B' conflict. C spends B. B is anchored in best chain. B' should not appear in the list methods.
  - B and B' conflict. C spends both B and B'. C is impossible.
  - B and B' conflict. C spends both B and B'. C is impossible. B' is confirmed.
  - B and B' conflict. C spends both B and B'. C is impossible. D spends C.

  These tests revealed that `TxGraph::walk_conflicts` was not checking ancestors of the root tx for conflicts. `TxGraph::walk_conflicts` has been refactored to check for conflicting ancestor transactions by using a new `TxAncestors` iterator in `TxGraph`.

  ### Changelog notice

  - Introduced `tx_template` module
  - Introduced `TxGraph::TxAncestors` iterator
  - Refactored `TxGraph::walk_conflicts` to use `TxGraph::TxAncestors`
  - Added `walk_ancestors` to `TxGraph`

  ### Checklists
  All Submissions:

  - [x] I've signed all my commits
  - [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  - [x] I ran cargo fmt and cargo clippy before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  evanlinjin:
    ACK 6d601a7e885bfc627594b794b1a460be47799eea

Tree-SHA512: ea151392874c4312233e4e10299579f4eee4a7100ae344b4d7f19994284b49c1e43f37338bed931d16e77326021166ea0b94d6de3ccf50a8fabb25139a8e69b4
2023-10-06 00:20:13 +08:00
Daniela Brozzoni
a7dbc22df1
Merge bitcoindevkit/bdk#1146: fix: Remove dependency on unnecessary bdk_chain features
5e79b81a6a3f7012153fea469720fab153266479 fix: Remove dependency on unnecessary bdk_chain features (LLFourn)

Pull request description:

ACKs for top commit:
  danielabrozzoni:
    utACK 5e79b81a6a3f7012153fea469720fab153266479

Tree-SHA512: 02259c2c87b46a3b16a89648ce87b36fc88a2816074de7e4dd012231c07bb5e1c2f833b6c8cab7f469c84ed0a0bc254276a6c145763daf187b2e589493892cd8
2023-10-04 16:54:06 +02:00
Daniela Brozzoni
6d601a7e88
test(chain): Add test for conflicting transactions
Co-authored-by: Wei Chen <wzc110@gmail.com>
2023-10-04 14:00:49 +02:00
Daniela Brozzoni
48ca95b541
test(chain): Add test for walk_ancestors
Co-authored-by: Wei Chen <wzc110@gmail.com>
2023-10-04 14:00:47 +02:00
Daniela Brozzoni
59a2403e28
test(chain): Introduce TxTemplate
Co-authored-by: Wei Chen <wzc110@gmail.com>
2023-10-04 14:00:46 +02:00
Daniela Brozzoni
6e511473a5
test(chain): add block_id! utility macro
Co-authored-by: Wei Chen <wzc110@gmail.com>
2023-10-04 14:00:45 +02:00
Daniela Brozzoni
62de55f12d
fix(chain): Consider conflicting ancestors in...
...try_get_chain_pos

In try_get_chain_pos, when we notice that a transaction is not included
in the best chain, we check the transactions in mempool to find
conflicting ones, and decide based on that if our transaction is still
in mempool or has been dropped.
This commit adds a check for transactions conflicting with the
unconfirmed ancestors of our tx.

Co-authored-by: Wei Chen <wzc110@gmail.com>
2023-10-04 14:00:44 +02:00
LLFourn
5e79b81a6a
fix: Remove dependency on unnecessary bdk_chain features 2023-10-04 10:52:12 +11:00
Daniela Brozzoni
a3e8480ad9
doc(chain): Clarify direct_conflicts_of_tx's docs
Co-authored-by: Wei Chen <wzc110@gmail.com>
2023-10-03 15:12:35 +02:00
Daniela Brozzoni
4742d88ea3
feat(chain): Introduce TxAncestors, walk_ancestors
Co-authored-by: Wei Chen <wzc110@gmail.com>
2023-10-03 15:11:05 +02:00
Daniela Brozzoni
2f26eca607
fix(chain): TxDescendants performs a BFS
This commit also changes test_descendants_no_repeat to check
the order of the transactions returned
2023-10-03 15:11:04 +02:00
Daniela Brozzoni
486e0e1437
doc(chain): Fix typos
Co-authored-by: Wei Chen <wzc110@gmail.com>
2023-10-03 11:25:53 +02:00
Steve Myers
9bd528607a
Merge bitcoindevkit/bdk#1137: fix: Add the pinning of time/cc in README
f28e665c7dd1d929f0b4f80a79caecafaf4b385e ci: update code_coverage workflow to use rust stable version (Steve Myers)
edfd4c236d76c91b3599c333ae8456ed4f577064 fix: Add the pinning of time/cc in README (Daniela Brozzoni)

Pull request description:

  Should have been in #1135, sorry.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK f28e665c7dd1d929f0b4f80a79caecafaf4b385e

Tree-SHA512: e1c2c05f436da1fd59b9988628318c0563b2dbe85a5f4fb8aef4c35d7601c441a542e8a2c3591c02f3a05ad9456cfc2d3f5e8605064498a56a39766f5bcbc2e1
2023-10-02 19:21:36 -05:00
Steve Myers
f28e665c7d
ci: update code_coverage workflow to use rust stable version 2023-10-02 13:30:41 +02:00
Daniela Brozzoni
417963f168
Merge bitcoindevkit/bdk#1132: fix: bump electrum version to 0.18
fe654310d7e46a0e05c8282bd7804ac0d5203816 fix: bump electrum version to 0.18 (sjeohp)

Pull request description:

  Fixes https://github.com/bitcoindevkit/bdk/issues/1123

ACKs for top commit:
  danielabrozzoni:
    ACK fe654310d7e46a0e05c8282bd7804ac0d5203816

Tree-SHA512: 184b82ba13c76c7e4fe14dcf1f30ee19345618ecf7f8eeb859963067eafa6c21dd79d90b36a44cd2cb50d4002623c4811789f8dbed9445272114b72b35461f8c
2023-09-29 15:29:48 +02:00
Daniela Brozzoni
edfd4c236d
fix: Add the pinning of time/cc in README
Should have been in #1135, sorry.
2023-09-29 15:20:45 +02:00
sjeohp
fe654310d7
fix: bump electrum version to 0.18 2023-09-28 10:49:19 -06:00
Steve Myers
37d5e5319f
Merge bitcoindevkit/bdk#1135: ci: Pin time, cc in order to keep MSRV
ea6411c6850eef4f6c171b3035b3d70a8b2a9dc5 ci: Pin time, cc in order to keep MSRV (Daniela Brozzoni)

Pull request description:

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK ea6411c6850eef4f6c171b3035b3d70a8b2a9dc5

Tree-SHA512: e2400bd4a1583db8503efa05279f1d97b136dfbe63ae92bc33817fa6763f7f3b8789acf9aef0f36bb8a0486539637eaa101f638d223354d3c6193f2ab2ebdfdb
2023-09-28 09:41:17 -05:00
Daniela Brozzoni
ea6411c685
ci: Pin time, cc in order to keep MSRV 2023-09-28 13:03:47 +02:00
Steve Myers
4a1b96dcc4
Merge bitcoindevkit/bdk#1110: fix(esplora): use saturating_add in update_tx_graph()
bf9a4258496ef91bec4d15126d6e98a2450533ea ci: fix MSRV build by pinning tokio-util to 0.7.8 (Steve Myers)
d35668e76aa3ba429041305e54106c10429a8b1b ci(esplora): fix wasm cargo check by setting workspace resolver to version 2 (Steve Myers)
31d52e12c93469dc6af9a88eba42ad87315dd63b ci: fix msrv dependency versions for rustls-webpki and zip (Steve Myers)
6a5c9d7a00bfddbdf6bd279d003fefe3958dccc1 fix(esplora): use saturating_add in update_tx_graph() (Steve Myers)
4d1a9fd47ab61e1cba2d01fe1191df8c0064c767 test(esplora): add async_ext and blocking_ext integration tests (Steve Myers)

Pull request description:

  ### Description

  This fixes overflow error when calling update_tx_graph() from update_tx_graph_without_keychain().

  ### Notes to the reviewers

  You can reproduce the error by reverting 66a2bf5ef2a70f8de41941d2f07bec776d152b96.

  The tests could use some cleanup but get the job done for this PR.

  ### Changelog notice

  None

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

Top commit has no ACKs.

Tree-SHA512: eace00e0c289a7ac161985c4b8e46ad660ec0d6777cd74027ef1f0ab245daea87e34258233281796efb60473cf4f18d2647c090a14c0f05f3dc8a1950ebe9dab
2023-09-26 10:00:12 -05:00
Steve Myers
bf9a425849
ci: fix MSRV build by pinning tokio-util to 0.7.8 2023-09-25 21:09:46 -05:00
Steve Myers
d35668e76a
ci(esplora): fix wasm cargo check by setting workspace resolver to version 2
The resolver version must be set at the workspace level.
See: https://blog.rust-lang.org/2021/03/25/Rust-1.51.0.html#cargos-new-feature-resolver
2023-09-25 21:09:45 -05:00
Steve Myers
31d52e12c9
ci: fix msrv dependency versions for rustls-webpki and zip 2023-09-25 21:09:43 -05:00
Steve Myers
6a5c9d7a00
fix(esplora): use saturating_add in update_tx_graph()
This fixes overflow error when calling update_tx_graph() from update_tx_graph_without_keychain().
2023-09-25 21:09:42 -05:00
Steve Myers
4d1a9fd47a
test(esplora): add async_ext and blocking_ext integration tests 2023-09-25 21:09:40 -05:00
Daniela Brozzoni
f95506ba6a
Merge bitcoindevkit/bdk#969: Update documentation for fee_rate and fee_absolute methods in tx_builder.rs
e6519e3a52a1ab8023b5fdf423d8f748a3b0260d Enhance the documentation for the fee_rate and fee_absolute methods. (Jon Marrs)

Pull request description:

  ### Description

  This pr helps solve this issue: https://github.com/bitcoindevkit/bdk/issues/856

  I added documentation to the fee_rate() method to describe the units as either satoshis/vbyte (sats/vbyte) or satoshis/kwu (sats/kwu), depending on the FeeRate type.

  I also added documentation to the fee_absolute() method to clarify that the fee is determined by whichever method (fee_rate or fee_absolute) was called last, as the FeePolicy is an enum, and FeeRate/FeeAmount are mutually exclusive.

  ### Notes to the reviewers

  I thought it would be helpful to provide documentation to alleviate confusion over the fee_rate method and the fee_absolute method.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

  #### Bugfixes:

  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK e6519e3a52a1ab8023b5fdf423d8f748a3b0260d

Tree-SHA512: 59f62d1d1f8355e6353c6a2550e464732975c86c767648adc9143f2b3a9b894a90536a30a33e9de7efbe53f16392ec2e19008d884fb65ef037edae64a3cb6970
2023-09-19 15:05:15 +02:00
Jon Marrs
e6519e3a52
Enhance the documentation for the fee_rate and fee_absolute methods.
Signed-off-by: Jon Marrs <jdmarrs@gmail.com>
2023-09-18 14:16:00 -07:00
Daniela Brozzoni
43fb0b20df
Merge bitcoindevkit/bdk#1086: docs: fix spelling errors
94f8fa530b34ae1c099db3df070000121e8283cf docs: fix spelling errors (Steve Myers)

Pull request description:

  ### Description

  I did a global spell check and found and fixed a few spelling errors.

  ### Notes to the reviewers

  This is low priority but want to make sure it's done before we do a beta release.

  ### Changelog notice

  None.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  realeinherjar:
    ACK 94f8fa5
  evanlinjin:
    ACK 94f8fa530b34ae1c099db3df070000121e8283cf

Tree-SHA512: eed0be31264c45d8ef4d6b77e30927591014a76d71696f324440989e77b488d6bf018002d6df2354575b25e5a50d49bca6592976a310e6de7009e44d6b35518d
2023-09-18 10:13:29 +02:00
Steve Myers
94f8fa530b
docs: fix spelling errors 2023-09-16 10:43:26 -05:00
志宇
c20a4da9fc
Merge bitcoindevkit/bdk#1084: Enhance bdk chain structures
1ff806c67f4da9ba58b7c7689fde0fe41a34a6f5 fix(chain)!: rm weird `From` impl (志宇)
d43ae0231fa4670b98780cad84466c14ae087292 refactor: improve docs, cleanup unnecessary types and improve code (Vladimir Fomene)
41042069809e3eeb4a8cc8a5a8db1af2c57c4a11 feat: impl Append for lots of tuples (LLFourn)
c56728ff1315e0deaf256af07fd1ff5e18fced8a refactor: Remove `scan` and `scan_txout` from SpkTxoutIndex and KeychainTxoutIndex (Vladimir Fomene)
32c40ac939bc514ac7f1d3f1d7cd1080011e20ba feat(electrum)!: change signature of `ElectrumExt` (志宇)
a28748c33976312b9e6671636ab7e305323efb03 refactor: Implement Default for WalletUpdate (Vladimir Fomene)
f42f8b8ff19c2e67888b476487e4e5c9edb0d0ff refactor: Allow for no chain update (Vladimir Fomene)
68572bfd2e32efdeefaa46618e8e248d3a87f143 refactor: move WalletChangeset to wallet module (Vladimir Fomene)
2392e50fd9793902d480556caa4ec225085c82d6 refactor: Move WalletUpdate to wallet module (Vladimir Fomene)
7c12dc994242bf2d7e35c2723f6e7000de97a388 refactor: Remove ForEachTxout trait (Vladimir Fomene)
6bcbb93233824ec391689191b8ca1f5459cec930 refactor: Edit ElectrumExt not to use WalletUpdate (Vladimir Fomene)

Pull request description:

  ### Description

  Fixes #1061

  ### Changelog notice

  - Move WalletUpdate to the wallet module
  - Remove ForEachTxout trait completely
  - Refactor ElectrumExt to not use WalletUpdate.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 1ff806c67f4da9ba58b7c7689fde0fe41a34a6f5

Tree-SHA512: 05349713af9d2efa14a522ceaabb7513bb437d786adf2f93055765589a67e4eb68bda36ff415aeba07816c4d30988d4d55bac018e7697019270a219105ed65a2
2023-09-15 09:24:53 +08:00
志宇
1ff806c67f
fix(chain)!: rm weird From impl
And signature of `example_cli::KeychainChangeSet` is changed.
2023-09-14 20:16:00 +08:00
Vladimir Fomene
d43ae0231f
refactor: improve docs, cleanup unnecessary types and improve code 2023-09-13 13:57:58 +03:00
Daniela Brozzoni
59fc1b341b
Merge bitcoindevkit/bdk#1070: Rename methods of esplora ext
20900218ceba728c8051a3c017a6341d74cbaee3 refactor: rename methods in EsploraExt and EsploraExtAsync (Vladimir Fomene)

Pull request description:

  ### Description

  This PR fixes #1058. Built on top of #1040

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

ACKs for top commit:
  realeinherjar:
    ACK 2090021
  danielabrozzoni:
    ACK 20900218ceba728c8051a3c017a6341d74cbaee3 - code looks good, `example_esplora` and `wallet_esplora_blocking` work just fine.

Tree-SHA512: 5b5285aaa67a0c4e8174e480cceec7d934ec04a74d81740e1c82f6b8673c3e3d9c676dc43257a170320089efe2d3cb0d33123b4a395fc3e7fec63f85bdf70c79
2023-09-12 16:35:46 +02:00
Vladimir Fomene
20900218ce
refactor: rename methods in EsploraExt and EsploraExtAsync 2023-09-12 16:38:49 +03:00
Vladimir Fomene
e89cf5a16a
refactor: use set_lookahead in set_lookahead_for_all 2023-09-06 11:56:44 +03:00
LLFourn
4104206980
feat: impl Append for lots of tuples 2023-09-05 07:53:50 +08:00
Vladimir Fomene
c56728ff13
refactor: Remove scan and scan_txout from SpkTxoutIndex and KeychainTxoutIndex 2023-09-03 01:51:21 +08:00
志宇
32c40ac939
feat(electrum)!: change signature of ElectrumExt
We remove `ElectrumUpdate` and return tuples instead for `ElectrumExt`
methods. We introduce the `IncompleteTxGraph` structure to specifically
hodl the incomplete `TxGraph`.

This change is motivated by @LLFourn's comment: 794bf37e63 (r1305432603)
2023-09-03 01:51:20 +08:00
Vladimir Fomene
a28748c339
refactor: Implement Default for WalletUpdate 2023-09-03 01:51:20 +08:00
Vladimir Fomene
f42f8b8ff1
refactor: Allow for no chain update 2023-09-03 01:51:20 +08:00
Vladimir Fomene
68572bfd2e
refactor: move WalletChangeset to wallet module
Consequently, remove the `WalletChangeset` dependency from
`example_electrum` and `example_esplora` examples.
2023-09-03 01:48:01 +08:00
Vladimir Fomene
2392e50fd9
refactor: Move WalletUpdate to wallet module 2023-09-03 00:54:23 +08:00
Vladimir Fomene
7c12dc9942
refactor: Remove ForEachTxout trait 2023-09-03 00:54:23 +08:00
Vladimir Fomene
6bcbb93233
refactor: Edit ElectrumExt not to use WalletUpdate 2023-09-03 00:54:23 +08:00
志宇
2867e88b64
Merge bitcoindevkit/bdk#1093: fix: spks_of_all_keychains() shouldn't return an infinite iterator for non-wildcard descriptors
e48b911c8d23cceab2071cc92085fe6675d55ca9 refactor: Make test errors more readable (Daniela Brozzoni)
a7a1d9b2fb9fda4d86fe17cf90d9c0d46c4d8609 fix: non-wildcard descriptors should return an.. ..spk only if index is equal to 0 (Daniela Brozzoni)
cc1a43c495639f0dbe6da52501cb48f17b8cbbd2 fix: SpkIterator::new_with_range takes wildcards.. ..into account (Daniela Brozzoni)

Pull request description:

  ### Description

  When you pass a non-wildcard descriptor in `new_with_range`, we make
  sure that the range length is at most 1; if that's not the case, we
  shorten it.
  We would previously use `new_with_range` without this check and with a
  non-wildcard descriptor in `spks_of_all_keychains`, this meant creating
  a spkiterator that would go on producing the same spks over and over
  again, causing some issues with syncing on electrum/esplora.

  To reproduce the bug, run in `example-crates/example_electrum`:
  ```
  cargo run "sh(wsh(or_d(c:pk_k(cPGudvRLDSgeV4hH9NUofLvYxYBSRjju3cpiXmBg9K8G9k1ikCMp),c:pk_k(cSBSBHRrzqSXFmrBhLkZMzQB9q4P9MnAq92v8d9a5UveBc9sLX32))))#zp9pcfs9" scan
  ```

  ### Changelog notice

  - Fixed a bug where `KeychainTxOutIndex::spks_of_all_keychains`/`KeychainTxOutIndex::spks_of_keychain` would return an iterator yielding infinite spks even for non-wildcard descriptors.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK e48b911c8d23cceab2071cc92085fe6675d55ca9

Tree-SHA512: 87627505049eadcec979a05888ec0d8a25c4743c03696a7db68348d457c2bf006d9b3b69c99e208f7812fc5b0234dd5a98b4a923c2486615c7678c3ab523f8cf
2023-09-01 15:48:10 +08:00
Daniela Brozzoni
e48b911c8d
refactor: Make test errors more readable 2023-09-01 09:13:33 +02:00
Daniela Brozzoni
a7a1d9b2fb
fix: non-wildcard descriptors should return an..
..spk only if index is equal to 0
2023-09-01 09:12:44 +02:00
Steve Myers
8321aaa5c7
Merge bitcoindevkit/bdk#1040: Add cli esplora example
f41cc1cb374d6bae553dd997ebb325ced21025f0 fix: s/index_tx_graph/indexed_tx_graph/g (LLFourn)
da8cfd39e9733f6da12b0fe10b8ccf5e5894e090 feat: add cli example for `esplora` (志宇)

Pull request description:

  ### Description

  This PR builds on top of #1034 and adds a cli-example for our `esplora` chain-src crate.

  ### Notes to the reviewers

  Don't merge this until #1034 is merged. The only relevant commit is 5ff0412d8edba933760c79a40be29c8365719096.

  ### Changelog notice

  * Add cli-example for `esplora`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  ~* [ ] I've added tests for the new feature~
  * [x] I've added docs for the new feature

ACKs for top commit:
  danielabrozzoni:
    ACK f41cc1cb374d6bae553dd997ebb325ced21025f0
  notmandatory:
    ACK f41cc1cb374d6bae553dd997ebb325ced21025f0

Tree-SHA512: a41fa456a9509f75feea0af013deaaad846cc6b60e5e6671672630a716e8c962361cbc9bb2d62c68e96d5fdb9e580912c19ff5fcab1acaf604b5b4a10eb40cee
2023-08-31 15:27:06 -05:00
Daniela Brozzoni
cc1a43c495
fix: SpkIterator::new_with_range takes wildcards..
..into account

When you pass a non-wildcard descriptor in `new_with_range`, we make
sure that the range length is at most 1; if that's not the case, we
shorten it.
We would previously use `new_with_range` without this check and with a
non-wildcard descriptor in `spks_of_all_keychains`, this meant creating
a spkiterator that would go on producing the same spks over and over
again, causing some issues with syncing on electrum/esplora.

To reproduce the bug, run in `example-crates/example_electrum`:
```
cargo run "sh(wsh(or_d(c:pk_k(cPGudvRLDSgeV4hH9NUofLvYxYBSRjju3cpiXmBg9K8G9k1ikCMp),c:pk_k(cSBSBHRrzqSXFmrBhLkZMzQB9q4P9MnAq92v8d9a5UveBc9sLX32))))#zp9pcfs9" scan
```
2023-08-31 16:48:20 +02:00
LLFourn
f41cc1cb37
fix: s/index_tx_graph/indexed_tx_graph/g 2023-08-31 13:07:19 +02:00
志宇
da8cfd39e9
feat: add cli example for esplora
Co-authored-by: remix <remix7531@pm.me>
Co-authored-by: LLFourn <lloyd.fourn@gmail.com>
Co-authored-by: Daniela Brozzoni <danielabrozzoni@protonmail.com>
2023-08-31 13:07:18 +02:00
志宇
93e8eaf7ee
Merge bitcoindevkit/bdk#1048: Remove TransactionDetails from Wallet API
5fb5061645ae92d37091a215e48e84423fea48a3 ci: fix msrv dependency versions for rustls (Steve Myers)
dd5b8d759954f39baa4523fa10b4a64efe48a25b test(wallet): add check_fee!(wallet,psbt) macro and use it in place of psbt.fee_amount() (Steve Myers)
465d53cc88b32bf8098dc61e9afdbb28d22b213d docs(wallet): update docs for calculate_fee/fee_rate and add_foreign_utxo (Steve Myers)
036299803f9f94c7c8218a75f3c206fa8c4297ab feat(wallet): add Wallet::insert_txout function and updated docs for fee functions (Steve Myers)
d443fe7f6613776a3dce00def0b655c4b2b36728 feat(tx_graph)!: change TxGraph::calculate_fee to return Result<u64,CalculateFeeError> (Steve Myers)
b4c31cd5bad4fea18044aab2cffd657b16ec185b feat(wallet)!: remove TransactionDetails from bdk::Wallet API (Steve Myers)

Pull request description:

  ### Description

  Removed `TransactionDetails` and changed `Wallet::get_tx` to return a `CanonicalTx`, and `TxBuilder::finish` to return only a `PartiallySignedTransaction`. This should fix #922 and fix #1015.

  I also added `Wallet` functions to get a `Transaction` send and receive amounts, fee, and `FeeRate`.

  see: https://github.com/bitcoindevkit/bdk/issues/922#issuecomment-1652814975

  ### Notes to the reviewers

  Alot of wallet tests had to change since `TxBuilder::finish` only returns a PSBT now.

  I added a new `CalculateFeeError` which follows changes coming in #1028.

  ### Changelog notice

  Added
  - Wallet::sent_and_received function
  - Wallet::calculate_fee and Wallet::calculate_fee_rate functions
  - Wallet::error::CalculateFeeError
  - Wallet::insert_txout function to allow inserting foreign TxOuts

  BREAKING CHANGES:

  Removed
  - TransactionDetails struct

  Changed
  - Wallet::get_tx now returns CanonicalTx instead of TransactionDetails
  - TxBuilder::finish now returns only a PartiallySignedTransaction

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  evanlinjin:
    ACK 5fb5061645ae92d37091a215e48e84423fea48a3

Tree-SHA512: 1a0be1c229b8871e5ee23ba6874ff40370170477a0a8bb104c0197e7fd97765d84854285f863dd1b38a34c3b71815e75e4db5b25288c81caea99a14ddaa78254
2023-08-31 13:29:13 +08:00
Steve Myers
5fb5061645
ci: fix msrv dependency versions for rustls 2023-08-30 13:31:35 -05:00
Steve Myers
dd5b8d7599
test(wallet): add check_fee!(wallet,psbt) macro and use it in place of psbt.fee_amount()
- removed test_calculate_fee_with_inserted_foreign_utxo() since it now duplicates test in test_add_foreign_utxo()
2023-08-30 13:31:33 -05:00
Steve Myers
465d53cc88
docs(wallet): update docs for calculate_fee/fee_rate and add_foreign_utxo 2023-08-30 13:31:24 -05:00
Steve Myers
036299803f
feat(wallet): add Wallet::insert_txout function and updated docs for fee functions
added
    - Wallet::insert_txout function to allow inserting foreign TxOuts
    - test to verify error when trying to calculate fee with missing foreign utxo
    - test to calculate fee with inserted foreign utxo

updated
    - docs for Wallet::calculate_fee, Wallet::calculate_fee_rate, and TxGraph::calculate_fee
      with note about missing foreign utxos
2023-08-30 11:55:18 -05:00
Steve Myers
d443fe7f66
feat(tx_graph)!: change TxGraph::calculate_fee to return Result<u64,CalculateFeeError>
added
- tx_graph::CalculateFeeError enum

BREAKING CHANGES:

changed
- TxGraph::calculate_fee function to return Result<u64,CalculateFeeError> instead of Option<i64>
2023-08-30 11:55:17 -05:00
Steve Myers
b4c31cd5ba
feat(wallet)!: remove TransactionDetails from bdk::Wallet API
Added
- Wallet::sent_and_received function
- Wallet::calculate_fee and Wallet::calculate_fee_rate functions
- Wallet::error::CalculateFeeError

BREAKING CHANGES:

Removed
- TransactionDetails struct

Changed
- Wallet::get_tx now returns CanonicalTx instead of TransactionDetails
- TxBuilder::finish now returns only a PartiallySignedTransaction
2023-08-30 11:55:15 -05:00
志宇
e5fb1ec7ff
Merge bitcoindevkit/bdk#1069: Implement Anchor for BlockId
18e8da393779617e8a501d7e21b0a9db1a8b11f1 docs: Add doctest for Anchor implementation on BlockId (Vladimir Fomene)
480c2730de524cbb19a72d8cc8c41cb73ab556df feat: Implement Anchor for BlockId (Vladimir Fomene)

Pull request description:

  ### Description

  This PR fixes #1062.
  It implements the `Anchor` trait on `BlockId`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  evanlinjin:
    ACK 18e8da393779617e8a501d7e21b0a9db1a8b11f1

Tree-SHA512: af9da8b4e9c7f2a110340efa4e4c86d9b96ea1275f0a66f08e26a47fcacd89e318a32c845e2a4302f3332eeb4c6a976c3771b1d9881adf4feda90d6ba1a2dd9d
2023-08-28 23:51:27 +08:00
Vladimir Fomene
18e8da3937
docs: Add doctest for Anchor implementation on BlockId 2023-08-28 17:12:03 +03:00
Daniela Brozzoni
8f978f86b8
Merge bitcoindevkit/bdk#1089: fix: Correct the coin type in the derivation path for wallet examples
21206fe773a6ebb9f12c534ccb0bfbd694684b58 fix: Correct the coin type in the derivation path for the three wallet examples (Casey Bowman)

Pull request description:

  Corrects the derivation path for the three wallet examples. For testnet, the coin type should be 1 instead of 0.

  Replaces #1076

ACKs for top commit:
  danielabrozzoni:
    ACK 21206fe773a6ebb9f12c534ccb0bfbd694684b58

Tree-SHA512: c323d90f16f338a1a678e28aa681b28848d8c5f02fd769dbf165d3a13df7804abed14760cf0dbe2be6194b107b25980b54be4703f36a7db63f6484c244dd3728
2023-08-25 14:43:54 +02:00
Casey Bowman
21206fe773
fix: Correct the coin type in the derivation path for the three wallet examples
fix: Correct the coin type in the derivation path for the three wallet examples
2023-08-25 02:24:14 -05:00
志宇
381c560c10
Merge bitcoindevkit/bdk#1092: Use apply_update instead of determine_changeset + apply_changeset around the code
c753584379185b0bd19d130ca39e44c8a6a65e65 refactor(chain): use `apply_update` instead of `determine_changeset` + `apply_changeset` (Wei Chen)

Pull request description:

  This PR implements #1081

ACKs for top commit:
  evanlinjin:
    ACK c753584379185b0bd19d130ca39e44c8a6a65e65

Tree-SHA512: cfb66a427dd76b8d11e07be24de9ba06958cda114b8eec260d492d30fba5a1cecbee2bb3e83b8636f9049eb8e920ad13aa76651a97a01290f53b0c7da8849b41
2023-08-25 15:21:41 +08:00
Wei Chen
c753584379
refactor(chain): use apply_update instead of determine_changeset + apply_changeset 2023-08-25 15:14:56 +08:00
志宇
6125062a5b
Merge bitcoindevkit/bdk#1085: docs: Update README.md
2263a58448f5f04a74e076132aea93f21c584bc0 refactor: Rename `wallet_esplora` to... ...`wallet_esplora_blocking` (Daniela Brozzoni)
11ac26f6b28b6694dfc04e9fc72c208e454632c7 docs: Update README.md (Daniela Brozzoni)

Pull request description:

  ### Description

  - Fixes the release timeline
  - Adds an explanation for the crates under `example-crates`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 2263a58448f5f04a74e076132aea93f21c584bc0
  evanlinjin:
    ACK 2263a58448f5f04a74e076132aea93f21c584bc0

Tree-SHA512: fd0eecb4a1051b8f88ae858ad6231b254beaad50f925d656a307c66bd6a20770cf698032d1d7e0179d93ac169cfa5d8c7c3b8def4c91334afc27f7a6f9d7558a
2023-08-24 20:27:03 +08:00
Daniela Brozzoni
2263a58448
refactor: Rename wallet_esplora to...
...`wallet_esplora_blocking`
2023-08-23 16:02:44 +02:00
Daniela Brozzoni
11ac26f6b2
docs: Update README.md
- Fixes the release timeline
- Adds an explanation for the crates under `example-crates`
2023-08-23 16:02:41 +02:00
Steve Myers
fb5cfa3c25
Merge bitcoindevkit/bdk#1091: ci: Pin rustls-webpki to 0.100.1
fa0bead02488d2bcfb9828e61c06a36a3dab70d4 ci: Pin rustls-webpki to 0.100.1 (Daniela Brozzoni)

Pull request description:

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK fa0bead02488d2bcfb9828e61c06a36a3dab70d4

Tree-SHA512: e8d0f21efef5abd222169bce2294e7de22699bd65e8366cd3e9c08e0858efd9163b4c428375b2a335c0358a0e7c591bd64899ee5c909cd09e0d14bfdda3d3633
2023-08-22 11:53:16 -05:00
Daniela Brozzoni
fa0bead024
ci: Pin rustls-webpki to 0.100.1 2023-08-22 17:35:32 +02:00
Daniela Brozzoni
8c4eeb56c0
Merge bitcoindevkit/bdk#1082: docs: add License and Contributing sections to repo top-level README
2d543475e2d7aa5503199699bb9bb4c0e519d0a8 docs: add License and Contributing sections to repo top-level README (Steve Myers)

Pull request description:

  ### Description

  Add explicit "License" and "Contributing" sections to the repo top-level `README.md` file to make it clear that it applies to everything in the project. Also moved license files up to repo top-level directory and did some minor cleanup of bdk/README.md License and Contribution sections to match top-level README.

ACKs for top commit:
  danielabrozzoni:
    ACK 2d543475e2d7aa5503199699bb9bb4c0e519d0a8

Tree-SHA512: 00442adf22258333d7672e8389b2380a8a81219f217bbffd525e253424a2aeeed13dd2316b3fe69d0bbeb13addbf2351697659c2abfec762e8e789fce3bb26e2
2023-08-22 15:20:03 +02:00
Daniela Brozzoni
3b5b829086
Merge bitcoindevkit/bdk#1087: ci: fix msrv dependency versions for reqest and h2
4f37b2a293df57cdc7c4bae7d4ae8e0f04dd8032 ci: fix msrv dependency versions for reqest and h2 (Steve Myers)

Pull request description:

  ### Description

  Fix MSRV dependency versions for `reqwest` and`h2`, both latest version now require 1.63.0.

  ### Notes to the reviewers

  - reqwest 0.11.19 has MSRV 1.63.0+, pin to 0.11.18
  - h2 0.3.21 has MSRV 1.63.0+, pin to 0.3.20

  ### Changelog notice

  None.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK 4f37b2a293df57cdc7c4bae7d4ae8e0f04dd8032

Tree-SHA512: 6cc5bdc793d57f8b28d10f70041c1faae686da95182e313c3c854d9d58f003a75a381f2e5ca660c9eb41356937197e9f84bc756695e06b3718e281d3e818af51
2023-08-22 11:48:00 +02:00
Steve Myers
4f37b2a293
ci: fix msrv dependency versions for reqest and h2
- reqwest 0.11.19 has MSRV 1.63.0+, pin to 0.11.18
- h2 0.3.21 has MSRV 1.63.0+, pin to 0.3.20
2023-08-21 15:25:57 -05:00
Steve Myers
2d543475e2
docs: add License and Contributing sections to repo top-level README
- moved license files up to repo top-level directory
- minor cleanup of bdk/README.md License and Contribution sections
2023-08-19 13:36:10 -05:00
志宇
d6bcd9b725
Merge bitcoindevkit/bdk#1065: refactor!(chain): Unify ChangeSet nomenclature
62f253103c3fd158ad66a0bba11399e7083226f2 ci: Update tokio version (Daniela Brozzoni)
80f5ecf3be2550808f1bf1870df2504c09395dee feat(chain): Add `initial_changeset` to graphs (Daniela Brozzoni)
ea50b6a932ca492f27ac4aaea93c6b6ba11fa0e8 refactor!(chain): Unify ChangeSet nomenclature (Daniela Brozzoni)

Pull request description:

  Solves #1022

  ### Changelog notice

  Rename `indexed_tx_graph::IndexedAdditions` to `indexed_tx_graph::ChangeSet`
  Rename `indexed_tx_graph::IndexedAdditions::graph_additions` to `indexed_tx_graph::ChangeSet::graph`
  Rename `indexed_tx_graph::IndexedAdditions::index_additions` to `indexed_tx_graph::ChangeSet::indexer`
  Rename `tx_graph::Additions` to `tx_graph::ChangeSet`
  Rename `keychain::DerivationAdditions` to `keychain::ChangeSet`
  Rename `CanonicalTx::node` to `CanonicalTx::tx_node`
  Rename `CanonicalTx::observed_as` to `CanonicalTx::chain_position`
  Rename `LocalChangeSet` to `WalletChangeSet`
  Rename `LocalChangeSet::chain_changeset` to `WalletChangeSet::chain`
  Rename `LocalChangeSet::indexed_additions` to `WalletChangeSet::indexed_tx_graph`
  Rename `LocalUpdate` to `WalletUpdate`
  Make `TxGraph::determine_changeset` `pub(crate)`
  Add `TxGraph::initial_changeset`
  Add `IndexedTxGraph::initial_changeset`
  Remove `TxGraph::insert_txout_preview`
  Remove `TxGraph::insert_tx_preview`
  Remove `insert_anchor_preview`
  Remove `insert_seen_at_preview`

  ### Notes to reviewers

  I'm not sure whether we want to keep `TxGraph::determine_changeset` public or not

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 62f253103c3fd158ad66a0bba11399e7083226f2

Tree-SHA512: 401bdf49c5f2082971cfcd54725ce98abd08263de7571205a324a2adbb5359be4f48454def415bedadde0a9c81db437b91c13cd6e892ba54b215059f75006dd5
2023-08-18 18:59:15 +08:00
Daniela Brozzoni
62f253103c
ci: Update tokio version 2023-08-18 12:07:11 +02: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
Vladimir Fomene
480c2730de
feat: Implement Anchor for BlockId 2023-08-16 18:55:26 +03:00
Daniela Brozzoni
0cd2348166
Merge bitcoindevkit/bdk#1077: fix: msrv issues
b0b91b74186575f11a4fba77ffd64005c482740e fix: msrv issues and update coverage toolchain (Vladimir Fomene)

Pull request description:

  Fix breaking MSRV for 1.57.0

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK b0b91b74186575f11a4fba77ffd64005c482740e

Tree-SHA512: d872f427da065c66346f0fd3ae19d4d62c535cf4444d236c0d1f6e9a5e169b7fd7773f643693daa23eeccbe6a3ddad6767f91520c7547360c07febc227a88f06
2023-08-16 15:49:20 +02:00
Vladimir Fomene
b0b91b7418
fix: msrv issues and update coverage toolchain 2023-08-16 16:22:28 +03:00
志宇
feafaaca31
Merge bitcoindevkit/bdk#1023: Update rust bitcoin
1da3b304bb0aa29e3bb013e0a583c34ec390b32d ci: Pin rustls to keep the MSRV (Daniela Brozzoni)
792b39fa92bfa1218a33bd6ded257fc105aec67c Explicitly deny multipath keys (Daniela Brozzoni)
b73385dbd2e4c46d0553fa6990e564743b705507 Update wallet_electrum to rust-bitcoin 0.30.0 (Daniela Brozzoni)
3dac3f9bba790e8c40a157aa6c9dc3fdf026255e Update example_electrum to rust-bitcoin 0.30.0 (Daniela Brozzoni)
2949bdc7b8ab40c44803fad8fccb2a8f420d1566 Update example_cli to rust-bitcoin 0.30.0 (Daniela Brozzoni)
468d2a0a3b349adb12564847d50a5e5b30c9df3e Update tmp_plan to rust-bitcoin 0.30.0 (Daniela Brozzoni)
b8ac16d03c070ead550d4b458ddad3159cea0001 Update coin_select to rust-bitcoin 0.30.0 (Daniela Brozzoni)
6c29e53ee8b20bfa73a693ef88a14a925492a19b Update wallet_esplora and wallet_esplora_async to... ...rust-bitcoin 0.30.0 (Daniela Brozzoni)
6eb079576f4387db41ec1b9fe729e1d9ab4f8c01 Update crates/esplora to rust-bitcoin 0.30.0 (Daniela Brozzoni)
91b0f0ba2913287449925c86761f363583e59190 Update crates/electrum to bitcoin 0.30.0 (Daniela Brozzoni)
f4e3ba3265fc61bf61ffb54486abfe005ce236d7 Update bdk to bitcoin 0.30.0 (Daniela Brozzoni)
853d3617514edebd0d7b6542a78b5874225a5473 Update bdk_chain to bitcoin 0.30.0 (Daniela Brozzoni)

Pull request description:

  ### Description

  Updates to rust-bitcoin 0.30.0 and miniscript 0.10.0

  Not covered in this PR:
  - https://github.com/bitcoindevkit/bdk/issues/1036. Although the latter is deprecated, I think it's better if I update it in a separate PR, as this one is pretty big already.
  - https://github.com/bitcoindevkit/bdk/issues/1037
  - https://github.com/bitcoindevkit/bdk/issues/1038

  Heads up, I'm explicitly denying multipath descriptors until we have better tests for them. See the commit message of 23fba7aee9b55bf59db73c296b9fb025a256502e

  ### Changelog notice

  - Update to `rust-bitcoin` 0.30.0 and `miniscript` 10.0.0

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK 1da3b304bb0aa29e3bb013e0a583c34ec390b32d

Tree-SHA512: ff1457ed711f9f8cdb446ea10aaf124632f539c02406da94317d8dc38013b321217d3bdcb2df4bd72b2ed92116b52e9c6b98ee91d4d508a579c67449a7caa549
2023-08-04 12:24:07 +08:00
Daniela Brozzoni
1da3b304bb
ci: Pin rustls to keep the MSRV 2023-08-03 10:59:16 +02:00
Daniela Brozzoni
792b39fa92
Explicitly deny multipath keys
Although there is *some* code to handle multipath keys inside bdk,
it's all untested, and from a few quick tests it
seems that it's pretty easy to find buggy edge cases.
Better to deny multipath descs for now, and revisit the
decision once we work on supporting multidescriptor wallets.
2023-08-03 10:59:15 +02:00
Daniela Brozzoni
b73385dbd2
Update wallet_electrum to rust-bitcoin 0.30.0 2023-08-03 10:59:12 +02:00
Daniela Brozzoni
3dac3f9bba
Update example_electrum to rust-bitcoin 0.30.0 2023-08-03 10:59:11 +02:00
Daniela Brozzoni
2949bdc7b8
Update example_cli to rust-bitcoin 0.30.0 2023-08-03 10:59:10 +02:00
Daniela Brozzoni
468d2a0a3b
Update tmp_plan to rust-bitcoin 0.30.0 2023-08-03 10:59:09 +02:00
Daniela Brozzoni
b8ac16d03c
Update coin_select to rust-bitcoin 0.30.0 2023-08-03 10:59:08 +02:00
Daniela Brozzoni
6c29e53ee8
Update wallet_esplora and wallet_esplora_async to...
...rust-bitcoin 0.30.0
2023-08-03 10:59:06 +02:00
Daniela Brozzoni
6eb079576f
Update crates/esplora to rust-bitcoin 0.30.0 2023-08-03 10:59:05 +02:00
Daniela Brozzoni
91b0f0ba29
Update crates/electrum to bitcoin 0.30.0 2023-08-03 10:59:04 +02:00
Daniela Brozzoni
f4e3ba3265
Update bdk to bitcoin 0.30.0 2023-08-03 10:59:02 +02:00
Daniela Brozzoni
853d361751
Update bdk_chain to bitcoin 0.30.0 2023-08-03 10:58:59 +02:00
志宇
d73669e8fa
Merge bitcoindevkit/bdk#1034: Implement linked-list LocalChain and update chain-src crates/examples
b206a985cffaa9b614841219371faa53ba23dfc3 fix: Even more refactoring to code and documentation (志宇)
bea8e5aff4f1e4d61db3970a6efaec86e686dbc3 fix: `TxGraph::missing_blocks` logic (志宇)
db15e03bdce78c6321f906f390b10b3d9e7501b2 fix: improve more docs and more refactoring (志宇)
95312d4d05618b4c464acc0fdff49fb17405ec88 fix: docs and some minor refactoring (志宇)
8bf7a997f70fdffd072fd37e12c385e731728c5a Refactor `debug_assertions` checks for `LocalChain` (志宇)
315e7e0b4b373d7175f21a48ff6480b6e919a2c6 fix: rm duplicate `bdk_tmp_plan` module (志宇)
af705da1a846214f104df8886201a23cfa4b6b74 Add exclusion of example cli `*.db` files in `.gitignore` (志宇)
eabeb6ccb169b32f7b7541c9dc6481693bdeeb8a Implement linked-list `LocalChain` and update chain-src crates/examples (志宇)

Pull request description:

  Fixes #997
  Replaces #1002

  ### Description

  This PR 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.
  * Exclude example-cli `*.db` files in `.gitignore`.
  * Rm duplicate `bdk_tmp_plan` module.

  ### Notes to the reviewers

  This is the smallest possible division of #1002 without resulting in PRs that do not compile. Since we have changed the API of `LocalChain`, we also need to change `esplora`, `electrum` crates and examples alongside `bdk::Wallet`.

  ### Changelog notice

  * Implement linked-list `LocalChain`. 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`.
  * Rewrote `esplora` chain-src crate to anchor txs to their confirmation blocks (using esplora API's tx-status `block_hash`).

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  LLFourn:
    ACK b206a985cffaa9b614841219371faa53ba23dfc3

Tree-SHA512: a513eecb4f1aae6a5c06a69854e4492961424312a75a42d74377d363b364e3d52415bc81b4aa3fbc3f369ded19bddd07ab895130ebba288e8a43e9d6186e9fcc
2023-08-03 16:05:20 +08:00
Steve Myers
933056706c
Merge bitcoindevkit/bdk#1039: docs: add required style for commit messages
e17f03e7555b7b6f5348b9854f3d4ef559e84d75 docs: add required style for commit messages (Steve Myers)

Pull request description:

  ### Description

  Update CONTRIBUTING.md to specify that new commits should use 'Conventional Commits 1.0' style messages. See https://www.conventionalcommits.org/en/v1.0.0/.  I also fixed our current MSRV in the doc and fixed a spelling error.

  ### Notes to the reviewers

  I'm open to suggestions if anyone has another well documented style for commit messages.

  ### Changelog notice

  None.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  thunderbiscuit:
    ACK e17f03e7555b7b6f5348b9854f3d4ef559e84d75. I've been using conventional commits for Padawan for over 2 years and think it's got good value, particularly on projects with bigger teams and number of contributors.
  danielabrozzoni:
    ACK e17f03e7555b7b6f5348b9854f3d4ef559e84d75 - I was hesitant at first, but I think this would make the commit messages cleaner (and in most cases even shorter). Going forward we should consider adding a CI check enforcing this.

Tree-SHA512: 5f4c42814e35e013ff7846110b2897a35720b8f4b8974f8c8004fc0f5161a10076cac62a7aa711c14295129999f93e238034972f28b77145c1917613f8856b03
2023-08-02 16:54:48 -05: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
志宇
bea8e5aff4
fix: TxGraph::missing_blocks logic
Added additional tests for unnecessary duplicate heights
2023-07-28 11:37:17 +08:00
志宇
db15e03bdc
fix: improve more docs and more refactoring
Thank you @vladimirfomene for these suggestions.

* Rename `LocalUpdate::keychain` to `LocalUpdate::last_active_indices`.
* Change docs for `CheckPoint` to be more descriptive.
* Fix incorrect logic in `update_local_chain` for `EsploraExt` and
  `EsploraAsyncExt`.
2023-07-28 11:37:17 +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
志宇
8bf7a997f7
Refactor debug_assertions checks for LocalChain 2023-07-28 11:30:16 +08:00
志宇
315e7e0b4b
fix: rm duplicate bdk_tmp_plan module 2023-07-28 11:30:16 +08:00
志宇
af705da1a8
Add exclusion of example cli *.db files in .gitignore 2023-07-28 11:30:16 +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
Daniela Brozzoni
8f38e96e45
Merge bitcoindevkit/bdk#1046: Avoid pinning dependencies, use --precise in ci
ffb7c795e15d2d879f2d857e7607729ca4a53155 ci: Avoid pinning dependencies, use --precise (Daniela Brozzoni)
56b8eea64330044fd7761cb2439d7dcca05106f2 ci: No need to add the llvm repository for wasm (Daniela Brozzoni)

Pull request description:

  Fixes #1035

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK ffb7c795e15d2d879f2d857e7607729ca4a53155

Tree-SHA512: a2e5e0ffea87dc86e27c2f2f3550e6e6429e66f5fd8e0196e85915de5b0f14f0e4ee9d56c87b38b101eb28d86a65868054c20421f32ecd475ca73d00471e2f8d
2023-07-25 17:06:08 +02:00
Daniela Brozzoni
ffb7c795e1
ci: Avoid pinning dependencies, use --precise
Fixes #1035
2023-07-25 13:34:23 +02:00
Daniela Brozzoni
56b8eea643
ci: No need to add the llvm repository for wasm
Adding it fails with "The repository'http://apt.llvm.org/focal
llvm-toolchain-focal Release' does not have a Release file.", and for
some reason it's not needed anymore.
2023-07-25 13:34:19 +02:00
Daniela Brozzoni
cb626e9fc8
Merge bitcoindevkit/bdk#1031: remove duplicate is_empty
f5074ee3aee319137db1ddfa1e99f7e111abcfd4 remove duplicate `is_empty` from DerivationAdditions (Vladimir Fomene)

Pull request description:

  Duplicate `is_empty` method

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK f5074ee3aee319137db1ddfa1e99f7e111abcfd4

Tree-SHA512: 1cb48d25c9e57dbe444646ebc33c838e3d58c2523d74b58a75f0d085f68d070ec6a644c46e0bccb8765af7167c8359f079a6222fc9d17ae28ce1e6dda820fc84
2023-07-24 11:21:41 +02:00
Steve Myers
e17f03e755
docs: add required style for commit messages
Update CONTRIBUTING.md to specify that new commits should use 'Conventional Commits 1.0'
style messages. See https://www.conventionalcommits.org/en/v1.0.0/.
2023-07-19 16:15:35 -05:00
Vladimir Fomene
f5074ee3ae
remove duplicate is_empty from DerivationAdditions 2023-07-14 17:52:08 +03:00
Steve Myers
f4d2a76661
Bump version to 1.0.0-alpha.1 2023-07-04 12:28:06 -05:00
Steve Myers
81c7613391
[ci] fix docsrs error for bdk crate 2023-07-04 09:02:39 -05:00
志宇
26ade11726
Fix cargo features
* `bdk_chain/std` should also enable `miniscript/std`
* use the version of `hashbrown` that `bitcoin` and `miniscript` is
  using
2023-06-26 11:02:06 +08:00
Steve Myers
5d1f922b3b
Merge bitcoindevkit/bdk#894: Better no-std support
7ab84be9c747fd73fc5d1bd0706e7027a66aadb5 Better no-std support (Steve Myers)

Pull request description:

  This replaces #893

  ### Description

  Carrying over relevant maintenance changes from release 0.27.2 to bdk `master`.

  - Use `default-features = false` for `miniscript` and `bitcoin`
  - Introduce `std`  features for `bdk`, `bdk_chain` and `bdk_esplora`

  ### Notes to the reviewers

  The `default-features = false`for `bitcoin` and `miniscript` is to let `bdk` be unbiased for things like no-std.

  ### Changelog notice

  - Set default-features = false for rust-bitcoin and rust-miniscript #894
  - Introduce `std`  features for `bdk`, `bdk_chain` and `bdk_esplora`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 7ab84be9c747fd73fc5d1bd0706e7027a66aadb5

Tree-SHA512: 217e0ebc04cd59898d4de1c4f8cc6c87de2561659e277cc6e0d969c8bc61142ca62c8bda86643d55676dce39da25891b516a901005a03a31404dae118a5fce76
2023-06-20 16:36:54 -05:00
Steve Myers
7ab84be9c7
Better no-std support
- Use `default-features = false` for `miniscript`,`bitcoin`,and `bdk_chain`
- Introduce `bdk_chain/std` feature
- Add GitHub workflow `check-no-std` (not yet completly working)
- Update GitHub workflow `check-wasm` to disable default `std` features
2023-06-20 15:53:48 -05:00
Steve Myers
b184e351e5
Merge bitcoindevkit/bdk#840: create taproot descriptor template
e30919ba3a7941e6f54e2f95e94533c05415d831 Create taproot descriptor template (Vladimir Fomene)

Pull request description:

  ### Description

  This PR solves #836. This PR adds a P2TR
  descriptor template and a BIP86 taproot
  descriptor template. With this, users
  can now create a taproot descriptor with templates.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK e30919ba3a7941e6f54e2f95e94533c05415d831

Tree-SHA512: ad171d29e1b22613a9fb5e6ed148d1d3002c76152df1b5aa94e24be134d08d7c90dda9560b7501a8df28e5a7076339745da627bbdde5ed6fa11eab3199c34a99
2023-06-19 15:44:01 -05:00
Daniela Brozzoni
352f5b29ab
Merge bitcoindevkit/bdk#1009: Pin log dependency to 0.4.18 to keep the MSRV to 1.57.0
fa54a2e3a5096b263388b9f729ba1cb42574072e Pin log dependency to 0.4.18 to keep the MSRV to 1.57.0 (Daniela Brozzoni)

Pull request description:

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK fa54a2e3a5096b263388b9f729ba1cb42574072e

Tree-SHA512: 5fc19dd8485fcfe88c2720ff183dac7bfb6cacefa7be0c23aa1e7b345d81d1e41ac0903d84c5606b00adf2314911ee9d25972bfd4f0764e70456c8d8ffb3ab33
2023-06-19 14:12:01 +02:00
Daniela Brozzoni
fa54a2e3a5
Pin log dependency to 0.4.18 to keep the MSRV to 1.57.0 2023-06-19 13:50:59 +02:00
Daniela Brozzoni
97d542cf1c
Merge bitcoindevkit/bdk#976: Reimplement Wallet, ElectrumExt and Esplora{Async}Ext with redesigned structures.
75f8b81d58a985669ce7302fe235ad68eddc0d47 Update documentation (志宇)
cff92111d500fbcdd70015c03bf57b386d473fba [wallet_redesign] Clean up and document address methods (志宇)
a7668a2f3e98b8950a139b7c88fbebff56f49a5f [wallet_redesign] Modified `insert_tx` to use lowest checkpoint (志宇)
ac80829caa4bc94de0acdd0459917d095358559c Rename fields of `tx_graph::Additions` (Shourya742)
1c3cbefa4df7a4f93bc95203534da8ea0186fc5a [chain_redesign] Remove old structures (志宇)
5860704b2dfab5d3883fc89960ce4a69b92b65ef Implement redesigned versions of `EsploraExt` and `EsploraAsyncExt` (志宇)
2952341e5245acef14623b482095526d55b64bd6 Update the `wallet_electrum` example (志宇)
78a7920ba378bb57f0b61d93faf29ec813889a75 `bdk_electrum` API improvements and simplifications (志宇)
92709d03ce8ed979cda127c2c30811bb1c8c5f58 Various tweaks to code arrangement and documentation (志宇)
50425e979bdbe81621fcd54463cdc7c7aeed90f0 Introduce `keychain::LocalChangeSet` (志宇)
a78967e51ba1fa94f00a0f7a580dfc009428a947 [example-cli] simplify new address logic (LLFourn)
6a1ac7f80a7f97cd3c6264fb54f2d1e3b1f95130 [examples_redesign] Implemented `example_electrum` (志宇)
f55974a64bd0f5f2ef9e95831c2fb5d4f92f8282 [examples_redesign] Introduce `example_cli` package (志宇)
2e3cee4bd0568073e42e5670476febddd85a7b36 [electrum_redesign] Introduce redesigned `ElectrumExt` (志宇)
7261669c097791ee2ff8c7da6754868732d02eb3 Add `last_seen` to the the `ConfirmationTime::Unconfirmed` variant (志宇)
aba88130d91b329d8637c450c84fd10af508bdac [wallet_redesign] Move the majority of `Update` to `bdk_chain` (志宇)
e69fccb15fb17ba6eb86e24efad4b9bd96e3bf72 [wallet_redesign] Update `Wallet` with redesigned structures (志宇)

Pull request description:

  ### Description

  Closes #938

  * Update `Wallet` to use redesigned structures.
  * Update `bdk_electrum::ElectrumExt` to produce updates for redesigned structures.
  * Update `bdk_esplora::EsploraExt` and `bdk_esplora::EsploraAsyncExt` to produce updates for redesigned structures.
  * Added `example-crates/example_cli` library for implementing examples with redesigned structures.
  * Added `example-crate/example_electrum` which is an electrum CLI wallet using the redesigned structures.
  * Updated `example-crate/{wallet_electrum|wallet_esplora|wallet_esplora_async}` examples to use redesigned structures.
  * Remove all old structures.

  ### Notes to the reviewers

  ~These changes bump our `all-features` MSRV to `1.60.0` because of the introduction of `bdk_esplora`. As long as the `bdk_chain` and `bdk_wallet` crates hit a MSRV of `1.48.0`, it will be fine (this work is done in #987).~ No longer needed due to #993

  ~I had to comment out the examples that use `Wallet` with our chain sources. Once we update the helper-packages for those chain sources, we can also update the examples.~

  Possible future improvements for `ElectrumExt`:

  * Remove requirement to retry obtaining ALL data after reorg is detected. Transactions can be anchored to a lower block (not block tip), and an `assume_final_depth` value can be used.

  * The logic to finalize an update with confirmation time can be improved during reorgs to not require returning an error.

  * Use the subscription model of electrum, as intended by the API.

  ### Changelog notice

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  LLFourn:
    ACK 75f8b81d58a985669ce7302fe235ad68eddc0d47
  danielabrozzoni:
    Partial ACK 75f8b81d58a985669ce7302fe235ad68eddc0d47 - the Wallet code looks good to me, I don't have a good enough understanding of the esplora/electrum code to confidently ACK it.

Tree-SHA512: d1d2b79e3c28fbe826044a8b5ef9b122c2dcfc0d371f24cc4aac7f286500b587c2dc3b06ca6461c8721adbc29f56ca41e7566eace560b0a9c541604e6a225c61
2023-06-19 13:38:39 +02:00
志宇
75f8b81d58
Update documentation
* Add `warn(missing_docs)` for `bdk_wallet` and `bdk_chain`.
* Add missing documentation.
* Remove `LocalChain::heights` method.
* Remove old TODOs.
2023-06-04 03:32:19 +08:00
志宇
cff92111d5
[wallet_redesign] Clean up and document address methods 2023-06-04 03:32:19 +08:00
志宇
a7668a2f3e
[wallet_redesign] Modified insert_tx to use lowest checkpoint
Also updated the documentation.
2023-06-04 03:32:19 +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
志宇
5860704b2d
Implement redesigned versions of EsploraExt and EsploraAsyncExt
All associated examples are also updated.
2023-06-04 03:32:18 +08:00
志宇
2952341e52
Update the wallet_electrum example 2023-06-04 03:32:18 +08:00
志宇
78a7920ba3
bdk_electrum API improvements and simplifications
* `ElectrumUpdate::missing_full_txs` now returns a `Vec<Txid>` so we
  don't keep a reference to the passed-in `graph`.

* `ElectrumUpdate::finalize*` methods now takes in `missing` txids
  instead of `full_txs`. `Client::batch_transaction_get` is called
within the methods.

Other changes:

* `wallet::ChangeSet` is now made public externally. This is required as
  a wallet db should implement `PersistBackend<wallet::ChangeSet>`.
2023-06-04 03:32:18 +08:00
志宇
92709d03ce
Various tweaks to code arrangement and documentation
As per reviews by @danielabrozzoni and @LLFourn
2023-06-04 03:32:18 +08:00
志宇
50425e979b
Introduce keychain::LocalChangeSet
This corresponds to `keychain::KeychainChangeSet` but for the redesigned
structures with `LocalChain`.

This structure is now used in `Wallet` as well as the examples.
2023-06-04 03:32:18 +08:00
LLFourn
a78967e51b
[example-cli] simplify new address logic 2023-06-04 03:32:18 +08:00
志宇
6a1ac7f80a
[examples_redesign] Implemented example_electrum
This is a version of `keychain_tracker_electrum` that uses the
redesigned structures instead.
2023-06-04 03:32:17 +08:00
志宇
f55974a64b
[examples_redesign] Introduce example_cli package
This is the equivalent of `keychain_tracker_example_cli` that works with
the redesigned structures.
2023-06-04 03:32:17 +08:00
志宇
2e3cee4bd0
[electrum_redesign] Introduce redesigned ElectrumExt
There are a number of improvements that can be done, but it is in a
decent state to be usable.

Possible improvements:

* Remove requirement to retry obtaining ALL data after reorg is
  detected. Transactions can be anchored to a lower block (not block
  tip), and an `assume_final_depth` value can be used.

* The logic to finalize an update with confirmation time can be improved
  during reorgs to not require returning an error.
2023-06-04 03:32:17 +08:00
志宇
7261669c09
Add last_seen to the the ConfirmationTime::Unconfirmed variant
This allows us to skip adding an extra input to `Wallet::insert_tx`.

Also remove redundant logic.
2023-06-04 03:32:17 +08:00
志宇
aba88130d9
[wallet_redesign] Move the majority of Update to bdk_chain
This is to make it easier for chain source crates to formulate updates.
2023-06-04 03:32:17 +08:00
志宇
e69fccb15f
[wallet_redesign] Update Wallet with redesigned structures 2023-06-04 03:32:14 +08:00
Daniela Brozzoni
8641847e6c
Merge bitcoindevkit/bdk#1001: Rename "keychanins" to keychains
22b8a4884245449fcf60877ca031e0e9e7495de9 Rename "keychanins" to keychains (Daniela Brozzoni)

Pull request description:

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 22b8a4884245449fcf60877ca031e0e9e7495de9

Tree-SHA512: 13ebbd597771a9d91c317fedc4dc506a275a641b764f24650cd13217cf8ac0d06c42a935a8c9e1e7f4761d2ade473c7f8381e90875e867b7a61381aa33cd8581
2023-06-02 00:45:03 +02:00
Daniela Brozzoni
22b8a48842
Rename "keychanins" to keychains 2023-06-01 19:29:02 +02:00
Daniela Brozzoni
9bc7fe855d
Merge bitcoindevkit/bdk#957: Documentation regarding absolute_fee and fee_rate updated
10b4b6c665d58321436413d1d9c0486e7d74c5ec Documentations regarding absolute_fee and fee_rate updated (TATHAGATA ROY)

Pull request description:

  ### Description
  This pr solves this issue #856
  Updated the documentation for absolute fee and fee rate in BDK docs

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

  #### Bugfixes:

  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK 10b4b6c665d58321436413d1d9c0486e7d74c5ec

Tree-SHA512: 5b5f360b742313443368dc0b75275c38888cb358545661f7d9c78f3290789c50ffa9830e18473055d8e3da544c7d9527b023a1acdb28eaf862b24c892b23e9c4
2023-05-28 15:05:12 +02:00
TATHAGATA ROY
10b4b6c665
Documentations regarding absolute_fee and fee_rate updated
Update tx_builder.rs
2023-05-25 22:00:46 +00:00
Daniela Brozzoni
796f433f6c
Merge bitcoindevkit/bdk#993: Unpin base64
ac3759254a939b01830ac6963b1d5160da01b733 Unpin base64 (Daniela Brozzoni)

Pull request description:

  base64 lowered the MSRV to 1.57.0 in version 0.21.2

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  evanlinjin:
    ACK ac3759254a939b01830ac6963b1d5160da01b733

Tree-SHA512: de66f4be7c7fd608f5a74e51c5666f4fe6b962c5a8345c08c7b1da2551f81b9adfb28c58f0991ac6c985fa5c31f3eb7d17f99edf136b04945cefa24b28eaee19
2023-05-25 17:24:44 +02:00
Daniela Brozzoni
ac3759254a
Unpin base64
base64 lowered the MSRV to 1.57.0 in version 0.21.2
2023-05-25 15:37:16 +02:00
Vladimir Fomene
e30919ba3a
Create taproot descriptor template
This PR solves #836. This PR adds a P2TR
descriptor template and a BIP86 taproot
descriptor template. With this, users
can now create a taproot descriptor with templates.
2023-05-25 13:42:53 +03:00
Daniela Brozzoni
1d55943fa1
Merge bitcoindevkit/bdk#990: Pin base64 to 0.21.0 to keep the MSRV to 1.57.0
df74b23f315007cc36d3a12904380f861326fb32 Pin base64 to 0.21.0 to keep the MSRV to 1.57.0 (Daniela Brozzoni)

Pull request description:

  Fixes #986

  ### Changelog notice

  - Pin base64 to 0.21.0

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK df74b23f315007cc36d3a12904380f861326fb32

Tree-SHA512: fb11db0771542b074b7605e4af9ec655c22106b1d3451e27103d2f81686270efb44d8687f8312b5b7ab724f03e8f24c349a9f4f3b6e0c89ed9550b121f526ce7
2023-05-24 17:49:59 +02:00
Daniela Brozzoni
df74b23f31
Pin base64 to 0.21.0 to keep the MSRV to 1.57.0 2023-05-24 16:12:34 +02:00
Daniela Brozzoni
725eee8c92
Merge bitcoindevkit/bdk#981: Fixed typos in CONTRIBUTING.md
c7a045fa54a8183899d90730249c06c3f538b027 Fixed typos in CONTRIBUTING.md (Jon Marrs)

Pull request description:

  ### Description

  Fixed typos in CONTRIBUTING.md

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

ACKs for top commit:
  thunderbiscuit:
    ACK c7a045fa54a8183899d90730249c06c3f538b027.

Tree-SHA512: de66f4be7c7fd608f5a74e51c5666f4fe6b962c5a8345c08c7b1da2551f81b9adfb28c58f0991ac6c985fa5c31f3eb7d17f99edf136b04945cefa24b28eaee19
2023-05-18 12:36:31 +02:00
Jon Marrs
c7a045fa54
Fixed typos in CONTRIBUTING.md 2023-05-16 21:39:18 -07:00
志宇
34d60870ac
Merge bitcoindevkit/bdk#975: Improve txout listing and balance APIs for redesigned structures
ed89de752cf20cb80deefda3ddf65a137b669288 Improve txout filter/listing method docs for `TxGraph` (志宇)
fb75aa94a9f47d53ce7246c14d739fc53dc38197 Clarify `TxGraph::try_filter_chain_unspents` logic (志宇)
96b10751325dc1bced09f9e864438216400e4ba3 Fix and improve `Persist::commit` method (志宇)
e01d17d59bd6177bf5e457232219669782b727b7 Improve `txout` listing and balance APIs for redesigned structures (志宇)

Pull request description:

  ### Description

  As noted in https://github.com/bitcoindevkit/bdk/issues/971#issuecomment-1542408941.

  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.

  #### Other Fixes

  The `Persist::commit` method is fixed in 96b10751325dc1bced09f9e864438216400e4ba3.

  Previously, regardless of whether writing to persistence backend is successful or not, the logic always cleared `self.staged`. This is changed to only clear `self.staged` after successful write.

  Additionally, the written changeset (if any) is returned, and `PersistBackend::write_changes` will not be called if `self.staged` is empty.

  ### Notes to the reviewers

  Yes, slightly more boilerplate to do the same things, but less code to maintain and a much more flexible API. Very worth it IMO.

  ### Changelog notice

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  LLFourn:
    ACK ed89de752cf20cb80deefda3ddf65a137b669288

Tree-SHA512: efae18c13ee74eff801febca61cb16bf4d8f3203ced96172b9ef555d8d2a749a382f87d024e8c92aacbab7eb4e50a8337de798e10524291ad80c6b35c4dc0161
2023-05-11 21:02:16 +08:00
志宇
ed89de752c
Improve txout filter/listing method docs for TxGraph
Rename the `S` trait bound to `OI` (outpoint index) to emphasize it's
not only for spk indexing.
2023-05-11 12:43:49 +08:00
志宇
fb75aa94a9
Clarify TxGraph::try_filter_chain_unspents logic 2023-05-11 11:59:57 +08:00
志宇
96b1075132
Fix and improve Persist::commit method
Previously, regardless of whether writing to persistence backend is
successful or not, the logic always cleared `self.staged`. This is
changed to only clear `self.staged` after successful write.

Additionally, the written changeset (if any) is returned, and
`PersistBackend::write_changes` will not be called if `self.staged` is
empty.
2023-05-11 11:49:33 +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
志宇
05d353c0ad
Merge bitcoindevkit/bdk#965: Implement persistence with the new structures
4963240599364c6520d0a6ecae97db77cc7b8ba8 Add more `impl`s for `Append` and docs for file store `magic` (志宇)
2aa08a5898545f670df9ed9c4804231f321d811a [persist_redesign] Introduce redesigned `persist` types (志宇)

Pull request description:

  ### Description

  This is part of #895 and #971

  * Introduce a more generic version of the `keychain::persist::*` structures that only needs a single generic for the changeset type.

  Additional changes:

  * The `Append` trait has a new method `is_empty`.
  * Introduce `Store` structure for `bdk_file_store` (which implements `PersistBackend`).

  ### Changelog notice

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

Top commit has no ACKs.

Tree-SHA512: 0211fbe7d7e27805d3ed3a80b42f184cdff1cebb32fd559aa9838e4a7f7c7e47b6c366b6ef68e299f876bafed549b8d1d8b8cc0366bf5b61db079504a565b9b4
2023-05-10 23:25:15 +08:00
志宇
4963240599
Add more impls for Append and docs for file store magic 2023-05-10 15:07:19 +08:00
志宇
2aa08a5898
[persist_redesign] Introduce redesigned persist types
This is a more generic version of `keychain::persist::*` structures.

Additional changes:

* The `Append` trait has a new method `is_empty`.
* Introduce `Store` structure for `bdk_file_store`.
2023-05-09 12:55:44 +08:00
志宇
e3c137043f
Merge pull request #963 from evanlinjin/chain_redesign_tweaks
Various tweaks to redesigned structures
2023-05-05 20:11:11 +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
志宇
4ae727a1fb
[chain_redesign] Relax generic constraints 2023-05-05 16:35:39 +08:00
志宇
085bf9413d
[chain_redesign] Add LocalChain::insert_block 2023-05-05 16:35:35 +08:00
志宇
e413d3e424
[chain_redesign] Change behavior of try_get_chain_position
`TxGraph::try_get_chain_position` used to always exclude unconfirmed
transactions with last_seen value of 0. However, what is the point of
including a transaction in the graph if it cannot be part of the chain
history? Additionally, maybe sometimes we don't wish to use the
last_seen field at all.

The new behavior will consider unconfirmed transactions with last_seen
of 0.
2023-05-03 11:43:16 +08:00
志宇
c61995ca97
Merge pull request #927 from LagginTimes/custom_spk_iterator
Custom spk iterator
2023-05-02 17:36:51 +08:00
Wei
10fe32e6f1
Implement SpkIterator
SpkIterator was created with its own nth() and next() implementations
and its own new() and new_with_range() constructors.

Co-authored-by: 志宇 <hello@evanlinjin.me>
2023-05-02 17:31:40 +08:00
Steve Myers
6bc5f33ded
Merge commit 'refs/pull/960/head' of github.com:bitcoindevkit/bdk
Reenable code coverage upload to Coveralls, only for /crates repos
2023-05-01 15:41:34 -05:00
志宇
702fe7ac5e
Merge pull request #959 from rajarshimaitra/test-graph-2
Cleanup IndexedTxGraph test.
2023-05-01 14:53:30 +08:00
Lloyd Fournier
ce5ae3eac4
Merge pull request #953 from benthecarman/kwu
Add sat_per_kwu to FeeRate
2023-05-01 13:22:44 +10:00
Steve Myers
c1cffe9333
Filter code coverage report results 2023-04-29 15:47:08 -05:00
Steve Myers
5be7c1c50d
Reenable code coverage upload to Coveralls, only for ./crates packages 2023-04-29 09:49:03 -05: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
Daniela Brozzoni
139e3d3802
Merge bitcoindevkit/bdk#926: Introduce redesigned bdk_chain structures
b799a5728b7e08a18059ffee7fe7ee6078354977 [bdk_chain_redesign] Add tests for `IndexedTxGraph` with `LocalChain` (rajarshimaitra)
8cd0328eec0b55f10dd085597a435b689b37444a [bdk_chain_redesign] Implement `OwnedIndexer` for indexers (rajarshimaitra)
911af34f509ad0b4c86c0be819d79b202679e3e5 [bdk_chain_redesign] Fix calculation bugs. (rajarshimaitra)
e536307e5c5532fc0cac0657a26609cfd26115bf [bdk_chain_redesign] Fix `tx_graph::Additions::append` logic (志宇)
f101dde09b6067c17b0b64ea3e3efd358a32a820 [bdk_chain_redesign] Fix `tx_graph::Additions::append` logic (志宇)
1b152647c557d2ff492cd241999c5320f7c4f6c5 [bdk_chain_redesign] Change `insert_relevant_txs` method (志宇)
ecc74ce4cd1ab0c51c2e9bcaa4f7d53390dd4d9b [bdk_chain_redesign] Docs for `is_mature` and `is_confirmed_and_spendable` (志宇)
ac336aa32f485cb253ac7ea5cae3b4bcc78cf507 [bdk_chain_redesign] Make `insert_relevant_txs` topologically-agnostic (志宇)
165b874dfedb2e05a7ea5d56e6f80577ada48d73 [bdk_chain_redesign] Add test for `insert_relevant_txs` (志宇)
f3e7b67bf1195eadf48a8f26f960b3f39d6134f7 [bdk_chain_redesign] Various tweaks and fixes (志宇)
03c128311a687249238fb109f804cde25ffddad2 [bdk_chain_redesign] Revert changes to `SparseChain` (志宇)
34a7bf5afe2d78db47b149f4958f0a0365b017d0 [bdk_chain_redesign] Rm unnecessary code and premature optimisation (志宇)
6c495707423cc7ce26c3027893dc812281b73053 [bdk_chain_redesign] Rm `HashSet` from `TxGraph::relevant_heights` (志宇)
1003fe2ee6167e110b0195e2431560b5b222e2f1 [bdk_chain_redesign] Test `LocalChain` (志宇)
7175a82c04b0a3f0c5716f4a37e122da70b8ceac [bdk_chain_redesign] Add tests for `TxGraph::relevant_heights` (志宇)
8e36a2e5f6d0fe2813dca9a13005e0b1be7e94c3 [bdk_chain_redesign] Remove incomplete logic (志宇)
81436fcd72a3c45bb10a098be28de0116322d22d [bdk_chain_redesign] Fix `Anchor` definition + docs (志宇)
001efdd1cb658f3a2929ffcf9047e6b07e9bd15c Include tests for new updates of TxGraph (rajarshimaitra)
10ab77c549e597d0d8157d94ae6fa3b4d39fd5dc [bdk_chain_redesign] MOVE `TxIndex` into `indexed_chain_graph.rs` (志宇)
7d92337b932fdcfec7008da8ed81f2b4b6e7a069 [bdk_chain_redesign] Remove `IndexedTxGraph::last_height` (志宇)
a7fbe0ac672cde6c308737fc98020f6693071a5f [bdk_chain_redesign] Documentation improvements (志宇)
ee1060f2ff168e6aaffa41882be2b319729f7de8 [bdk_chain_redesign] Simplify `LocalChain` (志宇)
611d2e3ea2ed9249ddf04e0f9089642160e5c901 [bdk_chain_redesign] Consistent `ChainOracle` (志宇)
bff80ec378fab29556099f9830bcb42911658710 [bdk_chain_redesign] Improve `BlockAnchor` docs (志宇)
24cd8c5cc7f3a6bd0db2bd45642f08a28ea5337a [bdk_chain_redesign] More tweaks and renamings (志宇)
ddd5e951f5ec77070034c7390a635d8d5bd7cb85 [bdk_chain_redesign] Modify signature of `TxIndex` (志宇)
da4cef044d4a3ad0f44ff1e33936c93c38c2f774 [bdk_chain_redesign] Introduce `Append` trait for additions (志宇)
89cfa4d78e059f9fe2544b690bbbf90e92b3efee [bdk_chain_redesign] Better names, comments and generic bounds (志宇)
6e59dce10b66212d7180cadabba887cc4d20fc32 [bdk_chain_redesign] `chain_oracle::Cache` (志宇)
a7eaebbb77f8794c5ff3717aaf0cf73dd5a77480 [bdk_chain_redesign] Add serde support for `IndexedAdditions` (志宇)
c09cd2afce4e649caa2797628edaffae08a60628 [bdk_chain_redesign] Added methods to `LocalChain` (志宇)
7810059ed0f23cae7dee61fe587a1c8f3f49480a [bdk_chain_redesign] `TxGraph` tweaks (志宇)
a63ffe97397cd14bc0a13ea5e96ceddf8b63a4f0 [bdk_chain_redesign] Simplify `TxIndex` (志宇)
a1172def7df478c61076b0d99d5d0f5f9cd99da6 [bdk_chain_redesign] Revert some API changes (志宇)
8c906170c96919cd8c65e306b8351fe01e139fd4 [bdk_chain_redesign] Make default anchor for `TxGraph` as `()` (志宇)
468701a1295c90761749e1bb46cc201cc7f95613 [bdk_chain_redesign] Initial work on `LocalChain`. (志宇)
34d0277e44fd054c8d463dfa756d8531ccda3ca9 [bdk_chain_redesign] Rm anchor type param for structs that don't use it (志宇)
3440a057110fbbcc653f2f8c7d58175472299bae [bdk_chain_redesign] Add docs (志宇)
236c50fa7bace29a0373dd16416ecebbb6dc1ae8 [bdk_chain_redesign] `IndexedTxGraph` keeps track of the last synced height (志宇)
e902c10295ba430bf0522b92ffab68cd60bd1666 [bdk_chain_redesign] Fix `apply_additions` logic for `IndexedTxGraph`. (志宇)
313965d8c84f5de43cafa58c7bd9250aea93b22c [bdk_chain_redesign] `mut_index` should be `index_mut` (志宇)
db7883d813e97229340c32a8fa82a9a13bac7361 [bdk_chain_redesign] Add balance methods to `IndexedTxGraph` (志宇)
d0a2aa83befce5dda26f8b3ae05449f6967df25a [bdk_chain_redesign] Add `apply_additions` to `IndexedTxGraph` (志宇)
6cbb18d409d84ea0c399d9b3ecb0cdb49cc0b32e [bdk_chain_redesign] MOVE: `IndexedTxGraph` into submodule (志宇)
784cd34e3db727659dbb26c428ed9096927286c1 [bdk_chain_redesign] List chain data methods can be try/non-try (志宇)
43b648fee02291858dfcab9b639c55a0bc3fad81 [bdk_chain_redesign] Add `..in_chain` methods (志宇)
61a8606fbcaec933f915c4f0600cd6f5e35636e8 [bdk_chain_redesign] Introduce `ChainOracle` and `TxIndex` traits (志宇)
5ae5fe30ebd53d72fe567509506ae0cda7a3a244 [bdk_chain_redesign] Introduce `BlockAnchor` trait (志宇)

Pull request description:

  ### Description

  This is part of #895

  The initial `bdk_chain` structures allowed updating to be done without blocking IO (alongside many other benefits). However, the requirement to have transactions "perfectly positioned" in our `SparseChain` increased complexity of the syncing API. Updates needed to be meticulously crafted to properly connect with the original `SparseChain`. Additionally, it forced us to keep a local copy of the "best chain" data (which may not always be needed depending on the chain source).

  The redesigned structures, as introduced by this PR, fixes these shortcomings.

  1. Instead of `SparseChain`, we introduce the ability to `Anchor` a transaction to multiple blocks that may or may not be in the same chain history. We expand `TxGraph` to records these anchors (while still maintaining the *monotone* nature of `TxGraph`). When updating our new `TxGraph`, we don't need to complicated *are-we-connected* checks that we need for `SparseChain`.
  2. The chain source, in combination with our new`TxGraph` is all that we need to determine the "chain position" of a transaction. The chain source only needs to implement a single trait `ChainOracle`. This typically does not need to be updated (as it is remote), although we can have a special `ChainOracle` implementation that is stored locally. This only needs block height and hash information, reducing the scope of *non-monotine* structures that need to be updated.

  **What is done:**

  * `TxGraph` includes anchors (ids of blocks that the tx is seen in) and last-seem unix timestamp (for determining which non-confirmed tx we should consider as part of "best chain" if there are conflicts). This structure continues to be fully "monotone"; we can introduce data in any manner and not risk resulting in an inconsistent state.
  * `LocalChain` includes the "checkpoint" logic of `SparseChain` but removes the `txid` data. `LocalChain` implements the `ChainOracle` trait. Any blockchain-source can also implement the `ChainOracle` trait.
  * `IndexedTxGraph` is introduced and contains two fields; an internal `TxGraph` struct and a `TxIndex` implementation. These two fields will be updated atomically and can replace the functionality of `keychain::Tracker`.

  **What is in-progress:**

  * ~@evanlinjin: The `TxIndex` trait should not have `is_{}_relevant` methods as we cannot guarantee this across all transaction indexes. We should introduce extension traits for these (https://github.com/bitcoindevkit/bdk/pull/926#discussion_r1159286393).~
  * ~@evanlinjin: `BlockAnchor` should be defined as "if this block is in chain, then this tx must be in chain". Therefore, the anchor does not provide us with the exact confirmation height of the tx. We need to introduce an extension trait `ExactConfirmationHeightAnchor` for certain operations (https://github.com/bitcoindevkit/bdk/pull/926#discussion_r1155480352).~

  **What will be done external to this PR:**

  * @rajarshimaitra: Persisting `indexed_tx_graph::Additions` (#937).
  * @notmandatory: Update examples to use redesigned structures.
  * Update `bdk::Wallet` to use the redesigned structures.

  ### Changelog notice

  * Initial implementation of the `bdk_chain` redesign (as mentioned in #895). Currently, only the `bdk_chain` core structures are implemented. Persistence and updates to the current examples and `bdk::Wallet` will be done in separate PRs.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  rajarshimaitra:
    ACK b799a5728b
  danielabrozzoni:
    Partial ACK b799a5728b7e08a18059ffee7fe7ee6078354977 - good job! I haven't looked at the tests or at the methods implementations in depth, but I have reviewed the architecture and it looks good. I have a few non-blocking questions.

Tree-SHA512: 8c386354cbd02f0701b5134991b65d206a54d19a2e78ab204e6ff1fa78a18f16299051bc0bf4ff4d2f5a0adab9b15658fa53cd0de2ca16969f4bf6a485225082
2023-04-28 18:49:36 +02:00
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
rajarshimaitra
8cd0328eec
[bdk_chain_redesign] Implement OwnedIndexer for indexers
`SpkTxOutIndex` and `KeychainTxOutIndex` now both implement
`OwnedIndexer`.
2023-04-28 19:09:52 +08:00
rajarshimaitra
911af34f50
[bdk_chain_redesign] Fix calculation bugs.
* `IndexedTxGraph::try_balance` should include "confirmed and spendable"
  into `confirmed` balance.
* `TxGraph::try_list_chain_unspents` filter logic should be reversed.
2023-04-28 19:07:12 +08:00
志宇
e536307e5c
[bdk_chain_redesign] Fix tx_graph::Additions::append logic
* `Additions` now implements `Append` and uses `Append` to implement
  `append()`.
* `append()` logic enforces that `last_seen` values should only
  increase.
* Test written for `append()` with `last_seen` behaviour.
2023-04-28 18:54:36 +08:00
benthecarman
217ea3321a
Add sat_per_kwu to FeeRate 2023-04-27 09:31:32 -05:00
志宇
f101dde09b
[bdk_chain_redesign] Fix tx_graph::Additions::append logic 2023-04-26 01:27:47 +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
志宇
ecc74ce4cd
[bdk_chain_redesign] Docs for is_mature and is_confirmed_and_spendable
Docs are updated to explain why `is_mature` and
`is_confirmed_and_spendable` may return false-negatives.
2023-04-22 23:39:49 +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
志宇
f3e7b67bf1
[bdk_chain_redesign] Various tweaks and fixes
The `ConfirmationHeight` trait has been removed in favour of a second
method on the `Anchor` trait: `confirmation_height_upper_bound()`.

Methods `try_balance_at()` and `balance_at()` of `IndexedTxGraph` have
been removed as they do not provide additional functionality.

`IndexedTxGraph::insert_relevant_txs` now uses two loops, the first loop
indexes all transactions first. This is done as some indexes require
ancestor transactions to be indexed first and we cannot guarantee that
the input transactions are in topological order.
2023-04-21 13:29:44 +08:00
志宇
03c128311a
[bdk_chain_redesign] Revert changes to SparseChain 2023-04-21 12:33:03 +08:00
志宇
34a7bf5afe
[bdk_chain_redesign] Rm unnecessary code and premature optimisation
* Remove `chain_oracle::CacheBackend` for now as it is not used.
* `SparseChain` does not need to implement `ChainOracle`.
* Remove filter predicate for `list..` methods of `TxGraph` and
  `IndexedTxGraph` as this is premature optimisation.
* `Append` can be implemented for all `BTreeMap`s and `BTreeSet`s,
  instead of only `local_chain::ChangeSet`.
2023-04-20 18:07:26 +08:00
志宇
6c49570742
[bdk_chain_redesign] Rm HashSet from TxGraph::relevant_heights
The `HashSet` was used for iterating without duplicate items. However,
since `anchors` is a `BTreeSet`, heights are in order. So a single
variable tracking last height will be sufficient.
2023-04-20 15:56:28 +08:00
志宇
1003fe2ee6
[bdk_chain_redesign] Test LocalChain
This is mostly copying over the relevant tests from `SparseChain`.
Changes are made to `local_chain::ChangeSet` to re-add the ability to
remove blocks.
2023-04-20 15:29:20 +08:00
志宇
7175a82c04
[bdk_chain_redesign] Add tests for TxGraph::relevant_heights 2023-04-19 16:14:52 +08:00
志宇
8e36a2e5f6
[bdk_chain_redesign] Remove incomplete logic
`ObservedAs::ConfirmedImplicit` is incomplete, remove for now.

`local_chain::ChangeSet` does not need to be a single-element tuple
struct.
2023-04-19 12:21:39 +08:00
志宇
81436fcd72
[bdk_chain_redesign] Fix Anchor definition + docs
Previously, I have misunderstood the definition of anchor. If a tx is
anchored in a block, it does not necessarily mean it is confirmed in
that block. The tx can be confirmed in an ancestor block of the anchor
block.

With this new definition, we need a new trait `ConfirmationHeight` that
has one method `confirmation_height`. This trait can be used to extend
`Anchor` for those implementations that can give us the exact
conirmation height of a tx (which is useful in most cases).

Another change is to add another variant to the `ObservedAs` enum;
`ObservedAs::ConfirmedImplicit(A)`. If a tx does not have an anchor, but
another tx that spends it has an anchor that in in the best chain, we
can assume that tx is also in the best chain. The logic of
`TxGraph::try_get_chain_position` is also changed to reflect this.

Some methods from `IndexedTxGraph` have been moved to `TxGraph` as they
do not require the `Indexer`. Some `TxGraph` methods have been renamed
for clarity and consistency.

Also more docs are added.
2023-04-18 00:02:14 +08:00
Steve Myers
5e026cfd03
Merge bitcoindevkit/bdk#932: Fix policy condition calculation
ebd6103e6597e0a66470541d2fcd25709ea77866 Fix policy condition calculation (Alekos Filini)

Pull request description:

  ### Description

  When constructing the `Condition` struct we recursively call `get_condition` on all the items in a threshold and short-circuit if there's an error somewhere (for example, because the policy-path hasn't been provided for a specific threshold).

  This can cause issues when the user doesn't care about a subtree, because we still try to call `get_condition` on all the items and fail if something is missing, even if the specific subtree isn't selected and won't be used later on.

  This commit changes the logic so that we first filter only the `selected` items, and then unwrap the error using the question mark. If errors happened somewhere else they will be ignored, as they should.

  ### Notes to the reviewers

  I think it makes sense to backport this to `0.27`: even though it's not a critical issue (and there's a workaround[^1] for the bug) it may be a while before the new `1.0` is released. I wouldn't do a release just for this, but I would just leave it there and maybe in a few weeks if there are other fixes to be backported to pre-1.0 they could all be released.

  ### Changelog notice

  - Fixed a bug in the policy condition calculation

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

  [^1]: The workaround is to simply set the items in the policy tree even if they won't be used. For example, if the item causing troubles is a `thresh(1, ...)` just set `[0]` in the policy path for that id.

ACKs for top commit:
  notmandatory:
    ACK ebd6103e6597e0a66470541d2fcd25709ea77866

Tree-SHA512: 1e0c6140e47ead3a518656cab660932b40f9e67425ce144f072267c30fd5cae5923ba943d9682af050c8f314756c522260abb68b104b9eeaae597319612984db
2023-04-14 22:47:04 -05:00
rajarshimaitra
001efdd1cb
Include tests for new updates of TxGraph 2023-04-12 13:21:20 +08:00
志宇
10ab77c549
[bdk_chain_redesign] MOVE TxIndex into indexed_chain_graph.rs
`tx_graph.rs` is rearranged as well.
2023-04-12 11:24:05 +08:00
志宇
7d92337b93
[bdk_chain_redesign] Remove IndexedTxGraph::last_height
It is better to have this external to this structure.
2023-04-10 16:51:16 +08:00
志宇
a7fbe0ac67
[bdk_chain_redesign] Documentation improvements 2023-04-10 16:23:10 +08:00
志宇
ee1060f2ff
[bdk_chain_redesign] Simplify LocalChain
Remove the requirement that evicted blocks should have in-best-chain
counterparts in the update.
2023-04-10 15:04:20 +08:00
志宇
611d2e3ea2
[bdk_chain_redesign] Consistent ChainOracle
The problem with the previous `ChainOracle` interface is that it had no
guarantee for consistency. For example, a block deemed to be part of the
"best chain" can be reorged out. So when `ChainOracle` is called
multiple times for an operation (such as getting the UTXO set), the
returned result may be inconsistent.

This PR changes `ChainOracle::is_block_in_chain` to take in another
input `static_block`, ensuring `block` is an ancestor of `static_block`.
Thus, if `static_block` is consistent across the operation, the result
will be consistent also.

`is_block_in_chain` now returns `Option<bool>`. The `None` case means
that the oracle implementation cannot determine whether block is an
ancestor of static block. `IndexedTxGraph::list_chain_txouts` handles
this case by checking child spends that are in chain, and if so, the
parent tx must be in chain too.
2023-04-10 13:03:51 +08:00
志宇
bff80ec378
[bdk_chain_redesign] Improve BlockAnchor docs 2023-04-07 09:23:00 +08:00
志宇
24cd8c5cc7
[bdk_chain_redesign] More tweaks and renamings 2023-04-05 19:13:42 +08:00
志宇
ddd5e951f5
[bdk_chain_redesign] Modify signature of TxIndex
This makes the API of `TxIndex` more consistent between scanning in data
and checking whether certain data is relevant.
2023-04-05 18:17:08 +08:00
志宇
da4cef044d
[bdk_chain_redesign] Introduce Append trait for additions
Before, we were using `core::ops::AddAsign` but it was not the most
appropriate.
2023-04-05 17:29:20 +08:00
志宇
89cfa4d78e
[bdk_chain_redesign] Better names, comments and generic bounds
* Instead of implementing `ChainPosition` for `ObservedIn<BlockId>` to
  use `FullTxOut` methods (`is_spendable_at` and `is_mature`), we create
  alternative versions of those methods that require bounds with `Anchor`.
  This removes all `ObservedIn<A>: ChainPosition` bounds for methods of
  `IndexedTxGraph`.

* Various improvements to comments and names.
2023-04-05 16:39:54 +08:00
志宇
6e59dce10b
[bdk_chain_redesign] chain_oracle::Cache
Introduce `chain_oracle::Cache` which is a cache for requests to the
chain oracle. `ChainOracle` has also been moved to the `chain_oracle`
module.

Introduce `get_tip_in_best_chain` method to the `ChainOracle` trait.
This allows for guaranteeing that chain state can be consistent across
operations with `IndexedTxGraph`.
2023-04-05 10:57:26 +08:00
Alekos Filini
ebd6103e65
Fix policy condition calculation
When constructing the `Condition` struct we recursively call
`get_condition` on all the items in a threshold and short-circuit if
there's an error somewhere (for example, because the policy-path hasn't
been provided for a specific threshold).

This can cause issues when the user doesn't care about a subtree, because
we still try to call `get_condition` on all the items and fail if
something is missing, even if the specific subtree isn't selected and
won't be used later on.

This commit changes the logic so that we first filter only the `selected`
items, and then unwrap the error using the question mark. If errors
happened somewhere else they will be ignored, as it should.
2023-04-01 12:57:49 +02:00
志宇
a7eaebbb77
[bdk_chain_redesign] Add serde support for IndexedAdditions 2023-03-31 22:55:57 +08:00
志宇
c09cd2afce
[bdk_chain_redesign] Added methods to LocalChain
Also made the `IndexedTxGraph::index` field public (`index()` and
`index_mut()` methods are no longer needed).
2023-03-31 22:42:47 +08:00
志宇
7810059ed0
[bdk_chain_redesign] TxGraph tweaks
* Rename `TxNode::last_seen` to `last_seen_unconfirmed` and improve docs
* Improve `try_get_chain_position` logic and tweak comments
2023-03-31 14:15:34 +08:00
志宇
a63ffe9739
[bdk_chain_redesign] Simplify TxIndex 2023-03-31 13:45:15 +08:00
志宇
a1172def7d
[bdk_chain_redesign] Revert some API changes
Methods of old structures that return transaction(s) no longer return
`TxNode`, but `Transaction` as done previously.

`TxInGraph` is renamed to `TxNode`, while the internal `TxNode` is
renamed to `TxNodeInternal`.
2023-03-31 11:55:11 +08:00
志宇
8c906170c9
[bdk_chain_redesign] Make default anchor for TxGraph as ()
This allows us to use the old API with minimal changes. `TxGraph`
methods have also been rearranged to allow for it.
2023-03-30 18:14:44 +08:00
志宇
468701a129
[bdk_chain_redesign] Initial work on LocalChain. 2023-03-30 13:07:13 +08:00
志宇
34d0277e44
[bdk_chain_redesign] Rm anchor type param for structs that don't use it 2023-03-28 14:58:59 +08:00
志宇
3440a05711
[bdk_chain_redesign] Add docs 2023-03-28 10:58:23 +08:00
志宇
236c50fa7b
[bdk_chain_redesign] IndexedTxGraph keeps track of the last synced height
This is important as a `ChainOracle` implementation is updated
separately to an `IndexedTxGraph`.
2023-03-27 22:42:39 +08:00
志宇
e902c10295
[bdk_chain_redesign] Fix apply_additions logic for IndexedTxGraph. 2023-03-27 21:51:11 +08:00
志宇
313965d8c8
[bdk_chain_redesign] mut_index should be index_mut 2023-03-27 20:56:42 +08:00
志宇
db7883d813
[bdk_chain_redesign] Add balance methods to IndexedTxGraph 2023-03-27 19:55:57 +08:00
志宇
d0a2aa83be
[bdk_chain_redesign] Add apply_additions to IndexedTxGraph
* Get mutable index from `IndexedChainGraph`.
* Also add `apply_additions` method to `TxIndex` trait.
2023-03-27 16:02:21 +08:00
志宇
6cbb18d409
[bdk_chain_redesign] MOVE: IndexedTxGraph into submodule 2023-03-27 14:21:10 +08:00
志宇
784cd34e3d
[bdk_chain_redesign] List chain data methods can be try/non-try
Methods that list chain data have try and non-try versions. Both of
these versions now return an `Iterator`.

* Try versions return `Iterator<Item = Result>`.
* Non-try versions require the `ChainOracle` implementation to be
  `ChainOracle<Error = Infallible>`.
2023-03-27 13:59:51 +08:00
志宇
43b648fee0
[bdk_chain_redesign] Add ..in_chain methods
Add methods to `TxGraph` and `IndexedTxGraph` that gets in-best-chain
data (such as transactions, txouts, unspent txouts).
2023-03-27 12:42:59 +08:00
志宇
61a8606fbc
[bdk_chain_redesign] Introduce ChainOracle and TxIndex traits
The chain oracle keeps track of the best chain, while the transaction
index indexes transaction data in relation to script pubkeys.

This commit also includes initial work on `IndexedTxGraph`.
2023-03-26 11:03:35 +08:00
志宇
5ae5fe30eb
[bdk_chain_redesign] Introduce BlockAnchor trait
* Introduce `GraphedTx` struct to access transaction data of graphed
  transactions.
* Ability to insert/access anchors and "seen at" values for graphed
  transactions.
* `Additions` now records changes to anchors and last_seen_at.
2023-03-24 12:11:41 +08:00
Steve Myers
5a090fac90
Add description to file_store cargo metadata 2023-03-20 12:48:25 -05:00
Steve Myers
f99eb32ac5
Remove keyword from file_store cargo metadata 2023-03-20 12:48:21 -05:00
Steve Myers
30c11904a7
Add bdk_chain README 2023-03-20 12:12:54 -05:00
Steve Myers
82f9caddab
Bump bdk version to 1.0.0-alpha.0
chain to 0.4.0
electrum to 0.2.0
esplora to 0.2.0
file_store to 0.1.0
2023-03-19 23:03:48 -05:00
Steve Myers
3b68a7bcc0
For examples and nursery remove workspace dependency versions 2023-03-19 23:03:45 -05:00
志宇
919e74aa8d
Merge pull request #890 from evanlinjin/simplify-reveal-to-target-logic
Simplify `reveal_to_target` logic
2023-03-18 10:28:57 +08:00
志宇
72b1e2a485
Simplify reveal_to_target logic
- Remove unnecessary check
- Better comments
- Better variable names
- Add test for scanning txouts with lookahead
2023-03-18 09:18:09 +08:00
志宇
2ae69ca10b
Merge pull request #889 from evanlinjin/add-async-syncing-esplora
Add docs for `EsploraAsyncExt` and make doctests runnable
2023-03-17 17:20:08 +08:00
志宇
877b658787
Add docs for EsploraAsyncExt and make doctests runnable 2023-03-16 13:08:42 +08:00
志宇
82f5d9c81e
Merge pull request #888 from rajarshimaitra/greamarly-fixes
Nit fixes on documentation
2023-03-15 16:07:05 +11:00
rajarshimaitra
24df03afd6
Add documentation fixes 2023-03-15 13:00:45 +08:00
Steve Myers
cd4945af3a
Merge bitcoindevkit/bdk#793: bdk v1.0.0-alpha.0
bc3e05c6c671e927d0f954dac602f89a452b3d86 Doc fixes (Daniela Brozzoni)
352f95f55830b0bd1455966a932abc60607d5745 [ci] misc fixes (Daniela Brozzoni)
2fcf9c4adb0d188dd93d5efbc79171197460f43c Make async esplora futures Send (LLFourn)
5dd4ce74cf762184c318e17d5c1d094e47179d69 More documentation improvements (志宇)
ae9b19d84c779ed23506f11352bf0d8c7b1f00b1 `bdk` README improvements (志宇)
def0c9ed397d1e0b94581fafae281f27c31f16ab Add `wallet_esplora_async` example and various fixes (志宇)
26ab2e2d6c1cd90ab1042c3f415ca26464a4c557 Implement EsploraExt for Async client (Vladimir Fomene)
ab9242d10ddaaafae3f6433966658af882d1f735 Replace current caching solution with Rust Cache (Vladimir Fomene)
0aaf420f6d4de3010d3c193d63a904c76c8391a5 examples: exit if balance < SEND_AMOUNT (Daniela Brozzoni)
47faa881fb5669702999d38300fed2e03c0021b1 Fix cargo clippy (Daniela Brozzoni)
9d26121dbc6e0209f4154594c9884600f1298cf3 Improve stdout output for wallet esplora/electrum examples (志宇)
eddd74887017b1aa2d08e079ad3669b455a5d40a Add `wallet_electrum` example (志宇)
0505cd72424a621825f8312af2e342b13a1fc65d Remove transaction-based type parameters and traits (志宇)
de9457fce67f5bdc7a128f68d2e14ec4d4f8947b Changed `inflate_update` logic to not depend on `Cow` (志宇)
69cf6d7924c4599e6a4fd4cd52c291e640324a8f Use os-specific temp dir for `wallet_esplora` example (志宇)
b3836cb30839e1f0b41cb595b4a33b2f47ce04ce Use hardcoded send amount for `wallet_esplora` example (志宇)
b0829322688229120044940160b505f434d7617f Add the wallet_esplora example (Daniela Brozzoni)
d267517dbd24b501415a8dcbb0f937504b093515 NewError implements StdError (fix typo) (Daniela Brozzoni)
0c7a0abb1941f7f03f28fd0ddfe18609d1316fb2 Disable code coverage (Daniela Brozzoni)
dfcbafd6b10746a967c63e7a835ba07ac990e828 Use action-rs/toolchain in CI (Daniela Brozzoni)
0ba41c57515566e3eae15d52fba1ff9422ec5fe8 Make bdk_esplora wasm compatible again (Daniela Brozzoni)
a38f63359d02f508dc987c8a985d34e393d831a8 Make bdk_file_store use bincode v1 (LLFourn)
38ef170ed1be43c60dd34aebd14997ab0082a3ca Make bdk and bdk_chain work under 1.57.0 (Steve Myers)
3a5d7278999d1be9a9edb5d161dfaeed80e255b9 Update workspace dependencies to be relative paths (Steve Myers)
96d932c8305bb6502529918ac6d94b0264458358 Add clippy.toml (Daniela Brozzoni)
5708bf0c8c33bd769baf8fe7d5bd34689511019b Fix docs (Daniela Brozzoni)
5acee8249621a90498e7b1b814b8c2fbbd45022b Update rust stable in CI (1.67.0) (Daniela Brozzoni)
8c9bcebc71c1d721e53c293359198c26122832aa Fix the "repository" field in Cargo.toml (Daniela Brozzoni)
c61b3604e167194516719da75c01653cef5dae6e Fix cargo clippy warnings (Daniela Brozzoni)
1805bd35c0530133e238bbf8d9a41d84e03e058d Fix clippy (Daniela Brozzoni)
3f5a78ae3b1e6c3f0a6acc98bb2445c895cfd743 Disable test-hardware-signer (Daniela Brozzoni)
303a1703c99e9cd02ded904e7e4409cedc21fe75 Rust fmt (Daniela Brozzoni)
b5559767db7e8f389415dfe135907063e21598b8 Rename the stub wallet examples (LLFourn)
2e82cd8c0406e2a0d2a7b40d77f7d0a169b9b9f8 Use tempfile for file_store tests (LLFourn)
c069b0fb4171aa11e980e8e070982d3046e07110 Move everything else over 🎉 (LLFourn)
949608ab1f0ae6ee4d3aad271a24f920068ccb3b Move bdk_electrum into the bdk repo 🎉 (Daniela Brozzoni)
03deafb5538e55462443cd8ead0114bf788a7765 Move bdk_file_store into the bdk repo 🎉 (Daniela Brozzoni)
37dfa77d9d732b8a48019b8457051659004ab6d9 Move bdk_chain into the bdk repo 🎉 (Daniela Brozzoni)
f2188f9dcd094e65fcb5649004ef19c7d4b7ec30 Make lib.rs's docs be the README.md (LLFourn)
1c970a9295044de47da5ef92208b901fb4d9ec44 Fix code coverage CI (Daniela Brozzoni)
94a084aafde5285f0a677a98aa60d4375a62c1d7 Fix doc links (LLFourn)
9edbdf54c9de841db01a741c09017ccca70b76bc [ci] Fix feature flags (LLFourn)
20e45b7af055733af6863a6a297b03a7dc13c8d7 Add back test-hardware-signer feature (LLFourn)
6d05598407aae448ed1ca55a9a446e7cfc029bee Remove test-readme-examples (LLFourn)
b60820a7b5b506421bd6eeed14aaeada750e5f1c Remove authors.workspace because older cargo don't like (LLFourn)
22bec6d363bb3349e26f56243bef9e72277a6790 Delete unused errors (LLFourn)
8a6de3aa2dc9bac479f059630d0788ec1e62301d Convert to workspace (LLFourn)
fdfc9b9ede74ff24df51a33106caf4b5af702a69 Delete unused things (LLFourn)
e1eb0253cf34053a4cb93e7be0ec2d74281eff47 Make doctests work (LLFourn)
3baf9721ec28384fc322909570394e76f8f2c991 Use bdk_chain Balance (LLFourn)
b310a7afdd80f416e35aaeffae1e17b4e1d8a24e Add Wallet::cancel_tx (LLFourn)
5985706c1a8c6358d840eb12ed678836b56ffb02 Add wallet persistence (LLFourn)
57538e53e4f834942ba25c72531a9bbf69982284 Move tests to /tests (LLFourn)
a40da9ba6c41d714d611da35f8868a496df2a767 Make bdk no_std (LLFourn)
aab2b12f7ad57be8dc2c26ff33c44769425cdac4 bdk_core integration initial commit 🔥 (LLFourn)
544c397a38f272f0ac2ffa1a3195fe6a07f2ddbd Modified build, clippy and test steps (志宇)

Pull request description:

  We prepare the BDK repo for a major restructuring 🔥. This PR maintains the existing wallet API as much as possible and adds very little.

  ## Things Done

  - database modules removed
  - blockchain gutted but new esplora syncing code added (this will be gone soon hopefully).
  - minimal API changes.
  - Many macros removed.
  - no longer applicable examples removed.
  - Much conditional compilation removed. Can compile with `--all-features` now.
  - All wallet tests passing
  - TestClient moved into its own repo
  - Example using `esplora`

  ## APIs changed

  - wallet no longer has a `sync` method. This is replaced with `apply_wallet_scan`.
  - address "caching" is gone. You can just change the derivation index with `ensure_derived_up_to` which sets your derivation to at least the argument. Unlike `ensure_addresses_cached` used to do this will alter what getting a new address gives you.
  - `AddressIndex::Reset` is gone. This thing didn't make much sense and is hard to do with the more sane internals we've established. Changing the derivation index changes what script pubkeys the wallet will search so this is dangerous. We plan to add method like `trim_unused` which lowers the derivation index to the highest unused index. Applications must handle giving out old addresses manually now (which I think is good).

  ## Unfinished work

  - [x] esplora example doesn't work for mempool transactions yet (seems like our esplora in testclient doesn't index mempool??).
  - [x] we need to figure out a way to retrieve and store transaction timestamps (we're currently just setting them to `u64::MAX`). In `bdk_core` we never got around to doing this but it needs to be done.
  - [x] A few insights we got from doing this PR should be applied to bdk_core first.
  - [x] doctests not working.

  ### Notes to the reviewers

  Try not to review the actual changes. This PR will be forced pushed a bit so it will be likely wasted.
  I think I did a faithful job of translating the tests. A bit of review here would be helpful.

  I *do* think it would be good to merge this PR soon into the v1 branch so we have something to work off once unfinished work is done.
  Checking out the branch and poke around and give feedback would be the most helpful thing.

  Run the (sort of) working example:

  ```
  cargo run --example esplora --features="bdk_test_client/bitcoind_22_0 bdk_test_client/esplora esplora"
  ```
  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [ ] I'm linking the issue being fixed by this PR (there's too many!)

ACKs for top commit:
  danielabrozzoni:
    ACK bc3e05c6c671e927d0f954dac602f89a452b3d86

Tree-SHA512: b5fbfd2263bb2a7cbf7b486530e639683775209bea944b266efd9c0447fb632295f7f5ddbd2e8d79796338415eaca26f1876617c2b66523485167b22e75e449e
2023-03-14 12:48:51 -05:00
Daniela Brozzoni
bc3e05c6c6
Doc fixes 2023-03-13 22:23:40 +01:00
Daniela Brozzoni
352f95f558
[ci] misc fixes
LLFourn is squashing these to get them all signed:

Remove useless clippy allow

ci: use clippy action

[ci] remove check for features=default
2023-03-13 14:32:13 +11:00
LLFourn
2fcf9c4adb
Make async esplora futures Send 2023-03-10 12:19:54 +11:00
志宇
5dd4ce74cf
More documentation improvements 2023-03-10 13:40:27 +13:00
志宇
ae9b19d84c
bdk README improvements 2023-03-10 10:29:12 +13:00
志宇
def0c9ed39
Add wallet_esplora_async example and various fixes
Fixes include:
* Allow `bdk_esplora` to use async with tls
* Reorganize `bdk_esplora` crate to have separate files for
  async vs blocking
* Use optional dependencies for `bdk_esplora` async
2023-03-09 11:07:45 +13:00
Vladimir Fomene
26ab2e2d6c
Implement EsploraExt for Async client
Creates a separate async EsploraAsyncExt trait for the
async client using async-trait crate. It has thesame
methods as the EsploraExt trait for the blocking client.
This trait is implemented on the AsyncClient of the
rust-esplora-client crate.
2023-03-09 09:25:54 +13:00
Vladimir Fomene
ab9242d10d
Replace current caching solution with Rust Cache 2023-03-08 15:42:45 +01:00
Daniela Brozzoni
0aaf420f6d
examples: exit if balance < SEND_AMOUNT 2023-03-08 15:41:49 +01:00
Daniela Brozzoni
47faa881fb
Fix cargo clippy 2023-03-08 15:20:20 +01:00
志宇
9d26121dbc
Improve stdout output for wallet esplora/electrum examples 2023-03-08 15:28:56 +13:00
志宇
eddd748870
Add wallet_electrum example 2023-03-08 12:01:01 +13:00
志宇
0505cd7242
Remove transaction-based type parameters and traits 2023-03-08 11:39:25 +13:00
志宇
de9457fce6
Changed inflate_update logic to not depend on Cow
As mentioned by @LLFourn:

1. We have a "sparse chain" from which there is a subset of txids M that are missing from graph.
2. There is also another subset C that are in the graph but their positions have changed.
3. We used the Cow to avoid copying/duplicating in memory transactions in subset C and M

Instead in inflate_update we could remove transactions in subset M and just clone data in subset C (which is usually tiny).
2023-03-08 01:53:09 +13:00
志宇
69cf6d7924
Use os-specific temp dir for wallet_esplora example 2023-03-07 10:59:13 +13:00
志宇
b3836cb308
Use hardcoded send amount for wallet_esplora example 2023-03-07 10:47:13 +13:00
Daniela Brozzoni
b082932268
Add the wallet_esplora example 2023-03-03 17:55:23 +01:00
Daniela Brozzoni
d267517dbd
NewError implements StdError (fix typo) 2023-03-03 17:55:23 +01:00
Daniela Brozzoni
0c7a0abb19
Disable code coverage
To be enabled again soon ™️
2023-03-03 17:55:22 +01:00
Daniela Brozzoni
dfcbafd6b1
Use action-rs/toolchain in CI 2023-03-03 17:44:11 +01:00
Daniela Brozzoni
0ba41c5751
Make bdk_esplora wasm compatible again
There's a huge todo!() for the AsyncClient
2023-03-03 17:44:10 +01:00
LLFourn
a38f63359d
Make bdk_file_store use bincode v1 2023-03-03 17:44:10 +01:00
Steve Myers
38ef170ed1
Make bdk and bdk_chain work under 1.57.0
- rewrite some parts of the code to deal with older borrow checker
- downgraded hashbrown
2023-03-03 17:44:09 +01:00
Steve Myers
3a5d727899
Update workspace dependencies to be relative paths 2023-03-03 17:44:08 +01:00
Daniela Brozzoni
96d932c830
Add clippy.toml
Explicitly sets the project MSRV so that clippy won't give warnings
for feature added after our MSRV
2023-03-03 17:44:07 +01:00
Daniela Brozzoni
5708bf0c8c
Fix docs 2023-03-03 17:44:06 +01:00
Daniela Brozzoni
5acee82496
Update rust stable in CI (1.67.0) 2023-03-03 17:44:05 +01:00
Daniela Brozzoni
8c9bcebc71
Fix the "repository" field in Cargo.toml 2023-03-03 17:44:04 +01:00
Daniela Brozzoni
c61b3604e1
Fix cargo clippy warnings
Disabled warnings for nursery/tmp_plan as it's going to be replaced
anyways
2023-03-03 17:44:03 +01:00
Daniela Brozzoni
1805bd35c0
Fix clippy 2023-03-03 17:44:02 +01:00
Daniela Brozzoni
3f5a78ae3b
Disable test-hardware-signer
I suspect the latest version of HWI just broke everything
2023-03-03 17:44:01 +01:00
Daniela Brozzoni
303a1703c9
Rust fmt 2023-03-02 12:27:52 +01:00
LLFourn
b5559767db
Rename the stub wallet examples 2023-03-02 10:56:38 +01:00
LLFourn
2e82cd8c04
Use tempfile for file_store tests 2023-03-02 10:56:37 +01:00
LLFourn
c069b0fb41
Move everything else over 🎉
This completes the move of things from https://github.com/LLFourn/bdk_core_staging
2023-03-02 10:56:36 +01:00
Daniela Brozzoni
949608ab1f
Move bdk_electrum into the bdk repo 🎉
Original repository: 250b4f1dcc/bdk_electrum

Co-authored-by: 志宇 <hello@evanlinjin.me>
Co-authored-by: LLFourn <lloyd.fourn@gmail.com>
2023-03-02 10:56:35 +01:00
Daniela Brozzoni
03deafb553
Move bdk_file_store into the bdk repo 🎉
Original repository: 250b4f1dcc/bdk_file_store

Co-authored-by: 志宇 <hello@evanlinjin.me>
Co-authored-by: LLFourn <lloyd.fourn@gmail.com>
Co-authored-by: Vladimir Fomene <vladimirfomene@gmail.com>
2023-03-02 10:56:34 +01:00
Daniela Brozzoni
37dfa77d9d
Move bdk_chain into the bdk repo 🎉
Original repository: 250b4f1dcc/bdk_chain

Co-authored-by: Steve Myers <steve@notmandatory.org>
Co-authored-by: 志宇 <hello@evanlinjin.me>
Co-authored-by: LLFourn <lloyd.fourn@gmail.com>
Co-authored-by: rajarshimaitra <rajarshi149@gmail.com>
Co-authored-by: LagginTimes <wzc110@gmail.com>
Co-authored-by: Steve Myers <steve@notmandatory.org>
Co-authored-by: Vladimir Fomene <vladimirfomene@gmail.com>
2023-03-02 10:56:33 +01:00
LLFourn
f2188f9dcd
Make lib.rs's docs be the README.md
Also flesh out README a bit
2023-03-02 10:56:32 +01:00
Daniela Brozzoni
1c970a9295
Fix code coverage CI
If you want to have tests on the hardware-signer you need to install
the python libraries and start the emulator
2023-03-02 10:56:31 +01:00
LLFourn
94a084aafd
Fix doc links 2023-03-02 10:56:30 +01:00
LLFourn
9edbdf54c9
[ci] Fix feature flags 2023-03-02 10:56:29 +01:00
LLFourn
20e45b7af0
Add back test-hardware-signer feature 2023-03-02 10:56:28 +01:00
LLFourn
6d05598407
Remove test-readme-examples
we shouldn't have a feature flag for this it should always be done.
2023-03-02 10:56:27 +01:00
LLFourn
b60820a7b5
Remove authors.workspace because older cargo don't like 2023-03-02 10:56:26 +01:00
LLFourn
22bec6d363
Delete unused errors 2023-03-02 10:56:25 +01:00
LLFourn
8a6de3aa2d
Convert to workspace 2023-03-02 10:56:22 +01:00
LLFourn
fdfc9b9ede
Delete unused things 2023-03-02 10:55:15 +01:00
LLFourn
e1eb0253cf
Make doctests work 2023-03-02 10:55:14 +01:00
LLFourn
3baf9721ec
Use bdk_chain Balance
instead of bdk's one
2023-03-02 10:55:13 +01:00
LLFourn
b310a7afdd
Add Wallet::cancel_tx
To allow you to re-use change addresses from transactions that get cancelled.
2023-03-02 10:55:12 +01:00
LLFourn
5985706c1a
Add wallet persistence 2023-03-02 10:55:11 +01:00
LLFourn
57538e53e4
Move tests to /tests
To stop my rust-anlayzer from killing me
2023-03-02 10:55:10 +01:00
LLFourn
a40da9ba6c
Make bdk no_std 2023-03-02 10:55:09 +01:00
LLFourn
aab2b12f7a
bdk_core integration initial commit 🔥
We prepare the BDK repo for a major restructuring.

- database modules removed
- blockchain module removed
- minimal API changes.
- Many macros removed.
- no longer applicable examples removed.
- Much conditional compilation removed. Can compile with --all-features.
- delete verify module
2023-03-02 10:55:07 +01:00
志宇
544c397a38
Modified build, clippy and test steps
Co-authored-by: Daniela Brozzoni <danielabrozzoni@protonmail.com>
2023-03-02 10:53:51 +01:00
Daniela Brozzoni
ced2d05e64
Merge bitcoindevkit/bdk#857: Check results in the DB tests
a1a70a50119fc4f02962cfffe29233e6d8fc116b Check results in the DB tests (Silvestrs Timofejevs)

Pull request description:

  ### Description

  Checksum test was giving a false positive due to ignoring the return value.

  Other tests were giving assertion fail later in the test, rather than an error on failed method call, thus making it more challenging to debug the issue.

  These have been discovered, when implementing PostgreSQL backend in a downstream fork.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing
  * [x] I ran all `sqlite` and `key-value-db` tests successfully

ACKs for top commit:
  danielabrozzoni:
    ACK a1a70a50119fc4f02962cfffe29233e6d8fc116b

Tree-SHA512: d3542cdd9f5f76f8318910261dbeb9cdcc9d4f26e9852e7aad7419c4abdf269d030b72bb21ee34a9dd314d2fa8433f1a6a9f1338a62699e5d8b6764c03067904
2023-02-24 11:22:59 +01:00
Steve Myers
843807b08f
Merge bitcoindevkit/bdk#869: Bump version to 0.27.1
231a1fba61c56c7d43c3a7d8d41af1f3b8aa4c3f Bump version to 0.27.1 (Steve Myers)

Pull request description:

  ### Description

  Bump dev version to 0.27.1.

  ### Notes to the reviewers

  This is in preparation for making a patch release and will be cherry picked to the release/0.27 branch. See #868.

  ### Changelog notice

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: 7c791d221d95fb800c19b85c110a47f462b1c9ea7991dc1cf9bc5bb17d12b2dea9d1823d7f928ba06f09aaac36b1140610a29454857257f918124e0e0893fc4e
2023-02-16 11:49:58 -06:00
Steve Myers
231a1fba61
Bump version to 0.27.1 2023-02-16 11:22:20 -06:00
Steve Myers
74119e70c3
Merge bitcoindevkit/bdk#867: Update rusqlite from 0.27.0 to 0.28.0
8b2943c49b6747fd32c65cb73114e631042f6d4a Update rusqlite from 0.27.0 to 0.28.0 (Steve Myers)

Pull request description:

  ### Description

  Fix #866 by updating `rusqlite` dependency version from `0.27.0` to `0.28.0` to fix [RUSTSEC-2022-0090](https://rustsec.org/advisories/RUSTSEC-2022-0090).

  ### Notes to the reviewers

  This will also need to be cherry-picked to the `release/0.27` branch to create a new `0.27.1` release.

  ### Changelog notice

  Changed

  * Update rusqlite version from 0.27.0 to 0.28.0 to fix [RUSTSEC-2022-0090](https://rustsec.org/advisories/RUSTSEC-2022-0090).

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  rajarshimaitra:
    tACK 8b2943c49b6747fd32c65cb73114e631042f6d4a

Tree-SHA512: 0633e0523805895efb0e4c21671e6018d440b93f0b8119e8d553a2fac1f089b36addb2bf82fdf370674887e1b3efc09dc4c461d85043c469aeb41077488384a5
2023-02-15 14:43:23 -06:00
Steve Myers
8b2943c49b
Update rusqlite from 0.27.0 to 0.28.0 2023-02-14 19:05:06 -06:00
Silvestrs Timofejevs
a1a70a5011
Check results in the DB tests
Checksum test was giving a false positive due to ignoring the return
value.

Other tests were giving assertion fail later in the test, rather than
an error on failed method call, thus making it more challenging to
debug the issue.

These have been discovered, when implementing PostgreSQL backend in
a downstream fork.
2023-02-14 07:17:52 +00:00
Daniela Brozzoni
2d173a17f7
Merge bitcoindevkit/bdk#863: Fix ci Dockerfile.ledger
5b9e0e392a246b7cafa3fa6836be7603b039bad7 Fix ci Dockerfile.ledger (Steve Myers)

Pull request description:

  ### Description

  Ledger emulator used to default to `-model nanos` but in latest release we need to add it to the command line. This change fixes `test_hardware_wallet` CI tests.

  ### Notes to the reviewers

  I originally made this fix in the `release/0.27` branch, this PR cherry-picks the change back to the `master` branch. I should have done a `master` branch PR first but it's only a CI change and I wanted to get the `0.27.0` release out.

  ### Changelog notice

  None.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    tACK 5b9e0e392a246b7cafa3fa6836be7603b039bad7

Tree-SHA512: 552586dc614d11c4084b73ad865078c9e28a1bdd3eda9addc8055df6408bba5f110f8aa7b3da730949f41cfd48f87b12cda0ba2df2b98e40e1590aa99b54a7ee
2023-02-13 23:23:00 +01:00
Steve Myers
5b9e0e392a
Fix ci Dockerfile.ledger 2023-02-13 11:38:26 -06:00
Steve Myers
c2a42493fd
Merge bitcoindevkit/bdk#852: Bump version to 0.27.0
0c2570ae07e7e90b66b2161121718ffac38dc3aa Pin dev-dependency zip to 0.6.3 (Steve Myers)
e83bb7c4dccd94d5876dc4361bd64c8405cf9f93 Bump version to 0.27.0 (Steve Myers)

Pull request description:

  ### Description

  Bump version to 0.27.0.

  ### Notes to the reviewers

  Updating changelog file again.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

ACKs for top commit:
  danielabrozzoni:
    ACK 0c2570ae07e7e90b66b2161121718ffac38dc3aa

Tree-SHA512: 334e0a6933be18152f266e3622b877ccf67dafadd3a641eaf9ffa4e671babafbedcdaef431e2195aa7e11945f164b8da44bd8a208c8e7287ce87684fb2459787
2023-02-03 16:01:31 -06:00
Steve Myers
0c2570ae07
Pin dev-dependency zip to 0.6.3 2023-02-03 12:13:20 -06:00
Steve Myers
e83bb7c4dc
Bump version to 0.27.0 2023-02-02 12:31:59 -06:00
Steve Myers
46273fe72f
Merge bitcoindevkit/bdk#847: Update electrsd to version 0.22
147a4ed141accc83aa2781b2468d3d950674f8e7 Update electrsd to version 0.22 (Steve Myers)

Pull request description:

  ### Description

  Update `electrsd` dev-dependency to version `0.22`.

  ### Notes to the reviewers

  We're able to do this now that esplora was updated in #830 and our MSRV was bumped to `1.57.0` in #842.

  ### Changelog

  None.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

ACKs for top commit:
  rajarshimaitra:
    ACK 147a4ed141accc83aa2781b2468d3d950674f8e7

Tree-SHA512: 20e0aebb02d786a4d426a2d2e66b78225a803eee2c2f6092b0cf8f18e6fe91e37ef7a74e109e3ad4d734af8de4dc71598f7e80f50d40187442dad323000c6090
2023-02-02 11:33:11 -06:00
Steve Myers
0b26fa75dc
Merge bitcoindevkit/bdk#844: Update rust-miniscript to 9.0
cf8cd2f2b4a975afbea18309a5dae0158acd8805 Update rust-miniscript to version 9.0, hwi to version 0.5 (Steve Myers)

Pull request description:

  ### Description

  A new [`rust-miniscript` release 9.0](https://github.com/rust-bitcoin/rust-miniscript/blob/master/CHANGELOG.md#900---november-5-2022) came out on Nov 14, updating to it to pickup the bug fixes. Also updating dependency`hwi` to new `0.5` version which used the `9.0` version of `rust-miniscript`.

  ### Notes to the reviewers

  This new version of `rust-miniscript` uses the same version of `rust-bitcoin` we are on, 0.29.1.

  ### Changelog notice

  Update rust-miniscript dependency to latest bug fix release 9.0.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  rajarshimaitra:
    ACK cf8cd2f2b4a975afbea18309a5dae0158acd8805

Tree-SHA512: 12473f67d2a4388e3d93b91988233e067328c344bb993981b014e1f7469db82f12d8f68eb1bf093feb25c4428d10451d8f361497c71c4f696d19939d4be9d858
2023-02-02 10:44:33 -06:00
Steve Myers
35bbe2beef
Merge bitcoindevkit/bdk#838: Add small clarification to docs
f0cec015b59ab484e81ca675d1170af5eb553911 Add small clarification to docs (thunderbiscuit)

Pull request description:

  ### Description
  Very small fixes to documentation:
  1. I got a DM last week from a user who thought we had a bug with our timestamps. It turns out he was using the milliseconds version of the Unix timestamp in his project and didn't realize we were giving out a standard Unix timestamp. The docs now mention this explicitly.
  2. I noticed some small inconsistencies in the documentation on the public templates while porting them over to Kotlin. This PR also fixes that so that all templates use a common documentation wording.

  ### Checklists
  #### All Submissions:
  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    Re-ACK f0cec015b59ab484e81ca675d1170af5eb553911

Tree-SHA512: ad42278126a0613fb1ba15f4e0ca92e05038389ac2e6b1015ea045f30ee8e92a40d6c089c35d0492bba0dc6d71e44b29879bd37a8bc491ff6367a89cab958db2
2023-02-01 20:06:44 -06:00
Steve Myers
9e7bad8afa
Merge bitcoindevkit/bdk#846: Update CHANGELOG and release process
4ada11f3581a172ec2d5980378267f578e998740 Update CHANGELOG and release process (Steve Myers)

Pull request description:

  ### Description

  Per discussion on discord with @danielabrozzoni this PR updates our release process to go back to updating our CHANGELOG.md file for each release.

  ### Notes to the reviewers

  This adds one more step the person making releases has to do but it isn't much.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

ACKs for top commit:
  danielabrozzoni:
    ACK 4ada11f3581a172ec2d5980378267f578e998740

Tree-SHA512: 80c116c90b4a5c5d4091678dd7714c9eee881c0f181dd220e878011001ad458db2bb81dea7dc13f2d768b9169c3644191d7969c533b784a5e26f5aa6c9e66fc2
2023-02-01 11:21:49 -06:00
Steve Myers
4ada11f358
Update CHANGELOG and release process 2023-01-31 14:08:14 -06:00
Steve Myers
cf8cd2f2b4
Update rust-miniscript to version 9.0, hwi to version 0.5 2023-01-31 13:54:52 -06:00
Steve Myers
147a4ed141
Update electrsd to version 0.22 2023-01-31 12:04:03 -06:00
Steve Myers
97f8fe3fd1
Merge bitcoindevkit/bdk#834: Document return type of sign method.
ff720780950e010cb13af7def1d2226841ca3f97 Document return type of `sign` method. (Thibaut Le Guilly)

Pull request description:

  Small thing but I had to look up the code to see what the returned boolean was about, thought it might be good to have in the docs.

  ### Description

  Documents the meaning of the returned value on the wallet `sign` method.

  I've just edited from github so skipped all the checks if that's not ok maybe someone else can update it properly.

ACKs for top commit:
  w0xlt:
    ACK ff72078095
  notmandatory:
    ACK ff720780950e010cb13af7def1d2226841ca3f97

Tree-SHA512: e0dd52a0af663b88d3fe0a20cb2909b9ba00bcf4f224b4f87cfd53fee0a199a01679dc5cd74aeb440326dfc52d45fa887534138d25df6fa1c8a38678be23204e
2023-01-31 11:50:38 -06:00
thunderbiscuit
f0cec015b5
Add small clarification to docs 2023-01-30 21:35:35 -05:00
Thibaut Le Guilly
ff72078095
Document return type of sign method.
Small thing but I had to look up the code to see what the returned boolean was about, thought it might be good to have in the docs.
2023-01-31 10:13:46 +09:00
Steve Myers
e678aad3c7
Merge bitcoindevkit/bdk#837: Derive PartialEq, Eq on SyncTime
45d41416ede5d2e26a8ef4c2cac6f44d0346fb23 Derive `PartialEq`, `Eq` on `SyncTime` (Max Fang)

Pull request description:

  ### Description

  This enables e.g. `assert_eq!` comparisons of `SyncTime` in tests (we use this)

  ### Changelog notice

  Derived `PartialEq`, `Eq` on `SyncTime`

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  rajarshimaitra:
    ACK 45d41416ede5d2e26a8ef4c2cac6f44d0346fb23
  evanlinjin:
    ACK 45d41416ede5d2e26a8ef4c2cac6f44d0346fb23

Tree-SHA512: eb2dc87762c33874a3a521c2f020250e83401c0f0e784911de6139bc8bf8c56f40c93ad2aa93cf20058ba796efd050979bddc5414acdd6856003e7a9f88c75c6
2023-01-30 13:11:59 -06:00
Steve Myers
41dc7f7d0d
Merge bitcoindevkit/bdk#831: Don't default to use async/await on wasm32
32912eaa05fd3bb4fa1577ca413dcedf909544d9 Don't default to use `async`/`await` on `wasm32` (Elias Rohrer)

Pull request description:

  ### Description

  We don't automatically want to make the interface `async` based on the used architecture, but now require the user to explicitly set the `async-interface` feature.

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 32912eaa05fd3bb4fa1577ca413dcedf909544d9

Tree-SHA512: 41a8f3ab29508a359a8c0d96994e4fa97e52c15e8b8003c1988bcfe036cafa81d6210d446ed825672ce52aff684ebb328dc61b8ae3d25cda6f51a3cae838de58
2023-01-30 13:10:06 -06:00
Steve Myers
6b92a169ab
Merge bitcoindevkit/bdk#814: Improve display error formatting
9019793bd4090d704b17876c57bf255a75507ed2 Improve display error formatting (Yuki Kishimoto)

Pull request description:

  ### Description

  Closes #555

  ### Checklists

  #### All Submissions:

  * [X] I've signed all my commits
  * [X] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [X] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [X] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 9019793bd4090d704b17876c57bf255a75507ed2

Tree-SHA512: 44f0c7e0374e255bf99cbbfb01f2af76746e52afe67ace1595d2830bd60be99f3c8726e6ad9744878978257796a79b3933e7ef21c30a5e4b99a16aaf9ac7ff64
2023-01-30 13:08:29 -06:00
Max Fang
45d41416ed
Derive PartialEq, Eq on SyncTime
This enables e.g. `assert_eq!` comparisons of `SyncTime` in tests.
2023-01-29 12:26:54 -08:00
Yuki Kishimoto
9019793bd4
Improve display error formatting 2023-01-27 18:21:56 +01:00
Elias Rohrer
32912eaa05
Don't default to use async/await on wasm32
We don't automatically want to make the interface `async` based on the
used architecture, but now require the user to explicitly set the
`async-interface` feature.
2023-01-27 11:09:26 -06:00
Steve Myers
2e7a220e39
Merge bitcoindevkit/bdk#842: Bump project MSRV to 1.57.0
b02bfb347d1faa0ce0a7ad6f67d0b92458510239 Bump project MSRV to 1.57.0, update stable for all jobs to 1.65.0 (Steve Myers)

Pull request description:

  ### Description

  Bump project MSRV from 1.56.1 to 1.57.0.

  Also bumped the `check-wasm` and `test_hardware_wallet` jobs rust STABLE version to 1.65.0 to match other jobs.

  ### Notes to the reviewers

  The `rustls` crate changed their MSRV to 1.57 on 2023-01-12 with a patch release from 0.20.7 to 0.20.8, rustls/rustls#1152. This breaks our CI builds that use `explora-client` 0.3 because it depends on a version of `ureq` that uses the latest `rustls`.

  ```
  rustls v0.20.8
  └── ureq v2.6.2
      └── esplora-client v0.3.0
          └── bdk v0.26.0 (/Users/steve/git/notmandatory/bdk)
      [build-dependencies]
      └── electrsd v0.21.1
          [dev-dependencies]
          └── bdk v0.26.0 (/Users/steve/git/notmandatory/bdk)
  ```

  https://github.com/rustls/rustls/blob/main/README.md

  ### Changelog notice

  Project MSRV changed from 1.56.1 to 1.57.0.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: 86b3ec2a7412a5ca1d1f620a3a16ccf315ce6afc363fdaa096187054de2edca09e4ce394df86174bfe45640b8226ed919bd4dc2d6e2149842355cb66e5c834be
2023-01-27 11:01:07 -06:00
Steve Myers
b02bfb347d
Bump project MSRV to 1.57.0, update stable for all jobs to 1.65.0 2023-01-27 10:33:43 -06:00
Steve Myers
0cce1ce982
Merge bitcoindevkit/bdk#815: Bump CI Rust stable version to 1.65.0
fb76c9ed9a0764a1e82d5c12a5e8104e26ef0ee5 ci: bump rust stable version to 1.65.0 (Yuki Kishimoto)
3a782b3b0da3ffbb2ec2480feb39c3b9e09149fe Fix Clippy Rust 1.65 (Yuki Kishimoto)

Pull request description:

  ### Description

  * Fix clippy for Rust 1.65.0
  * Bump CI Rust stable version to 1.65.0

  ### Checklists

  #### All Submissions:

  * [X] I've signed all my commits
  * [X] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [X] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  rajarshimaitra:
    ReACK fb76c9ed9a0764a1e82d5c12a5e8104e26ef0ee5

Tree-SHA512: 2f27915895cb203842831e525cc9efe0503269df07b7e58ab2a587e2991decf2990cb48abe8209c89cec5706a1d9c72387da532b70979ec100b5eed469051136
2023-01-24 12:08:51 -06:00
Yuki Kishimoto
fb76c9ed9a
ci: bump rust stable version to 1.65.0 2023-01-07 15:08:56 +01:00
Yuki Kishimoto
3a782b3b0d
Fix Clippy Rust 1.65 2023-01-07 15:08:37 +01:00
Steve Myers
eac739d395
Merge bitcoindevkit/bdk#830: Update esplora-client
6e5873ebba27d7dcef2695053a423bbe2d646a25 Update esplora-client (rajarshimaitra)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Update esplora-client and electrsd.

  Update: `electrsd v0.22` requires msrv at 1.57.. So removed from the PR for now..

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: 7c126822f7a45a6d3053c81d78e20340d64b159e7433ea333dc4bf5611316938718e16a65fcb37c59ec5e7e5d74d514bc312e49eeb49167a22b0eb2269203488
2023-01-02 20:23:14 -06:00
rajarshimaitra
6e5873ebba
Update esplora-client 2023-01-01 11:23:54 +05:30
Steve Myers
3205f0c16d
Bump version to 0.26.0 2022-12-26 13:55:48 -08:00
Steve Myers
5f0870a741
Merge bitcoindevkit/bdk#821: [#344] Add assert_matches
14bc9c0e356ac1c864e7c37aaadfe4696e999693 [#344] Add assert_matches Replace assert!(matches! with assert_matches! everywhere Convert assert! to assert_eq! in 2 places (Jeremy Mawson)

Pull request description:

  [#344] Add assert_matches

ACKs for top commit:
  notmandatory:
    ACK 14bc9c0e356ac1c864e7c37aaadfe4696e999693
  danielabrozzoni:
    utACK 14bc9c0e356ac1c864e7c37aaadfe4696e999693

Tree-SHA512: 730fed9c8c22b0725b1337140636def1a059ac78e4ae16f1abd4c7f379628d9329ccd3ed28e4cbab58e9ace5f349333cb5fa83ec43d507d7a7609601efebc9e1
2022-12-26 13:38:48 -08:00
Steve Myers
5a483472c1
Merge bitcoindevkit/bdk#825: Bump hwi to 0.4.0
4cad18bbcaa8199b82c10291aa38941f06823568 Bump hwi to 0.4.0 (Daniela Brozzoni)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice

  - Bump hwi to 0.4.0

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 4cad18bbcaa8199b82c10291aa38941f06823568

Tree-SHA512: 6c73c091da743734ed87e4792f3c2a838ac7aa252388309ad46e017cc7e9b338bfdb7ed70925c8041a7d22a4d12e2a984e902619b1b7735c645e6c1b6855aeb3
2022-12-26 13:37:05 -08:00
Steve Myers
8d4cc3920a
Merge bitcoindevkit/bdk#805: electrum: add validate_domain to ElectrumBlockchainConfig
2451c00268a8b518212c59132c263bc186d1b0f9 electrum: add validate_domain to ElectrumBlockchainConfig (Igor Cota)

Pull request description:

  ### Description

  The purpose of the PR is to be able to configure both `stop_gap` **and** `validate_domain`. Perhaps there are nicer ways.

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I'm linking the issue being fixed by this PR

  Issue in https://github.com/bitcoindevkit/bdk/issues/804

ACKs for top commit:
  notmandatory:
    ACK 2451c00268a8b518212c59132c263bc186d1b0f9

Tree-SHA512: e10e3a027c202c8e680e5181f2a98c9ca30fa7773660cc47bef93f557cdc94c09e46b154b0edee65e498a49bc997cc9172eb3782dc4310d5775c0763d8c2ca4a
2022-12-23 16:28:50 -08:00
Jeremy Mawson
14bc9c0e35
[#344] Add assert_matches
Replace assert!(matches! with assert_matches! everywhere
Convert assert! to assert_eq! in 2 places
2022-12-23 22:05:53 +10:00
Igor Cota
2451c00268
electrum: add validate_domain to ElectrumBlockchainConfig 2022-12-20 10:44:57 +01:00
Daniela Brozzoni
4cad18bbca
Bump hwi to 0.4.0 2022-12-19 11:18:44 +01:00
Daniela Brozzoni
634a0575cb
Merge bitcoindevkit/bdk#812: Implement ordering for TransactionDetails
d3d07564f28b68723630fcb03becdc9d5b8d72ae Implement ordering for TransactionDetails (benthecarman)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Pulled from https://github.com/BitcoinDevShop/mutiny-web-poc/pull/189

  Wallets should be able to sort the transactions easily, this makes it so you can just all `sort` on a list of tx details instead of needing to implement the sort_by yourself

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    utACK d3d07564f28b68723630fcb03becdc9d5b8d72ae

Tree-SHA512: d2b53dc959897b71d71794f3c919f86f8b7886e6ea5f6ac511cfaca0c19b2f78784a23491b3010380cf41da7ef69fd9ca1be75437c53eca1c60bd6651d1fec41
2022-12-19 09:43:26 +01:00
benthecarman
d3d07564f2
Implement ordering for TransactionDetails 2022-12-17 14:34:09 -06:00
Steve Myers
0b768d6f0b
Merge bitcoindevkit/bdk#818: Fix wrong key origin path in public descriptor templates
d6e730f18ad25706323a3f3bc8e8646c002d1e1c Fix wrong key origin path in public descriptor templates (Yuki Kishimoto)

Pull request description:

  ### Description

  Fixes #817

  ### Checklists

  #### All Submissions:

  * [X] I've signed all my commits
  * [X] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [X] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [X] I'm linking the issue being fixed by this PR

Top commit has no ACKs.

Tree-SHA512: df08007b27d44a889cf94fe3e2c608cb92f963737c937ca952288d0468636308b09124f04b5dbd793de81d6cb06cf076c89358356abfe8417775ab1ab5650698
2022-12-16 15:40:29 -06:00
Steve Myers
ec9aefac6b
Merge bitcoindevkit/bdk#808: fix: make save_tx order independent
d72aa7ebc071cb418ce53efa8da7447bac8161f7 chore: make TxCache.save_txs can order independent (bodymindarts)

Pull request description:

  fulcrum doesn't return txs in the order they are requested in. This PR makes the `TxCache` insensitive to this behaviour.

Top commit has no ACKs.

Tree-SHA512: fe17345ba26dd047ee18d23eb7341849a80ada71a72826dc653616014ca1371b07bddcdc4983e842d4cbfd951b192de21849a5f00662d40fdc8033f13ac2bb75
2022-12-16 15:37:45 -06:00
bodymindarts
d72aa7ebc0
chore: make TxCache.save_txs can order independent 2022-12-16 15:09:44 -06:00
Daniela Brozzoni
99930af12e
Merge bitcoindevkit/bdk#820: Make README.md code examples compile without errors
d1e5b87bfc1d37c5cd6631427ab521a59fa4e67a Make README.md code examples compile without errors (Peter Todd)

Pull request description:

ACKs for top commit:
  danielabrozzoni:
    ACK d1e5b87bfc1d37c5cd6631427ab521a59fa4e67a

Tree-SHA512: 343c62acfcfe9e2ea9af8a89d5a1653f9076c50a6fe2efcb23bc838d10d388395872080f2d98f21dd98fdd18a1b79457eb68dae3d73f02aa817f1b9045f19a25
2022-12-15 09:06:17 +01:00
Yuki Kishimoto
d6e730f18a
Fix wrong key origin path in public descriptor templates 2022-12-14 21:31:22 +01:00
Peter Todd
d1e5b87bfc
Make README.md code examples compile without errors 2022-12-14 15:26:18 -05:00
Daniela Brozzoni
c101dea460
Merge bitcoindevkit/bdk#822: Update ci nightly-docs workflow to use nightly-2022-12-14
9ddd5025382341a5e941630473563edc593645f4 Update ci nightly-docs workflow to use nightly-2022-12-14 (Steve Myers)

Pull request description:

  ### Description

  The current nightly version we were using for the nightly-docs workflow is failing so I updated it to tonight's (2022-12-14)
  version.

  ### Notes to the reviewers

  I decided to select another hard-coded date nightly version so we don't run the risk of some random nightly release breaking this workflow.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    utACK 9ddd5025382341a5e941630473563edc593645f4

Tree-SHA512: 650fc4880c1de37f3cd581ba1e2f416ac732d06e03b1dea2878b5051bf38ff809dd965baa0987c7ce47e5aa5e30932cedad3dce17fca6b787e6ace72d604c591
2022-12-14 20:15:47 +01:00
Steve Myers
9ddd502538
Update ci nightly-docs workflow to use nightly-2022-12-14 2022-12-14 11:53:54 -06:00
Daniela Brozzoni
a5d345fff2
Merge bitcoindevkit/bdk#811: Downgrade ubuntu to 20.04 for test_hardware_wallet CI job
11dcc14374e13c526972cd57a9ad726d183fc015 Downgrade ubuntu to 20.04 for test_hardware_wallet CI job (Steve Myers)

Pull request description:

  ### Description

  As suggested by bitcoindevkit/rust-hwi#61, downgrade ubuntu version to 20.04 (instead of using latest), to fix `test_hardware_wallet` CI job.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK 11dcc14374e13c526972cd57a9ad726d183fc015

Tree-SHA512: 26de7bb0e562065a9d1071fb292f8532894f921c3557c418e95b05dfff529d8e5bf1751d8b5136618d3b768f10d8af714882f7c453c91a08a9c5e9aafef976b5
2022-12-06 08:17:20 +01:00
Steve Myers
11dcc14374
Downgrade ubuntu to 20.04 for test_hardware_wallet CI job 2022-12-05 11:23:40 -06:00
Steve Myers
4c5ceaff14
Merge bitcoindevkit/bdk#806: Ensure there are no duplicated script_pubkeys in sqlite
b5fcddcf1ab795b96481f3e46da9356e4f9c8b41 Add sqlite migration to drop duplicated script_pubkeys rows (Steve Myers)
21c96c9c811337ba04a0f85b48a7dec58ba8b416 Add test for issue #801 (Alekos Filini)
c51d544932a666851c39f79a517e2e0a1e783b05 [wip] Ensure there are no duplicated script_pubkeys in sqlite (Alekos Filini)

Pull request description:

  ### Description

  Add a `UNIQUE` constraint on the script_pubkeys table so that it doesn't grow constantly when caching new addresses.

  Fixes #801

  ### Notes to the reviewers

  Adding it to the 0.25 milestone since it's just a bugfix.

  Still in draft because I need to add extra migration queries to clean up existing dbs.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK b5fcddcf1ab795b96481f3e46da9356e4f9c8b41

Tree-SHA512: 7b10e453bb38af5c4f80f77692a56e37259680e50f9c2c9e554a0e5f04fb9cab897da6476c6c9930f1c501b455472984a1c92c4f137cff49acdc390d2e705107
2022-11-30 09:05:47 -08:00
Steve Myers
b5fcddcf1a
Add sqlite migration to drop duplicated script_pubkeys rows 2022-11-29 07:20:49 -08:00
Alekos Filini
d570ff2c65
Merge bitcoindevkit/bdk#803: Bump version to 0.25.0
5e56c3b3c15e093b20beee669609d40424a04481 Bump version to 0.25.0 (Steve Myers)

Pull request description:

  ### Description

  Bump version to 0.25.0

ACKs for top commit:
  afilini:
    ACK 5e56c3b3c15e093b20beee669609d40424a04481

Tree-SHA512: b1fc49caed9676d4e3db2a625b6209fffa19694ada2e2ff4d3e5d5cbbd6816ff03924387d66bf3a8b8ec4a3b44bf5d00d95cc450427e5b669e88af60400b02c9
2022-11-28 10:55:16 +01:00
Alekos Filini
21c96c9c81
Add test for issue #801 2022-11-26 15:11:09 +01:00
Alekos Filini
c51d544932
[wip] Ensure there are no duplicated script_pubkeys in sqlite
Add a `UNIQUE` constraint on the script_pubkeys table so that it doesn't
grow constantly when caching new addresses.

Fixes #801
2022-11-26 15:04:34 +01:00
Steve Myers
5e56c3b3c1
Bump version to 0.25.0 2022-11-24 22:01:01 -08:00
Steve Myers
235961a934
Merge bitcoindevkit/bdk#746: Add mnemonic_to_descriptors example
df905a8d5ef8e275188389486ac685b29f0d8c9f Add mnemonic to descriptors example. (Vladimir Fomene)

Pull request description:

  ### Description

  Using *bdk-cli* it is simple for a new user to generate a mnemonic phrase and descriptors. This might
  not be clear for new users when using *bdk* itself.

  ### Notes to the reviewers

  This was initially requested by one user but might be relevant for other users as well.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK df905a8d5ef8e275188389486ac685b29f0d8c9f

Tree-SHA512: ccaab775d664d1d5ad6f4cd4fb11f9552c4662fbac747ad0487a016fd4a0fa6f13fcb4dffdc6f0d2f14ee432fcb2a72a8b8837b0a977ded649ec7d3d84e1c0ed
2022-11-24 12:52:42 -08:00
Vladimir Fomene
df905a8d5e
Add mnemonic to descriptors example.
This was initially requested by one user but might be
relevant for other users as well.
2022-11-24 21:18:13 +03:00
Steve Myers
8b68cf9546
Merge bitcoindevkit/bdk#800: fix: ensure the key network is updated in the KeyMap as well
150f4d6f41427d5d8a6608e7da4f30dfe3d0801a fix: ensure the key network is updated in the KeyMap as well (Alekos Filini)

Pull request description:

  ### Description

  Otherwise we may have inconsistencies with keys in the descriptor that have a network and keys in the keymap that are different.

  ### Notes to the reviewers

  Adding it to the `0.25` milestone since it's just a quick fix

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 150f4d6f41427d5d8a6608e7da4f30dfe3d0801a

Tree-SHA512: df87323cc29cf74f54a0867bfbe9fe24543de69dc6443656bd920458c9055d4b05614430c89bb470a8a6f7d10da023a0fb107b1cfb0fcc38e50f0579b6411a33
2022-11-24 09:23:10 -08:00
Alekos Filini
150f4d6f41
fix: ensure the key network is updated in the KeyMap as well
Otherwise we may have inconsistencies with keys in the descriptor that
have a network and keys in the keymap that are different.
2022-11-23 17:58:47 +01:00
Steve Myers
1c95ca33a8
Merge bitcoindevkit/bdk#526: Add code example for each supported backend
f99a6b9f434e86a78695da72e9d28e6937c7e5db add `esplora_backend` example. (w0xlt)
aedbc8c97d6bf87347c3fd3796d1f0dfe6a8701c add `electrum_backend` example. (w0xlt)

Pull request description:

  This PR adds code example for connecting to Esplora, Electrum Server, Neutrino and Bitcoin Core.
  Also shows how to retrieve balance, sign and broadcast transactions.

  To test:
  ```
  cd examples/backend/
  cargo run electrum
  cargo run esplora
  cargo run neutrino
  cargo run rpc_core
  ```

ACKs for top commit:
  rajarshimaitra:
    tACK f99a6b9f434e86a78695da72e9d28e6937c7e5db

Tree-SHA512: 1d99129f14d83d9a833cee1587fe0eb3e5da4c83ae9008fb3e510be96a874dc86f800f203f68f5da70648a911709107cf0f286c2623808dc97dd63b7addef16b
2022-11-22 08:13:16 -08:00
Steve Myers
108edc3a6b
Merge bitcoindevkit/bdk#785: Fix wallet export rescan height
e9bbb8724f92ada33228bbfc22acdaefbd79c44e Fix wallet export rescan height (LLFourn)

Pull request description:

  It would return the latest transaction height rather than the earliest as the height to rescan from.

  Found by @evanlinjin  and I while implementing `bdk_core` stuff into bdk's wallet.

  ### Changelog notice

  - Fix wallet export transaction height

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing

ACKs for top commit:
  rajarshimaitra:
    tACK e9bbb8724f92ada33228bbfc22acdaefbd79c44e
  notmandatory:
    ACK e9bbb8724f92ada33228bbfc22acdaefbd79c44e

Tree-SHA512: 9b29ef0df39d26806f48b38fa5c3643bad32f58b993ffdcfc7811aca64a025bd8f163967321f874aa2ef3d29c3e7bc6e2f44d348306a37111f4def036d4c095e
2022-11-22 06:30:17 -08:00
w0xlt
f99a6b9f43
add esplora_backend example. 2022-11-01 19:59:55 -03:00
w0xlt
aedbc8c97d
add electrum_backend example. 2022-11-01 19:59:46 -03:00
Steve Myers
5c42102c79
Bump version to 0.24.0 2022-10-26 23:27:30 -05:00
Steve Myers
5d5b2fb88c
Merge bitcoindevkit/bdk#765: Fix how descriptor checksums are calculated
648282e60283f579ba1644fe506ae1370786da96 Update docs and tests based on review comments (Steve Myers)
60057a7bf78f01bfb1149251f384de6432f94d59 Deprecate backward compatible get_checksum_bytes, get_checksum functions (Steve Myers)
e2a4a5884b444a6ef3f137ef2cc21a816c386acf Ensure backward compatibility of the  "checksum inception" bug (志宇)
fd34956c2980295e1f0cc32340fb2b99a6b245ea `get_checksum_bytes` now checks input data for checksum (志宇)

Pull request description:

  ### Description

  Previously, the methods `get_checksum_bytes` and `get_checksum` do not check input data to see whether the input data already has a checksum.

  This PR does the following:

  * Introduce a `exclude_hash: bool` flag for `get_checksum_bytes`, that excludes the checksum portion of the original data when calculating the checksum. In addition to this, if the calculated checksum does not match the original checksum, an error is returned for extra safety.
  * Ensure `Wallet` is still backwards compatible with databases created with the "checksum inception" bug.

  ### Notes to the reviewers

  Thank you.

  ### Changelog notice

  Fix the "checksum inception" bug, where we may accidentally calculate the checksum of a descriptor that already has a checksum.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  ~* [ ] I'm linking the issue being fixed by this PR~

Top commit has no ACKs.

Tree-SHA512: 7ea2721dcd56459b6996e56a3ddfc3559a0c64869a08f5312a8f0f4fcb5dbef7ac7461a4ab017acde4a62fed02d8a620c402dd384323aba85736610514fcb7e1
2022-10-26 22:39:38 -05:00
Steve Myers
9cb6f70fc0
Merge branch 'master' into fix_wallet_checksum 2022-10-26 22:01:07 -05:00
Steve Myers
5720e38033
Merge bitcoindevkit/bdk#770: Upgrade to rust-bitcoin 0.29
c7a43d941fd0f457f615f2fe43e71586a253e46a Remove unused code (Alekos Filini)
1ffd59d469ff28f673d854eaf15c992c15541bfe Upgrade to rust-bitcoin 0.29 (Alekos Filini)
ae4f4e541671e85be04fdddc97cb7f65af1eeea1 Upgrade `rand` to `0.8` (Alekos Filini)
9854fd34eaa688e5acd601119b8f448a2d77fbd9 Remove deprecated address validators (Alekos Filini)

Pull request description:

  ### Description

  Upgrade BDK to rust-bitcoin 0.29

  Missing pieces:

  - [x] rust-miniscript `update_output_with_descriptor` - rust-bitcoin/rust-miniscript#465
  - [x] rust-miniscript 8.0.0 release - rust-bitcoin/rust-miniscript#462
  - [x] Upgrade rust-hwi to bitcoin 0.29 bitcoindevkit/rust-hwi#50
  - [x] Upgrade esplora-client to bitcoin 0.29 https://github.com/bitcoindevkit/rust-esplora-client/pull/20
  - [x] Upgrade rand to 0.8 like secp256k1 did

  ### Notes to the reviewers

  The commits still need to be reordered and cleaned up

  ### Changelog notice

  - Upgrade rust-bitcoin to 0.29
  - Remove deprecated "address validators"

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK c7a43d941fd0f457f615f2fe43e71586a253e46a

Tree-SHA512: 718a1baf3613b31ec1de39fe63467ebee38617963a4ce0670a617e20fe4f46a57c5786933cdde6cfad9fc76ce0af08843f58844fb4a89f5948cb42c697f802ef
2022-10-26 21:46:41 -05:00
LLFourn
e9bbb8724f
Fix wallet export rescan height
It would return the latest transaction height rather than the earliest :S
2022-10-26 12:35:21 +08:00
Steve Myers
648282e602
Update docs and tests based on review comments 2022-10-25 11:20:22 -05:00
Alekos Filini
c7a43d941f
Remove unused code 2022-10-25 12:14:36 +02:00
Alekos Filini
1ffd59d469
Upgrade to rust-bitcoin 0.29 2022-10-25 11:16:02 +02:00
Alekos Filini
ae4f4e5416
Upgrade rand to 0.8 2022-10-25 11:15:59 +02:00
Alekos Filini
9854fd34ea
Remove deprecated address validators 2022-10-25 11:08:47 +02:00
Steve Myers
60057a7bf7
Deprecate backward compatible get_checksum_bytes, get_checksum functions
Rename replacement functions calc_checksum_bytes and calc_checksum
2022-10-24 14:24:54 -05:00
Alekos Filini
ea47d7a35b
Merge bitcoindevkit/bdk#758: Add HWI example in docs
1437e1ecfe663b819156d98c5e1975fb357a763f Add the hardware_signer example (Daniela Brozzoni)
1a71eb1f4736651ad82e0abd64792b6cc7b16c20 Update the hardwaresigner module documentation (Daniela Brozzoni)
0695e9fb3e41727e5732561a993411147487afd3 Bump HWI to 0.2.3 (Daniela Brozzoni)
a4a43ea86060fa0a62b47dedc7de820459b3a472 Re-export HWI if the hardware-signer feature is set (Daniela Brozzoni)

Pull request description:

  ### Description

  ### Notes to the reviewers

  ### Changelog notice

  - bdk re-exports the `hwi` create when the feature `hardware-signer` is on
  - Add `examples/hardware_signer.rs`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  afilini:
    ACK 1437e1ecfe663b819156d98c5e1975fb357a763f

Tree-SHA512: 181f4d14dce11e19497fbf30e0af8de21c2c210d37129d7d879ed5670ed09a25be1c8d371389c431e18df9e76870cf5e4afe7b29a6c05fe59b3e1816bc8cf673
2022-10-24 10:53:39 +02:00
Steve Myers
f2181f5467
Merge bitcoindevkit/bdk#782: Make psbt mod public and add required docs
34987d58ec9933af455e44d20c8d889bc896f869 Make psbt mod public and add required docs (Steve Myers)

Pull request description:

  ### Description

  Make psbt mod public and add required docs. The module needs to be public so `bdk-ffi` can expose the new PSBT `fee_amount()` and `fee_rate()` functions.

  ### Notes to the reviewers

  I should have done this as part of #728.

  ### Changelog notice

  Make psbt module public to expose PsbtUtils trait to downstream projects.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  rajarshimaitra:
    Concept + tACK 34987d58ec9933af455e44d20c8d889bc896f869

Tree-SHA512: 99e91e948bccb7593a3da3ac5468232103d4ba90ad4e5888ef6aebb0d16511ad3a3286951779789c05587b4bb996bc359baa28b0f4c3c55e29b24bfc12a10073
2022-10-21 17:58:47 -05:00
Steve Myers
34987d58ec
Make psbt mod public and add required docs 2022-10-18 15:26:12 -05:00
Daniela Brozzoni
1c76084db8
Merge bitcoindevkit/bdk#779: Add signature grinding for ECDSA signatures
68dd6d20311b28f5c8e8c9657dce8cddae4f7aa3 Add signature grinding for ECDSA signatures (Vladimir Fomene)

Pull request description:

  ### Description

  This PR adds a new field called `allow_grinding`
  in the Signer's `SignOptions` struct that is used
  to determine whether or not to grind an ECDSA signature during the signing process.

  ### Changelog notice

  Breaking change: the BDK Signer now produces low-R signatures by default, saving one byte. If you want to preserve the original behavior, set `allow_grinding` in the `SignOptions` to `false`.

  ### Notes to the reviewers

  This PR resolves issue #695

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK 68dd6d20311b28f5c8e8c9657dce8cddae4f7aa3
  rajarshimaitra:
    ACK 68dd6d20311b28f5c8e8c9657dce8cddae4f7aa3

Tree-SHA512: 6472338c611b4b32986cf66fcd313ef84f17f5b0ae9e7991ea7da47142641ab812f8b325d4d18314e1a58abe462683101160e62e2363a048fdab3f18aee4d699
2022-10-17 11:48:19 +01:00
Vladimir Fomene
68dd6d2031
Add signature grinding for ECDSA signatures
This PR adds a new field called `allow_grinding`
in the Signer's `SignOptions` struct that is used
to determine whether or not to grind an ECDSA signature
during the signing process.
2022-10-17 12:27:35 +03:00
Daniela Brozzoni
1437e1ecfe
Add the hardware_signer example 2022-10-13 10:46:49 +01:00
Daniela Brozzoni
1a71eb1f47
Update the hardwaresigner module documentation
Add a little example on how to use the HWISigner, slightly improve
the module description
2022-10-13 10:46:47 +01:00
Daniela Brozzoni
0695e9fb3e
Bump HWI to 0.2.3 2022-10-12 14:24:09 +01:00
Daniela Brozzoni
a4a43ea860
Re-export HWI if the hardware-signer feature is set 2022-10-12 14:23:42 +01:00
Daniela Brozzoni
b627455b8f
Merge bitcoindevkit/bdk#780: Update psbt_signer example to use descriptor! macro
1331193800911bb8168e5d1c2689676af3c1fe86 Update psbt_signer example to use descriptor! macro (Steve Myers)

Pull request description:

  ### Description

  This is a small fix to the psbt_signer example to also use the `descriptor!` macro.

  ### Notes to the reviewers

  I also added more docs to at the beginning of the example.

  ### Changelog notice

  None

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Example:

  * [x] I've added docs for the new example

ACKs for top commit:
  danielabrozzoni:
    ACK 1331193800911bb8168e5d1c2689676af3c1fe86

Tree-SHA512: 602fa317313dea77bc4804abce500db33d5834625704019c6590ae6b80cf339cbaddffef667eaef2696e8e769756a2c2405c84109409ef33816db60d3df4d53d
2022-10-12 11:07:29 +01:00
Steve Myers
1331193800
Update psbt_signer example to use descriptor! macro 2022-10-09 21:39:04 -05:00
Steve Myers
7de8be46c0
Add enhancement request github issue template 2022-10-01 10:14:37 -05:00
Alekos Filini
55145f57a1
Bump version to 0.23.0 2022-09-29 20:57:36 +02:00
Steve Myers
8e8fd49e04
Merge bitcoindevkit/bdk#764: Use the esplora client crate
d7bfe68e2df270ab799d36ebf3563e178ae50c6e Fix broken nightly docs (Alekos Filini)
b11c86d074a8f56f99bd5f3af77d3b056af71de4 Rename internal esplora modules, fix docs (Alekos Filini)
b5b92248c76aeb42ac747931efd45bc2e7af5ebd Rename esplora features to -async and -blocking (Alekos Filini)
cf2bc388f22b069fc25fba482e59da6305207864 Re-export `esplora_client` (Elias Rohrer)
5baf46f84d41fb714f200a7b26170c9b77823dc1 Use the external esplora client library (Alekos Filini)

Pull request description:

  ### Description

  Use the external esplora client crate now that it's published

  ### Changelog notice

  - Start using the external esplora client crate
  - Deprecate the `use-esplora-reqwest` and `use-esplora-ureq` features in favor of `use-esplora-async` and `use-esplora-blocking`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK d7bfe68e2df270ab799d36ebf3563e178ae50c6e

Tree-SHA512: 23bd47536fe6f723602cbcc51d909eb9aed28376430f4453eea832e30a587be3d312cdca993d114391132bfb39c48637030f974ab1a742f7defe44f40a82ef8b
2022-09-29 11:46:05 -05:00
Alekos Filini
d7bfe68e2d
Fix broken nightly docs 2022-09-29 12:00:11 +02:00
Alekos Filini
b11c86d074
Rename internal esplora modules, fix docs 2022-09-29 12:00:09 +02:00
志宇
e2a4a5884b
Ensure backward compatibility of the "checksum inception" bug
`Wallet` stores the descriptors' checksum in the database for safety.
Previously, the checksum used was a checksum of a descriptor that
already had a checksum.

This PR allows for backward-compatibility of databases created with this
bug.
2022-09-29 14:45:24 +08:00
志宇
fd34956c29
get_checksum_bytes now checks input data for checksum
If `exclude_hash` is set, we split the input data, and if a checksum
already existed within the original data, we check the calculated
checksum against the original checksum.

Additionally, the implementation of `IntoWalletDescriptor` for `&str`
has been refactored for clarity.
2022-09-29 13:06:03 +08:00
Alekos Filini
b5b92248c7
Rename esplora features to -async and -blocking 2022-09-28 21:08:18 +02:00
Elias Rohrer
cf2bc388f2
Re-export esplora_client 2022-09-28 21:08:16 +02:00
Alekos Filini
5baf46f84d
Use the external esplora client library 2022-09-28 21:08:14 +02:00
Daniela Brozzoni
a8cf34e809
Merge bitcoindevkit/bdk#763: Fix Wallet::descriptor_checksum to actually return the checksum
af0b3698c691cd08ece9ae201cc9699f0d57acc8 Fix `Wallet::descriptor_checksum` to actually return the checksum (志宇)

Pull request description:

  ### Description

  `Wallet::descriptor_checksum` should return the checksum, not the descriptor without the checksum.

  ### Notes to the reviewers

  Please merge.

  ### Changelog notice

  Fix `Wallet::descriptor_checksum` to actually return the descriptor checksum.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  ~* [ ] This pull request breaks the existing API~
  * [x] I've added tests to reproduce the issue which are now passing
  ~* [ ] I'm linking the issue being fixed by this PR~

ACKs for top commit:
  danielabrozzoni:
    ACK af0b3698c691cd08ece9ae201cc9699f0d57acc8 - I run the test you added with the old code, and verified that the bug was there. I then run the test (with a few more dbg!() expressions) and manually verified that the problem is fixed.
  notmandatory:
    ACK af0b3698c691cd08ece9ae201cc9699f0d57acc8

Tree-SHA512: 64a5b1f4708db6f6dcff2f6ef5e0a4c7d206e764d7602ea803c8cc002410326eb59eee770d9c91694dfbf07193ee3ff6bfe163bcbb3506cd7b2a6b59814a3e5c
2022-09-28 15:26:22 +02:00
志宇
af0b3698c6
Fix Wallet::descriptor_checksum to actually return the checksum 2022-09-27 21:56:25 +08:00
志宇
92ad4876c4
Add vscode filter to gitignore 2022-09-27 20:40:14 +08:00
Steve Myers
b14e4ee3a0
Merge bitcoindevkit/bdk#756: Remove genesis_block lazy initialization
e6f2d029fa9708f98599c1bd4ef74d232b111c5a Remove genesis_block lazy initialization (Shobit Beltangdy)

Pull request description:

  ### Description

  This commit contains a change to address issue #752

  cargo test runs successfully.

  ### Notes to the reviewers

  Hi, newbie here learning Rust and BDK!  I've removed the lazy_static block in this commit, and when learning about lazy_static also came across something called [once_cell](https://doc.rust-lang.org/std/cell/struct.OnceCell.html), [soon to be available in stdlib](https://github.com/rust-lang/rust/issues/74465).  It's like lazy_static but faster and is not a macro.  Shall I keep the lazy_static and create an issue to switch to once_cell in the future, or remove the lazy_static (as I've done) and create an issue anyway?

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK e6f2d029fa9708f98599c1bd4ef74d232b111c5a

Tree-SHA512: 528f5fdfb0d7d1f7a83869b7a0de1b25dfcfafae2671c9229cdb4e5d80d11e5578d9325b3d95555e59f5dfb4ed6304c0c112a01a56b6a596e50dd62e310c516e
2022-09-26 17:33:35 -05:00
Shobit Beltangdy
e6f2d029fa
Remove genesis_block lazy initialization
This commit contains a change to address issue #752

cargo test runs successfully.
2022-09-26 10:54:12 -07:00
Steve Myers
bbf524b3f9
Merge bitcoindevkit/bdk#754: Fix the release process
e1fa0b66954cc56dae055464ab5bb40b7a5043be Fix the new release process (Alekos Filini)

Pull request description:

  ### Description

  A few things I noticed while doing the 0.22 release.

  Follow-up of #544

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

ACKs for top commit:
  notmandatory:
    ACK e1fa0b66954cc56dae055464ab5bb40b7a5043be

Tree-SHA512: 5e60e73ba1f820fc39f62b75583e1125f911e578ab7263a20636e2a995d0efa10ba1b3b66a1e03d8a2ed61e32c00b53de9d6bbdb31de94db37c79fa5acdbf483
2022-09-26 11:45:40 -05:00
Daniela Brozzoni
dbf6bf5fdf
Merge bitcoindevkit/bdk#761: Remove redundant duplicated keys check
e2bf9734b16f5a0f419f1c1fc39c9773fd7e1128 Remove redundant duplicated keys check (Alekos Filini)

Pull request description:

  ### Description

  This check is redundant since it's already performed by miniscript (see https://docs.rs/miniscript/7.0.0/miniscript/miniscript/analyzable/enum.AnalysisError.html#variant.RepeatedPubkeys) and it was incorrectly failing on tr descriptors that contain duplicated keys across different taproot leaves

  Fixes #760

  ### Changelog notice

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    Code review ACK e2bf9734b16f5a0f419f1c1fc39c9773fd7e1128 - the code looks good to me, but I didn't test manually

Tree-SHA512: 3c557d741e34abf6336c7e257867f2c6f91a4be0024317af834f08ba7c0c64557bd74b643005254c9f04e953350b104b0d4d287f0d0528134b357a4adf580f87
2022-09-26 14:45:58 +02:00
Alekos Filini
aff41d6e1c
Merge bitcoindevkit/bdk#730: Update compiler example to a Policy example
97b6fb06aa6d95d1c8cf1498cc4478d0f27423e4 Add a policy example (rajarshimaitra)
da7670801b81e3e67ff776444afc6e6b48fc10bb Update compiler example. (rajarshimaitra)

Pull request description:

  ### Description

  Fixes #729.

  There is an "unmaintained" warning in a old version of clap, which triggered the issue.

  Ideally, we should not have clap in bdk's dependency. It was only used for the `compiler.rs` example, which was a very tiny clap app compiling miniscript policies, and it wasn't really an example for bdk.

  This PR rewrites the example as a `policy.rs` which demos the BDK's Policy module and policy structures.

   - Use a `wsh(multi(2, Privkey, Pubkey))` descriptor, which has only one part private and other part public.
   - use `into_wallet_descriptor()` to turn that into a `Descriptor` and `KeyMap`.
   - Use the `KeyMap` to create a custom signer.
   - Extract the descriptor `Policy` structure from the given keymap.

   I am not very sure on how much this example is helpful. I still find it hard to read the Policy structure visually. But if Policy is something we want the user to know about descriptors and bdk wallets, this shows how to extract it for a simple multisig condition.

  Note: There is no use of `bdk::wallet` in the example. BDK uses the Policy extraction internally while transaction creation. But all these are exposed publicly, so can be used independently too.

  ### Questions:

  - Should we still have a `minscript::policy::compile()` example?  Which IIUC is very different from `bdk::policy:Policy`.  I didn't include it in this PR, because I am not sure if it fits inside bdk example categories.

   - Should we expose `extract_policy` as an wallet API? All though its possible to get policy without creating a wallet, why not let the wallet also spit one out for itself, if its useful?

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  afilini:
    ACK 97b6fb06aa6d95d1c8cf1498cc4478d0f27423e4

Tree-SHA512: 8e3719fdad308a347d22377050b2f29e02a884ff7d4e57a05a06d078de0709b5bf70bbcb1a696d1e1cdfe02cdb470e5af643da7c775b67fe318046bd6b80f440
2022-09-26 14:13:46 +02:00
Alekos Filini
e2bf9734b1
Remove redundant duplicated keys check
This check is redundant since it's already performed by miniscript (see
https://docs.rs/miniscript/7.0.0/miniscript/miniscript/analyzable/enum.AnalysisError.html#variant.RepeatedPubkeys)
and it was incorrectly failing on tr descriptors that contain duplicated
keys across different taproot leaves

Fixes #760
2022-09-24 15:42:42 +02:00
Alekos Filini
c3faf05be9
Merge bitcoindevkit/bdk#713: Add datatype for is_spent sqlite column
54d768412abf218d2646aba211bb79b9dd287118 Sqlite migrations should either succeed or fail (Vladimir Fomene)
369e17b8012df56587c10cd9ce6651908d6a4be9 Add datatype for is_spent sqlite column (Vladimir Fomene)

Pull request description:

  ### Description

  During table creation, Sqlite does not throw an error when a column datatype is not defined. In addition, the datatype provided during table creation does not put a constraint on the type of data that can be put in that column. So you can easily put a string value in an integer column. Despite this, I think it is important for us to add the datatype for clarity.

  ### Notes to the reviewers

  You can read more about how Sqlite dynamic typing [here](https://www.sqlite.org/faq.html). I have amended our `migrate` code with a new commit. The idea is to run migrations in a transaction so that they either succeed or fail. This prevents us from having the database in an inconsistent state at any point in time.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  rajarshimaitra:
    tACK 54d768412abf218d2646aba211bb79b9dd287118
  afilini:
    ACK 54d768412abf218d2646aba211bb79b9dd287118

Tree-SHA512: bb6c0467f799ca917f8d45c6495b766352b3177fc81952fcdd678208abf092fdeae966686528a5dcb3f342d7171783274df6312a08cbef3580063e059f5f7254
2022-09-23 12:08:17 +02:00
Alekos Filini
aad5461ee1
Merge bitcoindevkit/bdk#757: Enable signing taproot transactions with only non_witness_utxos
5e9965fca7fb50708af0d293a9f6cd27d0c85fed Enable signing taproot transactions with only `non_witness_utxos` (Alekos Filini)

Pull request description:

  ### Description

  Some wallets may only specify the `non_witness_utxo` for a PSBT input. If that's the case, BDK should still be able to sign.

  This was pointed out in the discussion of #734

  ### Changelog notice

  - Enable signing taproot transactions that only specify the `non_witness_utxo`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    tACK 5e9965fca7fb50708af0d293a9f6cd27d0c85fed - the code looks good to me, I played around with the test you provided (inspecting the PSBT, adding/removing the witness and non-witness utxos, etc) and everything works as expected.

Tree-SHA512: 2f205286263bfee4c76de8e8c81ae1349b1c3b255b72045488f8d629c05cab64c6f775307e831674dc036e5a3a760f95d9cdc1beaf48afb4c475aee838131a33
2022-09-23 11:52:20 +02:00
Daniela Brozzoni
0a7a1f4ef2
Merge bitcoindevkit/bdk#745: Add tests to improve coverage
e65edbf53cb14e273ff99ed0576843dd3367385d Change parameter name of database in test funcs (Vladimir Fomene)
88307045b0f049b7f6b9c0cdc577c4a4bb3a041e Add more test to the database module (Vladimir Fomene)
e06c3f945ca5de4ce4f78bc2179c00e42d0bb4e5 Set tx field to none if `include_raw` is false (Vladimir Fomene)

Pull request description:

  ### Description

  This PR add more test to the database module and also fixes certain bugs discovered by the written test. I also amended the name used for the database parameter in the test functions.

  ### Notes to the reviewers

  This contributes to fixing #699

  ### Changelog notice

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  rajarshimaitra:
    tACK e65edbf53cb14e273ff99ed0576843dd3367385d
  danielabrozzoni:
    Code review ACK e65edbf53cb14e273ff99ed0576843dd3367385d

Tree-SHA512: 1ac1475f7d63f25e94ef21342e6f6e243c34c8c9208d11a5492f224026055da2a96f20be83497c1ba361effff9861f4e68920f98feebaf4b201d205c7030c282
2022-09-22 13:02:55 +02:00
Alekos Filini
5e9965fca7
Enable signing taproot transactions with only non_witness_utxos
Some wallets may only specify the `non_witness_utxo` for a PSBT input.
If that's the case, BDK should still be able to sign.

This was pointed out in the discussion of #734
2022-09-19 10:54:55 +02:00
Vladimir Fomene
54d768412a
Sqlite migrations should either succeed or fail
The current implementation of the `migrate` method for
Sqlite database does not rollback changes when there is
an error while running one of the migration scripts. This
can leave the database in an inconsistent state. This
change ensures that migrations either succeed completely
or fail.
2022-09-16 19:03:56 +03:00
rajarshimaitra
97b6fb06aa
Add a policy example
Add a new policy example demonstrating the bdk's policy structure
and how to derive it for any descriptor without creating a bdk wallet.
2022-09-16 18:50:26 +05:30
rajarshimaitra
da7670801b
Update compiler example.
Change the compiler clap app into a specific example. Add comment docs
and example description. Remove clap from dependency.
2022-09-16 18:50:26 +05:30
Alekos Filini
e1fa0b6695
Fix the new release process 2022-09-16 14:56:27 +02:00
Alekos Filini
dfeb08fa00
Merge bitcoindevkit/bdk#753: Improve docs regarding PSBT finalization
8963e8c9f445f4069262edffd15cbd971c0adc6b Improve docs w.r.t. PSBT finalization (Elias Rohrer)

Pull request description:

  ### Description

  This PR includes just a few tiny changes to the docs trying to make it a bit more clear what PSBT finalization is and what to expect.

  ### Notes to the reviewers

  ### Changelog notice

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  afilini:
    ACK 8963e8c9f445f4069262edffd15cbd971c0adc6b

Tree-SHA512: ea1a6c715c2832cdf3a428654fb8fad08a0549e46a808ca7a424590145fc2c40164ea08eb636ce5cd648dd6335480accd1d91f9e37e9397feaf0dac2015e8baa
2022-09-15 16:16:19 +02:00
Elias Rohrer
8963e8c9f4
Improve docs w.r.t. PSBT finalization 2022-09-15 14:45:47 +02:00
Alekos Filini
562cb81cad
Merge bitcoindevkit/bdk#728: Add fee_amount() and fee_rate() functions to PsbtUtils trait
ab41679368be79e8645915b40be554cc07557931 Add fee_amount() and fee_rate() functions to PsbtUtils trait (Steve Myers)

Pull request description:

  ### Description

  The purpose of the PR is to provide a more convenient way to calculate the transaction fee amount and fee rate for a PSBT. This PR adds `fee_amount` and `fee_rate` functions to the existing `PsbtUtils` trait and implements them for `PartiallySignedBitcoinTransaction`. The `fee_rate` value is only valid if the PSBT it is called on is fully signed and finalized.

  See related discussion: https://github.com/bitcoindevkit/bdk-ffi/issues/179

  ### Changelog

  Added
  - PsbtUtils.fee_amount(), calculates the PSBT total transaction fee amount in Sats.
  - PsbtUtils.fee_rate(), calculates the PSBT FeeRate, the value is only accurate AFTER the PSBT is finalized.

  ### Notes to the reviewers

  Ideally I'd like `fee_rate` to return an `Option` and return `None` if the PSBT isn't finalized. But I'm not quite sure how to determine if a PSBT is finalized without having a `Wallet` and running it through the finalize code first. Or there might be a way to fill in missing signatures with properly sized fake data prior to calculating the fee rate. For now I think it's enough to do this simple approach with usage warning in the rust docs.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature

ACKs for top commit:
  afilini:
    ACK ab41679368be79e8645915b40be554cc07557931

Tree-SHA512: 5386109c9ffcf63160f18b4c51eb2c582f4121b669c7276aaba489d186cf9b97343d46f887469b1407ccd7a24448b5e7aee4c6832d86768239b21f4e68054a0f
2022-09-13 18:36:23 +02:00
Alekos Filini
b12dec3620
Merge bitcoindevkit/bdk#744: Add psbt_signer.rs example
fa998de4b1849adcf43351dbec05b3de43e6694e Add psbt_signer.rs example (Steve Myers)

Pull request description:

  ### Description

  Adding a simple example of how to create a PSBT with a watch only wallet and then sign it with a signing wallet.

  ### Notes to the reviewers

  This example was inspired by a question from a user.

  ### Changelog notice

  none.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK fa998de4b1849adcf43351dbec05b3de43e6694e
  afilini:
    ACK fa998de4b1849adcf43351dbec05b3de43e6694e

Tree-SHA512: 2e178ee59ce94eb1e9b5616a499e106e1d2843589036bdb6cff2c987e280588ad9989b026cdbf01290cc60f02eccbc410a3e1d1cd45eb4b8ff04353ae31b23ea
2022-09-13 18:24:38 +02:00
Vladimir Fomene
e65edbf53c
Change parameter name of database in test funcs
Change parameter name in database test functions
from `tree` to `db`.
2022-09-13 16:36:31 +03:00
Vladimir Fomene
88307045b0
Add more test to the database module
This PR aims to add more test to database
code so that we can catch bugs as soon
as they occur. Contributing to fixing
issue #699.
2022-09-13 16:35:53 +03:00
Vladimir Fomene
e06c3f945c
Set tx field to none if include_raw is false
`del_tx` pulls the TransactionDetails object using
`select_transaction_details_by_txid` method which gets the transaction
details' data with a non-None transaction field even if the
`include_raw` argument is `false`. So it becomes necessary to Set
the transaction field in transactiondetails to None in `del_tx`, when
we make a call to it with `include_raw=false`.
2022-09-13 11:08:03 +03:00
Steve Myers
ab41679368
Add fee_amount() and fee_rate() functions to PsbtUtils trait
PsbtUtils.fee_amount(), calculates the PSBT total transaction fee amount in Sats.
PsbtUtils.fee_rate(), calculates the PSBT FeeRate, the value is only accurate AFTER the PSBT is finalized.
2022-09-12 22:01:18 -05:00
Alekos Filini
7b12f35698
Merge bitcoindevkit/bdk#747: Run code coverage on every PR
aa0ea6aeff474a9934d4e9eb6e14ea1667573fc5 codecov: warn about missing features (Daniela Brozzoni)
c3a7bbb3ff936031200a7b70d5d9287f7f242513 codecov: slightly change the test features (Daniela Brozzoni)
1c4d47825b0ebc6027f04b8672ccabe83cbd8cee Run code coverage on every PR (Daniela Brozzoni)

Pull request description:

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK aa0ea6aeff474a9934d4e9eb6e14ea1667573fc5
  afilini:
    ACK aa0ea6aeff474a9934d4e9eb6e14ea1667573fc5

Tree-SHA512: c2d0d9ad1e956f1c1808b46394f810939154442534241f9a023f18173910339ac236a5b6c66f78207dd2cb90a8f18000fc057b960e3354e2882c627fe1ef2c9f
2022-09-12 16:39:27 +02:00
Daniela Brozzoni
aa0ea6aeff
codecov: warn about missing features 2022-09-10 18:11:22 +02:00
Daniela Brozzoni
c3a7bbb3ff
codecov: slightly change the test features
- Remove default and minimal, as they are redundant
- Use lexicographic order
2022-09-10 18:11:17 +02:00
Daniela Brozzoni
1c4d47825b
Run code coverage on every PR
In this way we can check how much of a PR is covered by the tests,
making the review process slightly easier.
2022-09-09 22:34:58 +02:00
Steve Myers
fa998de4b1
Add psbt_signer.rs example 2022-09-07 20:33:39 -05:00
Alekos Filini
06310f1dd0
Merge bitcoindevkit/bdk#708: Change configs for source-base code coverage
0010ecd94aae49f389093cd3e8983c405049dbf5 Add badge to README (wszdexdrf)
690411722e2131f69a605a6f3b5e97911778e9ed Change configs for source-base code coverage (wszdexdrf)

Pull request description:

  ### Description

  This also changes the code coverage front end to coveralls instead of codecov, which had some issues with other changes in the PR. This will provide better and more accurate code coverage reports.

  ### Notes to the reviewers

  The tests run before generating the report are not exhaustive (not exhaustive earlier too, but I added as many as I could), and hence the report won't be 100% accurate.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK 0010ecd94aae49f389093cd3e8983c405049dbf5

Tree-SHA512: 04a21b7481b80287cf8a31276238b0a5958871310664363f54d53779bb2dda6f49198baaf3b5471667fa6131443b022aabd86f2e3b1cfcf5d4aacadf137a166e
2022-09-02 16:57:21 +02:00
Alekos Filini
8dd02094df
Merge bitcoindevkit/bdk#737: Update electrum-client to 0.11.0
d7163c3a976daf1b6a38884d77546a745805bd3c Update electrum-client to 0.11.0 (Alekos Filini)

Pull request description:

  ### Description

  Update electrum-client to 0.11.0

  ### Changelog notice

  - Updated `electrum-client` to `0.11.0`

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  danielabrozzoni:
    utACK d7163c3a976daf1b6a38884d77546a745805bd3c

Tree-SHA512: 3be61935e2bebfc5e4b530d17b9900e3c1bd2ef377fdd18df4303de713b124d51555f48f7aff5f4c2579105e86f52480e6b3f2af9c7494cbdb1dd2a2c5b4e0da
2022-09-02 16:53:12 +02:00
wszdexdrf
0010ecd94a
Add badge to README 2022-09-02 11:20:08 +05:30
wszdexdrf
690411722e
Change configs for source-base code coverage
Also add cacheing to code coverage workflow
2022-09-02 11:20:04 +05:30
Alekos Filini
7001b14b4c
Bump version to 0.22.0 2022-09-01 15:46:44 +02:00
Alekos Filini
13cf72ffa7
Merge bitcoindevkit/bdk#738: Fix docs.rs features
3451d1c12e4271b6067ff246d095eb9fb1ca3bd5 Fix docs.rs features (Alekos Filini)

Pull request description:

  ### Description

  Fix docs.rs features

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

ACKs for top commit:
  danielabrozzoni:
    utACK 3451d1c12e4271b6067ff246d095eb9fb1ca3bd5
  notmandatory:
    ACK 3451d1c12e4271b6067ff246d095eb9fb1ca3bd5

Tree-SHA512: 96dc4f816b21cf20fc2828dcfd56865f3f9add8e4aa643205879c810d09e6f2e73d6643061bf3ca98145b37e726907dedd31a145f92d6646c172a43ae2285aa8
2022-08-31 15:57:48 +02:00
Alekos Filini
d7163c3a97
Update electrum-client to 0.11.0 2022-08-31 15:34:20 +02:00
Alekos Filini
cf13c80991
Merge bitcoindevkit/bdk#544: Update DEVELOPMENT_CYCLE.md to work with [patch.crates-io]
7c57965999ca4a3d640d1dc11d7e10401abcabbf Bump version before making release branch, separate patch_release template (Steve Myers)
3d69f1c291b8d595399bfcb3ce202dca77a3f474 Update DEVELOPMENT_CYCLE.md to work with [patch.crates-io] (Steve Myers)

Pull request description:

  ### Description

  Update DEVELOPMENT_CYCLE and release instructions to make [overriding dependencies] possible for downstream projects with unreleased `bdk` versions for development and testing. Also simplifies the release process by capturing changelog information in the `pull_request_template` and recording release changelog information in the release tag message instead of in a `CHANGELOG.md` file which causes too many merge conflicts and complicates the release process.

  Fixes #536
  Fixes #496

  ### Notes to the reviewers

  The primary changes to our current release process are:

  1. Don't add `-dev` or `-rc.x` to unreleased `bdk` cargo versions because those extensions do not work with [overriding dependencies].
  2. Increment the `master` branch version as soon as a `release/MAJOR.MINOR` branch is created, the next release `release/MAJOR.MINOR` branch version with be **MAJOR.MINOR.PATCH**, and the `master` branch development version will be **MAJOR.MINOR+1.0**; either version can be used with [overriding dependencies].
  4. Remove the `bdk` version from the `src/lib.rs` file so that it doesn't need to be changed on every release, because it isn't needed in the rust docs for most developers and removing it will help simplify the release process.
  5. The new release process is now documented as a checklist in a new `release.md` github issue template.
  6. Putting changelog information in the release tag message is how the tokio project does it. ~~After this PR is merged I will replace old tags with new ones containing changelog information and then do a new PR to remove the CHANGELOG.md file.~~ After this PR is merged I don't think we need to update old tags, only rename the CHANGELOG.md file to CHANGELOG-OLD.md with a note to check tags for future change log info.

  [overriding dependencies]: https://doc.rust-lang.org/cargo/reference/overriding-dependencies.html

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  afilini:
    ACK 7c57965999ca4a3d640d1dc11d7e10401abcabbf

Tree-SHA512: 818e2f9bc7a629cbbb190a83b9743e8f4de49a4093beae83ed0b9c506f33e6f96b2c1e376f788536d58c46908d278bde08140f43a625515401ea1f9efdb9153f
2022-08-31 15:18:20 +02:00
Steve Myers
7c57965999
Bump version before making release branch, separate patch_release template 2022-08-31 07:43:06 -05:00
Steve Myers
3d69f1c291
Update DEVELOPMENT_CYCLE.md to work with [patch.crates-io] 2022-08-31 07:43:03 -05:00
Alekos Filini
3451d1c12e
Fix docs.rs features 2022-08-31 11:23:51 +02:00
Daniela Brozzoni
4fbd8520e6
Merge bitcoindevkit/bdk#689: Add allow_dust method to TxBuilder
bfd7b2f65debe57edc5d563c071f0bfce592a8d2 Allow creating transactions with dust outputs (Liam)

Pull request description:

  We needed this for testing our wallet with dust, does this look like a reasonable feature? If so, I'll go ahead and add a test, update the changelog, etc.

ACKs for top commit:
  danielabrozzoni:
    tACK bfd7b2f65debe57edc5d563c071f0bfce592a8d2

Tree-SHA512: b467b365d8a68f5a868cc5cc88387677533e8fb0bf543bf4c7a5b984f8b28972281029a3be8d2c92cee7d6ee05c243d12af0841e7a7e1d652745567557f2bede
2022-08-31 10:31:01 +02:00
Liam
bfd7b2f65d
Allow creating transactions with dust outputs
Add TxBuilder::allow_dust() that skips checking the dust limit
2022-08-30 11:25:34 -04:00
Alekos Filini
061f15af00
Merge bitcoindevkit/bdk#682: Add a custom signer for hardware wallets
138acc3b7d137788d0518182e2167504e58ebc48 Change `populate_test_db` to not return empty input (wszdexdrf)
d6e1dd104063075f49b617786d82d29c1f9c6a0a Change CI to add test using ledger emulator (wszdexdrf)
76034772cba4d3d6fa1bdcb08977c2b9d7a157c2 Add a custom signer for hardware wallets (wszdexdrf)

Pull request description:

  Also adds a new test in CI for building and testing on a virtual
  hardware wallet.

  ### Description

  This PR would enable BDK users to sign transactions using a hardware wallet. It is just the beginning hence there are no complex features, but I hope not for long.
  I have added a test in CI for building a ledger emulator and running the new test on it. The test is similar to the one on bitcoindevkit/rust-hwi.

  ### Notes to the reviewers
  The PR is incomplete (and wouldn't work, as the rust-hwi in `cargo.toml` is pointing to a local crate, temporarily) as a small change is required in rust-hwi (https://github.com/bitcoindevkit/rust-hwi/pull/42).

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  afilini:
    ACK 138acc3b7d137788d0518182e2167504e58ebc48

Tree-SHA512: 54337f06247829242b4dc60f733346173d957de8e9f8b80beb91304d679cfb4e0e4db722c967469265a5b6ede2bd641ba5c089760391c671995dc30de37897de
2022-08-29 16:15:02 +02:00
Vladimir Fomene
369e17b801
Add datatype for is_spent sqlite column
Although, Sqlite column accepts
values of any type, it is
important to annotate this column
to make it easy to reason about.
2022-08-29 13:35:33 +03:00
Alekos Filini
2bff4e5e56
Merge bitcoindevkit/bdk#726: [bug-fix] Set the db sync height
08668ac46247d527cc53af5b6f359b1fa4e3b6aa Set the db sync height (rajarshimaitra)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Fixes #719

  Previously we weren't setting the db sync height in populate_test_db
  macro even when current height is provided.. This creates a bug that
  get_funded_wallet will return 0 balance.

  This PR fixes the populate_test_db macro and updates tests which were
  previously dependent on the unsynced wallet behavior.

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 08668ac46247d527cc53af5b6f359b1fa4e3b6aa

Tree-SHA512: 1dcc968e4b3551e916b450c5ff2fab6636083f104cc982eb3f7602c624382434e0170d9f0c0a356e6c9c5f834eebe5cb1365b37ef73d7b4ef15d652a364dc2ab
2022-08-29 10:24:40 +02:00
wszdexdrf
138acc3b7d
Change populate_test_db to not return empty input 2022-08-29 13:54:01 +05:30
wszdexdrf
d6e1dd1040
Change CI to add test using ledger emulator 2022-08-29 13:54:01 +05:30
wszdexdrf
76034772cb
Add a custom signer for hardware wallets
Also add function to get funded wallet with coinbase
2022-08-29 13:53:56 +05:30
Daniela Brozzoni
12507c707f
Merge bitcoindevkit/bdk#678: Implement conversion for Lightning fee rate
de358f8cdc97bf685ba46cf6751443d007b9f58e Implement conversion for Lightning fee rate (Vladimir Fomene)

Pull request description:

  This PR fixes #608.

  ### Description

  Lightning denotes transaction fee rate sats / 1000 weight units and sats / 1000 vbytes.
  Here we add support for creating BDK FeeRate from lightning fee rate. We also move all FeeRate tests to
  types.rs and rename as_sat_vb to as_sat_per_vb.

  ### Notes to the reviewers

  Matt was concerned that we might round down value in fee calculation in such a way that a transaction may not be relayed because it is below Bitcoin Core's min relay fee (1 sat/vbyte). I don't think we need to worry about that because we [round up(ceil)](https://github.com/bitcoindevkit/bdk/blob/master/src/types.rs#L91) during fee calculation, we don't round down. I will love to hear what you think. Is there something I'm missing? @johncantrell97, I will appreciate your review on this one.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK de358f8cdc97bf685ba46cf6751443d007b9f58e

Tree-SHA512: aaa7da8284b668d15ad9c92168c149c4b3ee0f8faee9b7eb159745d23e38835189eaf5c336da14ba9272ee07cd366718eefb8365da9ddf53014e122b6393a087
2022-08-29 10:02:31 +02:00
Vladimir Fomene
de358f8cdc
Implement conversion for Lightning fee rate
Lightning denotes transaction fee rate
sats / 1000 weight units and sats / 1000 vbytes.
Here we add support for creating BDK fee rate from
lightning fee rate. We also move all FeeRate test to
types.rs and rename as_sat_vb to as_sat_per_vb.
2022-08-28 21:37:07 +03:00
rajarshimaitra
08668ac462
Set the db sync height
Previously we weren't setting the db sync height in populate_test_db
macro even when current height is provided.. This creates a bug that
get_funded_wallet will return 0 balance.

This PR fixes the populate_test_db macro and updates tests which were
previously dependent on the unsynced wallet behavior.
2022-08-28 23:51:24 +05:30
Alekos Filini
0a3734ed2b
Merge bitcoindevkit/bdk#718: Verify signatures after signing
7b1ad1b62914a26d6f445364ace4e784bb2901c2 Verify signatures after signing (Scott Robinson)

Pull request description:

  ### Description

  Verify signatures after signing

  As per [BIP-340, footnote 14][fn]:
  > Verifying the signature before leaving the signer prevents random or
  > attacker provoked computation errors. This prevents publishing invalid
  > signatures which may leak information about the secret key. It is
  > recommended, but can be omitted if the computation cost is prohibitive.

  [fn]: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#cite_note-14

  ### Notes to the reviewers

  How do we test this?

  ### Checklists

  #### All Submissions:

  * [ ] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  afilini:
    re-ACK 7b1ad1b62914a26d6f445364ace4e784bb2901c2

Tree-SHA512: 7319db1f8cec2fcfe4ac443ab5728893f9fb6133b33331b35ec6910662c45de8a7cdcf80ac1f3bb435815e914ccf639682a5c07ff0baef42605bf044a34a8232
2022-08-25 12:21:40 +02:00
Alekos Filini
a5d1a3d65c
Merge bitcoindevkit/bdk#722: Implement Deref<Target=UrlClient> for EsploraBlockchain
baf7eaace66edcae8bf3252a962b9417b704ba26 Implement Deref<Target=UrlClient> for EsploraBlockchain (Vladimir Fomene)

Pull request description:

  ### Description

  There is currently no way to access the client from the EsploraBlockchain. This makes it difficult for users to extend it's functionality. This PR exposes both the reqwest and ureq clients. This PR is related to PR #705.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  rajarshimaitra:
    tACK baf7eaace66edcae8bf3252a962b9417b704ba26

Tree-SHA512: e2f530058c88e06fc2972edfcd2df1b534d43b0214d710b62e4d5200ac0e38dad6a9f8db1e0c7a7ed19892e59411dcc07f3f6dc8ad58afae9d677169ca98bb38
2022-08-25 12:20:12 +02:00
Alekos Filini
7bc2980905
Merge bitcoindevkit/bdk#705: Implement Deref<Target=Client> for ElectrumBlockchain
c5952dd09a61b1cd2185c273e0b8bcb3fd6ed2dd Implement `Deref<Target=Client>` for `ElectrumBlockchain` (Alekos Filini)

Pull request description:

  ### Description

  As pointed out in https://github.com/bitcoindevkit/rust-electrum-client/pull/58#issuecomment-1207890096 there was no way to keep using the client once it was given to BDK.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  rajarshimaitra:
    ACK c5952dd09a61b1cd2185c273e0b8bcb3fd6ed2dd

Tree-SHA512: fbfbada51c9426266c8960da5508ee07b196808f0d670a09a51962bd6eda9ccf585e209f5b99b5ab78a3d17af774bdb3e33ef36ac4f4d1ce7f2c3398ae4f6d0c
2022-08-25 12:19:21 +02:00
Alekos Filini
34e792e193
Merge bitcoindevkit/bdk#731: Implement Deref<Target=Client> for RpcBlockchain
a8f9f6c43adb90c9ceced21da6b6bafaa90d7af9 RpcBlockchain derefs to the underlying RPC Client (rajarshimaitra)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  For the same reason as #705  and #722 ..

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  afilini:
    ACK a8f9f6c43adb90c9ceced21da6b6bafaa90d7af9

Tree-SHA512: 81e596fe451c275ca0ce27ee7ac9cf7e88433775603021c2dd1cd26a26558531cf74f81ef05d0ae9d5d0e59e91196e3ac6d38c0f4853b1889ddf822d8e63e178
2022-08-25 12:18:22 +02:00
Scott Robinson
7b1ad1b629
Verify signatures after signing
As per [BIP-340, footnote 14][fn]:
> Verifying the signature before leaving the signer prevents random or
> attacker provoked computation errors. This prevents publishing invalid
> signatures which may leak information about the secret key. It is
> recommended, but can be omitted if the computation cost is prohibitive.

[fn]: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#cite_note-14
2022-08-25 16:29:44 +10:00
rajarshimaitra
a8f9f6c43a
RpcBlockchain derefs to the underlying RPC Client 2022-08-23 21:44:38 +05:30
Alekos Filini
c9b1b6d076
Merge bitcoindevkit/bdk#723: Fix P2WPKH_SATISFACTION_SIZE in CS tests
cd078903a7108f86fdd9557b206f25c9611d07d3 Fix P2WPKH_SATISFACTION_SIZE in CS tests (Daniela Brozzoni)

Pull request description:

  Our costant for the P2WPKH satisfaction size was wrong: in
  7ac87b8f99fc0897753ce57d48ea24adf495a633 we added 1 WU for the script
  sig len - but actually, that's 4WU! This resulted in
  P2WPKH_SATISFACTION_SIZE being equal to 109 instead of 112.
  This also adds a comment for better readability.

  ### Description

  ### Notes to the reviewers

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  csralvall:
    utACK cd078903a7108f86fdd9557b206f25c9611d07d3
  afilini:
    ACK cd078903a7108f86fdd9557b206f25c9611d07d3

Tree-SHA512: 3e39735505e411392cf01885b5920443d23fa21d9c20cc7c8fdeaa2698df8bc2da86241b6c20f5e3f5941fe1a0aebe8f957d8145d4f9e7ad3f213e4658d6ea68
2022-08-17 13:46:48 +02:00
Daniela Brozzoni
cd078903a7
Fix P2WPKH_SATISFACTION_SIZE in CS tests
Our costant for the P2WPKH satisfaction size was wrong: in
7ac87b8f99fc0897753ce57d48ea24adf495a633 we added 1 WU for the script
sig len - but actually, that's 4WU! This resulted in
P2WPKH_SATISFACTION_SIZE being equal to 109 instead of 112.
This also adds a comment for better readability.
2022-08-16 18:27:59 +01:00
Alekos Filini
588c17ff69
Merge bitcoindevkit/bdk#711: Release/0.21.0
8026bd9476fc5a89baa86ea2a8707a9d341d3743 Bump version to 0.21.1-dev (Alekos Filini)
e2bd96012a08137e4f6776c9192d5247ae20df0b Bump version to 0.21.0 (Alekos Filini)
2c01b6118f3291c2918a60cac635f26df1780dac Bump version to 0.21.0-rc.1 (Alekos Filini)

Pull request description:

  ### Description

  Merge the release branch back into master

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK 8026bd9476fc5a89baa86ea2a8707a9d341d3743

Tree-SHA512: a2a924a60d551a823de035b609d4d51652a165a0695212af76dea87706919c8929dba977bb297f4787708470bf075d14dd0a37657bd3a76e7d44a746fb5439df
2022-08-16 13:39:49 +02:00
Vladimir Fomene
baf7eaace6
Implement Deref<Target=UrlClient> for EsploraBlockchain
There is currently no way to access the client
from the EsploraBlockchain. This makes it difficult
for users to extend it's functionality. This PR exposes
both the reqwest and ureq clients. This PR is related to
PR #705.
2022-08-15 19:34:57 +03:00
Alekos Filini
8026bd9476
Bump version to 0.21.1-dev 2022-08-11 20:56:03 +02:00
Alekos Filini
e2bd96012a
Bump version to 0.21.0 2022-08-11 17:02:32 +02:00
Alekos Filini
9be63e66ec
Merge commit 'refs/pull/703/head' of github.com:bitcoindevkit/bdk into release/0.21.0 2022-08-09 12:06:13 +02:00
Alekos Filini
9f9ffd0efd
Merge bitcoindevkit/bdk#703: Fix minor typos in docs
134b19a9cb127989402fe331f48a1e37eb3cdcad Fix minor typos in docs (thunderbiscuit)

Pull request description:

  ### Description
  This PR fixes:
  1. The use of "i.e." in docs, sometimes spelled as "ie."
  2. A small typo in the sentence "Note that this methods only operate on the internal database..."
  3. A small typo in the sentence "Finish the building the transaction"

  I came across these while building docs for bdk-kotlin.

  ### Notes to the reviewers

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    ACK 134b19a9cb127989402fe331f48a1e37eb3cdcad

Tree-SHA512: 67296999eba8ffe1fe64756fa023d85064774cb9d4c26e99054d467b5024baea4138f11d602d04e695412c61625ee4f5b4687b75f177cfec2604a6c61a5a6216
2022-08-09 12:05:35 +02:00
Alekos Filini
2db881519a
Merge branch 'release/0.21.0', commit 'refs/pull/704/head' of github.com:bitcoindevkit/bdk into release/0.21.0 2022-08-09 11:54:23 +02:00
Alekos Filini
d9adfbe047
Merge bitcoindevkit/bdk#704: Fix rpc::CoreTxIter logic.
74e2c477f124489a2357921ca879cc82e24da5fd Replace `rpc::CoreTxIter` with `list_transactions` fn. (志宇)

Pull request description:

  ### Description

  This fixes a bug where `CoreTxIter` attempts to call `listtransactions` immediately after a tx result is filtered (instead of being returned), when in fact, the correct logic will be to pop another tx result.

  The new logic also ensures that tx results are returned in chonological order. The test `test_list_transactions` verifies this. We also now ensure that `page_size` is between the range `[0 to 1000]` otherwise an error is returned.

  Some needless cloning is removed from `from_config` as well as logging improvements.

  ### Notes to the reviewers

  This is an oversight by me (sorry) for PR #683

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  ~* [ ] This pull request breaks the existing API~
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 74e2c477f124489a2357921ca879cc82e24da5fd

Tree-SHA512: f32314a9947067673d19d95da8cde36b350c0bb0ebe0924405ad50602c14590f7ccb09a3e03cdfdd227f938dccd0f556f3a2b4dd7fdd6eba1591c0f8d3e65182
2022-08-09 11:49:56 +02:00
志宇
74e2c477f1
Replace rpc::CoreTxIter with list_transactions fn.
This fixes a bug where `CoreTxIter` attempts to call `listtransactions`
immediately after a tx result is filtered (instead of being returned),
when in fact, the correct logic will be to pop another tx result.

The new logic also ensures that tx results are returned in chonological
order. The test `test_list_transactions` verifies this. We also now
ensure that `page_size` is between the range `[0 to 1000]` otherwise an
error is returned.

Some needless cloning is removed from `from_config` as well as logging
improvements.
2022-08-08 21:12:23 +08:00
Alekos Filini
c5952dd09a
Implement Deref<Target=Client> for ElectrumBlockchain
As pointed out in https://github.com/bitcoindevkit/rust-electrum-client/pull/58#issuecomment-1207890096
there was no way to keep using the client once it was given to BDK.
2022-08-08 12:03:35 +02:00
thunderbiscuit
134b19a9cb
Fix minor typos in docs 2022-08-05 12:45:18 -04:00
Alekos Filini
2c01b6118f
Bump version to 0.21.0-rc.1 2022-08-04 11:59:56 +02:00
Alekos Filini
03d3c786f2
Merge bitcoindevkit/bdk#640: Get balance in categories
0f03831274d3aa69da6e89729c65d66530bbd752 Change get_balance to return in categories. (wszdexdrf)

Pull request description:

  ### Description
  This changes `get_balance()` function so that it returns balance separated in 4 categories:
  - available
  - trusted-pending
  - untrusted-pending
  - immature

  Fixes #238

  ### Notes to the reviewers
  Based on #614

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've updated tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  afilini:
    ACK 0f03831274d3aa69da6e89729c65d66530bbd752

Tree-SHA512: 39f02c22c61b6c73dd8e6d27b1775a72e64ab773ee67c0ad00e817e555c52cdf648f482ca8be5fcc2f3d62134c35b720b1e61b311cb6debb3ad651e79c829b93
2022-08-04 11:43:40 +02:00
wszdexdrf
0f03831274
Change get_balance to return in categories.
Add type balance with add, display traits. Change affected tests.
Update `CHANGELOG.md`
2022-08-04 10:37:09 +02:00
Alekos Filini
dc7adb7161
Merge bitcoindevkit/bdk#683: Fix wallet sync for RpcBlockchain
5eeba6cced9a6fa0ad8ee4f64d04e1948620eac8 Various `RpcBlockchain` improvements (志宇)
5eb74af41494b7ec4894d7da3015da2981639228  Rpc: Manually add immature coinbase utxos (志宇)
ac19c19f21fce43a99ecf0c4f95ae818b620558c New `RpcBlockchain` implementation with various fixes (志宇)

Pull request description:

  Fixes #677

  ### Description

  Unfortunately to fix all the problems, I had to do a complete re-implementation of `RpcBlockchain`.

  **The new implementation fixes the following:**
  * We can track more than 100 scriptPubKeys
  * We can obtain more than 1000 transactions per sync
  * Transaction "metadata" for already-syned transactions are updated when we introduce new scriptPubKeys

  **`RpcConfig` changes:**
  * Introduce `RpcSyncParams`.
  * Remove `RpcConfig::skip_blocks` (this is replaced by `RpcSyncParams::start_time`).

  ### Notes to the reviewers

  * The `RpcConfig` structure is changed. It will be good to confirm whether this is an okay change.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  ~* [ ] I've added tests for the new feature~
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 5eeba6cced9a6fa0ad8ee4f64d04e1948620eac8

Tree-SHA512: 7e0c9cfc4ef10fb07e4ac7f6fbf30cf28ca6395495c0237fa5bfa9a2fcbbd4d8ff980ffcf71ddd10bc052e4c07bc2c27f093dd3cd1c69cb29141455c693f2386
2022-08-04 10:23:19 +02:00
志宇
5eeba6cced
Various RpcBlockchain improvements
These are as suggested by @danielabrozzoni and @afilini

Also introduced `RpcSyncParams::force_start_time` for users who
prioritise reliability above all else.

Also improved logging.
2022-08-04 11:29:38 +08:00
志宇
5eb74af414
Rpc: Manually add immature coinbase utxos
Before this commit, the rpc backend would not notice immature utxos
(`listunspent` does not return them), making the rpc balance different
to other blockchain implementations.

Co-authored-by: Daniela Brozzoni <danielabrozzoni@protonmail.com>
2022-08-04 11:27:50 +08:00
志宇
ac19c19f21
New RpcBlockchain implementation with various fixes
The new implementation fixes the following:
* We can track more than 100 scriptPubKeys
* We can obtain more than 1000 transactions per sync
* `TransactionDetails` for already-synced transactions are updated when
  new scriptPubKeys are introduced (fixing the missing balance/coins
      issue of supposedly tracked scriptPubKeys)

`RpcConfig` changes:
* Introduce `RpcSyncParams`.
* Remove `RpcConfig::skip_blocks` (this is replaced by
  `RpcSyncParams::start_time`).
2022-08-04 11:27:37 +08:00
Daniela Brozzoni
ef03da0a76
Merge bitcoindevkit/bdk#693: Fix the early InsufficientFunds error in the branch and bound
9d85c9667f7d12902afef3ba08ea7231f6868a78 Fix the early InsufficientFunds error in the branch and bound (Alekos Filini)

Pull request description:

  ### Description

  We were wrongly considering the sum of "effective value" (i.e. value -
  fee cost) when reporting an early "insufficient funds" error in the
  branch and bound coin selection.

  This commit fixes essentially two issues:
  - Very high fee rates could cause a panic during the i64 -> u64
    conversion because we assumed the sum of effective values would never
    be negative
  - Since we were comparing the sum of effective values of *all* the UTXOs
    (even the optional UTXOs with negative effective value) with the target
    we'd like to reach, we could in some cases error and tell the user we
    don't have enough funds, while in fact we do! Since we are not required
    to spend any of the optional UTXOs, so we could just ignore the ones
    that *cost us* money to spend and excluding them could potentially
    allow us to reach the target.

  There's a third issue that was present before and remains even with this
  fix: when we report the "available" funds in the error, we are ignoring
  UTXOs with negative effective value, so it may look like there are less
  funds in the wallet than there actually are.

  I don't know how to convey the right message the user: if we actually
  consider them we just make the "needed" value larger and larger (which
  may be confusing, because if the user asks BDK to send 10k satoshis, why
  do we say that we actually need 100k?), while if we don't we could report
  an incorrect "available" value.

  ### Notes to the reviewers

  I'm opening this as a draft before adding tests because I want to gather some feedback on the available vs needed error reporting. I personally think reporting a reasonable "needed" value is more important than the "available", because in a wallet app I would expect this is the value that would be shown to the user.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    utACK 9d85c9667f7d12902afef3ba08ea7231f6868a78

Tree-SHA512: 9a06758cba61ade73198f35b08070987d5eb065e01750ce62409f86b37cd0b0894640e9f75c8b2c26543c0da04e3f77bd397fab540e789f221661aae828db224
2022-08-03 20:04:28 +02:00
Alekos Filini
9d85c9667f
Fix the early InsufficientFunds error in the branch and bound
We were wrongly considering the sum of "effective value" (i.e. value -
fee cost) when reporting an early "insufficient funds" error in the
branch and bound coin selection.

This commit fixes essentially two issues:
- Very high fee rates could cause a panic during the i64 -> u64
  conversion because we assumed the sum of effective values would never
  be negative
- Since we were comparing the sum of effective values of *all* the UTXOs
  (even the optional UTXOs with negative effective value) with the target
  we'd like to reach, we could in some cases error and tell the user we
  don't have enough funds, while in fact we do! Since we are not required
  to spend any of the optional UTXOs, so we could just ignore the ones
  that *cost us* money to spend and excluding them could potentially
  allow us to reach the target.

There's a third issue that was present before and remains even with this
fix: when we report the "available" funds in the error, we are ignoring
UTXOs with negative effective value, so it may look like there are less
funds in the wallet than there actually are.

I don't know how to convey the right message the user: if we actually
consider them we just make the "needed" value larger and larger (which
may be confusing, because if the user asks BDK to send 10k satoshis, why
do we say that we actually need 100k?), while if we don't we could report
an incorrect "available" value.
2022-08-03 19:15:06 +02:00
Daniela Brozzoni
85bd126c6c
Merge bitcoindevkit/bdk#686: doc: Document that list_transactions() might return unsorted txs
7fdacdbad40f4e9f6726b064d8eb4d93789e9990 doc: Document that list_transactions() might return unsorted txs, show how to sort them if needed (w0xlt)

Pull request description:

  This PR documents that `list_transactions()` might return unsorted transaction and shows how to sort them if needed.

  Closes #518.

ACKs for top commit:
  danielabrozzoni:
    re-ACK 7fdacdbad40f4e9f6726b064d8eb4d93789e9990

Tree-SHA512: 83bec98e1903d6dc6b8933e8994cb9d04aad059cee8a7b8e1e3a322cf52511364b36d0cd6be1c8cb1fd82c67f8be5a262bbd2c76e30b24eb4097c30f38aa8b10
2022-08-03 17:17:36 +02:00
w0xlt
7fdacdbad4
doc: Document that list_transactions() might return unsorted txs, show how to sort them if needed 2022-08-03 12:08:50 -03:00
Alekos Filini
9c0a769675
Merge bitcoindevkit/bdk#662: Consolidate fee_amount and amount_needed
e8df3d2d91927edb9a339c664f0603c47622e4b0 Consolidate `fee_amount` and `amount_needed` (Cesar Alvarez Vallero)

Pull request description:

  ### Description

  Before this commit `fee_amount` and `amount_needed` were passed as independent
  parameters. From the perspective of coin selection algorithms, they are always
  used jointly for the same purpose, to create a coin selection with a total
  effective value greater than it's summed values.

  This commit removes the abstraction that the use of the two parameter
  introduced by consolidating both into a single parameter, `target_amount`, who
  carries their values added up.

  Resolves: #641

  ### Notes to the reviewers

  I just updated old tests and didn't create new ones because almost all changes
  are renames and "logic changes" (like the addition of the selection fee) are
  tested in the modified tests.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    re-ACK e8df3d2d91927edb9a339c664f0603c47622e4b0 - I tested with the fuzzer, run it for 13,000,000 iterations, couldn't find any crash :)

Tree-SHA512: 64b46473799352c06cc554659e4b159a33812b3d3793c9d436bd1e46b65edd085d71b219f6a0474f6836979ca608aa019a72bdc6915a2cc2d744a76e2a28b889
2022-08-03 12:32:44 +02:00
Alekos Filini
11865fddff
Merge bitcoindevkit/bdk#681: Add electrsd/bitcoind_22_0 to example\rpcwallet target
a63c51f35dc392bfcd390cbda0eb40205b78ac8e Add `electrsd/bitcoind_22_0` to `example\rpcwallet` target (w0xlt)

Pull request description:

  On master branch, `example\rpcwallet` fails.

  ```
  $ cargo run --features="keys-bip39 key-value-db rpc" --example rpcwallet
     Compiling bitcoin_hashes v0.9.7
     Compiling bip39 v1.0.1
     Compiling bdk v0.20.1-dev (/home/node01/Dev/wbdk)
      Finished dev [unoptimized + debuginfo] target(s) in 19.64s
       Running `target/debug/examples/rpcwallet`
  >> Setting up bitcoind
  thread 'main' panicked at 'We should always have downloaded path: Called a method requiring a feature to be set, but it's not', examples/rpcwallet.rs:56:51
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
  ```

  This PR adds `electrsd/bitcoind_22_0` to `required-features`, making clear that this lib is needed to run this example..

  ```
  $ cargo run --features="keys-bip39 key-value-db rpc electrsd/bitcoind_22_0" --example rpcwallet
      Blocking waiting for file lock on package cache
     Compiling electrsd v0.19.1
     Compiling bdk v0.20.1-dev (/home/node01/Dev/wbdk)
      Finished dev [unoptimized + debuginfo] target(s) in 10.27s
       Running `target/debug/examples/rpcwallet`
  >> Setting up bitcoind
  >> bitcoind setup complete
  Available coins in Core wallet : 50.00000000 BTC

  >> Setting up BDK wallet
  >> BDK wallet setup complete.
  Available initial coins in BDK wallet : 0 sats

  >> Sending coins: Core --> BDK, 10 BTC
  >> Received coins in BDK wallet
  Available balance in BDK wallet: 1000000000 sats

  >> Sending coins: BDK --> Core, 5 BTC
  >> Coins sent to Core wallet
  Remaining BDK wallet balance: 499999859 sats

  Congrats!! you made your first test transaction with bdk and bitcoin core.
  ```

ACKs for top commit:
  afilini:
    reACK a63c51f35dc392bfcd390cbda0eb40205b78ac8e

Tree-SHA512: ef13d5e001121c8b1ff6436f9e95b656737bee6692e9b18c4012846a2d2e9e9ad7e6b5cd87cebf4a873335e92a524694e684567a1268f5f0705156659fd9a916
2022-08-03 12:31:11 +02:00
Cesar Alvarez Vallero
e8df3d2d91
Consolidate fee_amount and amount_needed
Before this commit `fee_amount` and `amount_needed` were passed as independent
parameters. From the perspective of coin selection algorithms, they are always
used jointly for the same purpose, to create a coin selection with a total
effective value greater than it's summed values.

This commit removes the abstraction that the use of the two parameter
introduced by consolidating both into a single parameter, `target_amount`, who
carries their values added up.
2022-08-03 12:19:01 +02:00
w0xlt
a63c51f35d
Add electrsd/bitcoind_22_0 to example\rpcwallet target 2022-08-03 12:13:56 +02:00
Alekos Filini
1730e0150f
Merge bitcoindevkit/bdk#666: Various fixes to the fee_amount calculation in create_tx
419dc248b667db05295cd4c68347c4ef51f51023 test: Document `test_bump_fee_add_input_change_dust` (Daniela Brozzoni)
632dabaa07ef9c58926facf0af5190f62bb65d12 test: Check tx feerate with longer signatures (Daniela Brozzoni)
2756411ef7cf0415baf2f2401e2d5a78481d0aa1 test: Reproduce #660 conditions (Daniela Brozzoni)
50af51da5a5c906d8bf660d35a4f922ceb996068 test: Fix P2WPKH_FAKE_WITNESS_SIZE (Daniela Brozzoni)
ae919061e2b341ae74c90f0133ba392e835cb4e1 Take into account the segwit tx header when... ...selecting coins (Daniela Brozzoni)
7ac87b8f99fc0897753ce57d48ea24adf495a633 TXIN_BASE_WEIGHT shouldn't include the script len (Daniela Brozzoni)
ac051d7ae9512883e11a89ab002ad2d2c3c55c19 Calculate fee amount after output addition (Daniela Brozzoni)
00d426b88546a346820c102386cd1bfff82ca8f6 test: Check that the feerate is never below... ...the requested one in assert_fee_rate (Daniela Brozzoni)
42fde6d4575b4aea121286f884f712b1c1cf64be test: Check fee_amount in assert_fee_rate (Daniela Brozzoni)

Pull request description:

  ### Description

  This PR mainly fixes two bugs:
  1. TXIN_BASE_WEIGHT wrongly included the `script_len` (Fixes #160)
  2. We wouldn't take into account the segwit header in the fee calculation, which could have resulted in a transaction with a lower feerate than the requested one
  3. In tests we used to push 108 bytes on the witness as a fake signature, but we should have pushed 106 instead

  I also add a test to reproduce the conditions of #660, to check if it's solved. Turns out it's been solved already in #630, but if you're curious about what the bug was, here it is: https://github.com/bitcoindevkit/bdk/issues/660#issuecomment-1196436776
  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 419dc248b667db05295cd4c68347c4ef51f51023

Tree-SHA512: c7b55342eac440a3607a16b94560cb9c08c4805c853432adfda8e21c5177f85d5a8afe0e7e61140e92c8f10934332459c6234fc5f1509ea699d97b1d04f030c6
2022-08-03 11:40:36 +02:00
Alekos Filini
5a415979af
Merge bitcoindevkit/bdk#645: Allow signing only specific leaf hashes
a713a5a0629c9a643708a4b0d8d6ac3a87a13195 Better customize signing in taproot transactions (Daniela Brozzoni)

Pull request description:

  Fixes #616

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  afilini:
    ACK a713a5a0629c9a643708a4b0d8d6ac3a87a13195

Tree-SHA512: 1100d43cb394b429450fc34f49dd815a024701987c0e6dd163865bd5c4c6f7102127b1ea6e10ced5fdb319874be97baeeb0deea66b4138410871a1d68b4def10
2022-08-02 22:48:29 +02:00
Daniela Brozzoni
a713a5a062
Better customize signing in taproot transactions
We would previously always try to sign with the taproot internal
key, and try to sign all the script leaves hashes.
Instead, add the `sign_with_tap_internal_key` and `TapLeaveOptions`
parameters, to be able to specify if we should sign with the internal
key, and exactly which leaves we should sign.
Fixes #616
2022-08-02 12:20:08 +02:00
Daniela Brozzoni
419dc248b6
test: Document test_bump_fee_add_input_change_dust
Add a rationale for the feerate in the test
2022-08-02 12:09:42 +02:00
Daniela Brozzoni
632dabaa07
test: Check tx feerate with longer signatures
This commit also suppresses the `unused_mut` warning
in `assert_fee_rate`, which happens because we call it
without `add_signatures`.
2022-08-02 12:08:56 +02:00
Daniela Brozzoni
2756411ef7
test: Reproduce #660 conditions
Issue #660 has been fixed by 32ae95f463f62c42c6d6aec62c1832a30298fce4,
when we moved the change calculation inside the coin selection.
This commit just adds a test to make sure that the problem is fixed.
2022-08-02 12:08:55 +02:00
Daniela Brozzoni
50af51da5a
test: Fix P2WPKH_FAKE_WITNESS_SIZE
We would previously push 108 bytes on a P2WPKH witness
to simulate signature + pubkey. This was wrong: we should push
106 bytes instead.
The max satisfaction size for a P2WPKH is 112 WU:
elements in witness (1 byte, 1WU) + OP_PUSH (1 byte, 1WU) +
pk (33 bytes, 33 WU) + OP_PUSH (1 byte, 1WU) + signature and sighash
(72 bytes, 72 WU) + scriptsig len (1 byte, 4WU)
We should push on the witness pk + signature and sighash. This is 105
WU. Since we push just once instead of twice, we add 1WU for the OP_PUSH
we are omitting.
2022-08-02 12:08:54 +02:00
Daniela Brozzoni
ae919061e2
Take into account the segwit tx header when...
...selecting coins

We take into account the larger segwit tx header for every
transaction, not just the segwit ones. The reason for this is that
we prefer to overestimate the fees for the transaction than
underestimating them - the former might create txs with a slightly
higher feerate than the requested one, while the latter might
create txs with a slightly lower one - or worse, invalid (<1 sat/vbyte)!
2022-08-02 12:08:53 +02:00
Daniela Brozzoni
7ac87b8f99
TXIN_BASE_WEIGHT shouldn't include the script len
We would before calculate the TXIN_BASE_WEIGHT as prev_txid (32 bytes) +
prev_vout (4 bytes) + sequence (4 bytes) + script_sig_len (1 bytes), but
that's wrong: the script_sig_len shouldn't be included, as miniscript
already includes it in the `max_satisfaction_size` calculation.
Fixes #160
2022-08-02 12:08:52 +02:00
Daniela Brozzoni
ac051d7ae9
Calculate fee amount after output addition
We would previously calculate the fee amount in two steps:
1. Add the weight of the empty transaction
2. Add the weight of each output

That's unnecessary: you can just use the weight of the transaction
*after* the output addition. This is clearer, but also avoids a
rare bug: if there are many outputs, adding them would cause the
"number of outputs" transaction parameter lenght to increase, and we
wouldn't notice it.
This might still happen when adding the drain output - this
commit also adds a comment as a reminder.
2022-08-02 12:08:51 +02:00
Daniela Brozzoni
00d426b885
test: Check that the feerate is never below...
...the requested one in assert_fee_rate
2022-08-02 12:08:26 +02:00
Daniela Brozzoni
42fde6d457
test: Check fee_amount in assert_fee_rate 2022-08-02 12:08:12 +02:00
Alekos Filini
8e0d00a3ea
Merge bitcoindevkit/bdk#694: Add assertions in the FeeRate constructor
235011feef8a6faadc08b814e199e5d5ced2f3a0 Add assertions in the FeeRate constructor (Alekos Filini)

Pull request description:

  ### Description

  Disallow negative, NaN, infinite or subnormal fee rate values.

  ### Notes to the reviewers

  This commit is technically an API break because it makes the `FeeRate::from_sat_per_vb` function non-const. I think it's worth it compared to the risk of having completely nonsensical fee rates (that can break the coin selection in interesting ways).

  EDIT: it's also a breaking change because our code can now panic in scenarios where it didn't before. Again, I think it's worth it.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    re-ACK 235011feef8a6faadc08b814e199e5d5ced2f3a0

Tree-SHA512: c9432956162fadfd255edf20b825635a487adb29c88d791e18f170da79a2aac6f8e745b5e5be09be3c211697d0b1f4bddc1da75c181e8f9fc4fddf566a7a3e5c
2022-08-02 11:26:36 +02:00
Alekos Filini
235011feef
Add assertions in the FeeRate constructor
Disallow negative, NaN, infinite or subnormal fee rate values.
2022-08-02 11:02:11 +02:00
Daniela Brozzoni
a1477405d1
Merge bitcoindevkit/bdk#675: Use T: AsRef<Path> as param to SqliteDatabase::new
558e37afa72b69228fc40cc20be9122b3ea00597 Use T: AsRef<Path> as param to SqliteDatabase::new (Vladimir Fomene)

Pull request description:

  This PR fixes #674

  ### Description

  Currently SqliteDatabase::new takes a String as path,
  with this change, it now accepts any type that implements
  AsRef<Path>.

  ### Notes to the reviewers

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    utACK 558e37afa72b69228fc40cc20be9122b3ea00597

Tree-SHA512: c5ff5b60e5904a5b7ef492a1e40296864b6b7506e4c6a187cfab05ef8140d14ddd322d016b4eeb18c5cfca8d4b575370b4f13c6ea7d7374ab0372a3237a5ed94
2022-07-30 09:30:20 +02:00
Vladimir Fomene
558e37afa7
Use T: AsRef<Path> as param to SqliteDatabase::new
Currently SqliteDatabase::new takes a String as path,
with this change, it now accepts any type that implements
AsRef<Path>.
2022-07-29 17:39:12 +03:00
Alekos Filini
6bae52e6f2
Merge bitcoindevkit/bdk#630: Move change logic to coin_select
32ae95f463f62c42c6d6aec62c1832a30298fce4 Move change calculus to coin_select (Cesar Alvarez Vallero)

Pull request description:

  ### Description

  The former way to compute and create change was inside `create_tx`, just after
  performing coin selection.
  It blocked the opportunity to have an "ensemble" algorithm to decide between
  multiple coin selection algorithms based on a metric, like Waste.
  Now, change is not created inside `coin_select` but the change amount and the
  possibility to create change is decided inside the `coin_select` method. In
  this way, change is associated with the coin selection algorithm that generated
  it, and a method to decide between them can be implemented.

  Fixes #147.
  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  afilini:
    ACK 32ae95f463f62c42c6d6aec62c1832a30298fce4

Tree-SHA512: 350adb86538949ff50f41151fc46c8d28d9f5fd659e9869882cc3cb30128d76d4b479512c74c721f8beebfdb5423363ad63368e30556efe65ced2b8c52c34ef6
2022-07-26 11:51:10 +02:00
Cesar Alvarez Vallero
32ae95f463
Move change calculus to coin_select
The former way to compute and create change was inside `create_tx`, just after
performing coin selection.
It blocked the opportunity to have an "ensemble" algorithm to decide between
multiple coin selection algorithms based on a metric, like Waste.

Now, change isn't created inside `coin_select` but the change amount and the
possibility to create change is decided inside the `coin_select` method. In
this way, change is associated with the coin selection algorithm that generated
it, and a method to decide between them can be implemented.
2022-07-23 15:40:59 -03:00
Alekos Filini
3644a452c1
Merge bitcoindevkit/bdk#672: Fix wallet sync not finding coins of addresses which are not cached
5c940c33cb1f1a166c6e28e8bbfd9cdaef6c1ab6 Fix wallet sync not finding coins of addresses which are not cached (志宇)

Pull request description:

  Fixes #521
  Fixes #451

  ^ However, only for electrum-based `Blockchain` implementations. For RPC and Compact Block Filters, syncing works differently, and so are the bugs - I have created a separate ticket for this (#677).

  ### Description

  Previously, electrum-based blockchain implementations only synced for `scriptPubKey`s that are already cached in `Database`.

  This PR introduces a feedback mechanism, that uses `stop_gap` and the difference between "current index" and "last active index" to determine whether we need to cache more `scriptPubKeys`.

  The `WalletSync::wallet_setup` trait now may return an `Error::MissingCachedScripts` error which contains the number of extra `scriptPubKey`s to cache, in order to satisfy `stop_gap` for the next call.

  `Wallet::sync` now calls `WalletSync` in a loop, caching in-between subsequent calls (if needed).

  #### Notes to reviewers

  1. The caveat to this solution is that it is not the most efficient. Every call to `WalletSync::wallet_setup` starts polling the Electrum-based server for `scriptPubKey`s starting from index 0.

      However, I feel like this solution is the least "destructive" to the API of `Blockchain`. Also, once the `bdk_core` sync logic is integration, we can select specific ranges of `scriptPubKey`s to sync.

  2. Also note that this PR only fixes the issue for electrum-based `Blockchain` implementations (currently `blockchain::electrum` and `blockchain::esplora` only).

  3. Another thing to note is that, although `Database` assumes 1-2 keychains, the current `WalletSync` "feedback" only returns one number (which is interpreted as the larger "missing count" of the two keychains). This is done for simplicity, and because we are planning to only have one keychain per database in the future.

      f0c876e7bf/src/blockchain/mod.rs (L157-L161)

  4. Please have a read of https://github.com/bitcoindevkit/bdk/pull/672#issuecomment-1186929465 for additional context.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 5c940c33cb1f1a166c6e28e8bbfd9cdaef6c1ab6

Tree-SHA512: aee917ed4821438fc0675241432a7994603a09a77d5a72e96bad863e7cdd55a9bc6fbd931ce096fef1153905cf1b786e1d8d932dc19032d549480bcda7c75d1b
2022-07-21 18:05:57 +02:00
志宇
5c940c33cb
Fix wallet sync not finding coins of addresses which are not cached
Previously, electrum-based blockchain implementations only synced for
`scriptPubKey`s that are already cached in `Database`.

This PR introduces a feedback mechanism, that uses `stop_gap` and the
difference between "current index" and "last active index" to determine
whether we need to cache more `scriptPubKeys`.

The `WalletSync::wallet_setup` trait now may return an
`Error::MissingCachedScripts` error which contains the number of extra
`scriptPubKey`s to cache, in order to satisfy `stop_gap` for the next call.

`Wallet::sync` now calls `WalletSync` in a loop, cacheing inbetween
subsequent calls (if needed).
2022-07-20 23:08:12 +08:00
Daniela Brozzoni
277e18f5cb
Merge bitcoindevkit/bdk#661: Test: No address reuse for single descriptor
2c02a44586c67d1ec9720f17a3748f28c1d18643 Test: No address reuse for single descriptor (志宇)

Pull request description:

  ### Description

  Just a simple new test.

  This test is to ensure there are no regressions when we later change
  internal logic of `Wallet`. A single descriptor wallet should always get
  a new address with `AddressIndex::New` even if we alternate grabbing
  internal/external keychains.

  I thought of adding this during work on #647

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    tACK 2c02a44586c67d1ec9720f17a3748f28c1d18643
  rajarshimaitra:
    tACK 2c02a44586c67d1ec9720f17a3748f28c1d18643

Tree-SHA512: d065ae0979dc3ef7c26d6dfc19c88498e4bf17cc908e4f5677dcbf62ee59162e666cb00eb87b96d4c2557310960e3677eec7b6d907a5a4860cb7d2d74dba07b0
2022-07-20 14:14:05 +02:00
Daniela Brozzoni
8d3b2a9581
Merge bitcoindevkit/bdk#659: Fix: Run README.md examples on the CI
9d2024434eb0d542133d06db14020968e713fd9b Fix: Run README.md example on the CI (meryacine)

Pull request description:

  ### Description
  Seems like `doc(include = "../README.md")` doesn't include the readme file as doc for the dummy struct. This might be due to a difference in Rust edition used back then or something.

  Fixes #637
  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    tACK 9d2024434eb0d542133d06db14020968e713fd9b

Tree-SHA512: 5842f7cdc34d76045596a248ec80bbcf86591ec9abe32d92af8322672e7a5d08d3b4baf1a000b1556542b449271dc8c438e6269eaf0204bee815c67fcf1218a8
2022-07-20 11:53:33 +02:00
Alekos Filini
45a4ae5828
Merge bitcoindevkit/bdk#671: Introduce get_checksum_bytes method and improvements
6db5b4a094263a07eeb82ba92b47754d25a8d0d3 Introduce `get_checksum_bytes` method and improvements (志宇)

Pull request description:

  ### Description

  `get_checksum_bytes()` returns a descriptor checksum as `[u8; 8]` instead of `String`, potentially improving performance and memory usage.

  In addition to this, since descriptors only use characters that fit within a UTF-8 8-bit code unit ([US-ASCII](https://www.charset.org/charsets/us-ascii)), there is no need to use the `char` type (which is 4 bytes). This can also potentially bring in some performance and memory-usage benefits.

  ### Notes to the reviewers

  This is useful because we will be using descriptor checksums for indexing operations in the near future (multi-descriptor wallets #486 ).

  Refer to comments by @afilini :
  * https://github.com/bitcoindevkit/bdk/pull/647#discussion_r921184366
  * https://github.com/bitcoindevkit/bdk/pull/647#discussion_r921914696
  * https://github.com/bitcoindevkit/bdk/pull/654#discussion_r921980876

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  afilini:
    ACK 6db5b4a094263a07eeb82ba92b47754d25a8d0d3

Tree-SHA512: 1cecc3a1514a3ec3ac0a50775f6b3c4dd9785e3606390ceba57cc6248b8ff19c4023add0643c48dd9d84984341c506c036c4880fca4a4358ce1b54ccb4c56687
2022-07-20 09:13:21 +02:00
志宇
6db5b4a094
Introduce get_checksum_bytes method and improvements
`get_checksum_bytes` returns a descriptor checksum as `[u8; 8]` instead
of `String`, potentially improving performance and memory usage.

In addition to this, since descriptors only use charaters that fit
within a UTF-8 8-bit code unit, there is no need to use the `char` type
(which is 4 bytes). This can also potentially bring in some performance
and memory-usage benefits.
2022-07-19 22:02:49 +08:00
meryacine
9d2024434e
Fix: Run README.md example on the CI
Seems like `doc(include = "../README.md")` doesn't include the readme file as docs for the dummy struct. This might be due to a difference in Rust edition used back then or something
2022-07-17 18:33:56 +02:00
Alekos Filini
9165faef95
Merge bitcoindevkit/bdk#657: Release 0.20.0
46c344feb02e2ecfdc065d85cba320d06811bedf Bump version to 0.20.1-dev (Steve Myers)
78d26f6eb3dcccd791a858cfc6c8303b409e9a6e Bump version to 0.20.0 (Steve Myers)
92b9597f8b8dc3694508062b5e7c5f23acbc3a4f Rename `set_current_height` to `current_height` (Alekos Filini)
b5a120c649a17302f3825c45efd9ea0c3b2dd266 Missing newlines (Alekos Filini)
af6bde3997ac2fe4cfdbb691f2af2e802f0ab7c6 Fix: Wallet sync may decrement address index (志宇)
45db468c9be0c8bb2dc5fac52fbd52b6b41b4d53 Deprecate `AddressValidator` (志宇)
01141bed5ab1f73feade4058d9488c7a12f025a8 Update CHANGELOG and lib.rs docs version (Steve Myers)
87e864674367172022feaa6d3cf5e746caa3124c Bump version to 0.20.0-rc.1 (Steve Myers)

Pull request description:

  Proposed tweet:

  📢 Release 0.20.0 is out! Highlights include bug fixes for the ElectrumBlockchain and descriptor templates, discourage fee sniping in tx building, and new tx signing options. A big thanks to our past and latest new contributors. For all changes see: https://github.com/bitcoindevkit/bdk/releases/tag/v0.20.0

ACKs for top commit:
  afilini:
    ACK 46c344feb02e2ecfdc065d85cba320d06811bedf

Tree-SHA512: 7c36a85611f715d76a37d5a285bc72f1a06297fc06b85cca7e38c3350fcbc0a3e35d38ce617a82d191538776aa49362e523beef70bbe3b93b21d8d28d774b75f
2022-07-14 12:05:13 +02:00
Steve Myers
46c344feb0
Bump version to 0.20.1-dev 2022-07-13 11:41:57 -07:00
Steve Myers
78d26f6eb3
Bump version to 0.20.0 2022-07-13 10:55:57 -07:00
Alekos Filini
844856d39e
Merge bitcoindevkit/bdk#667: Rename set_current_height to current_height
92b9597f8b8dc3694508062b5e7c5f23acbc3a4f Rename `set_current_height` to `current_height` (Alekos Filini)

Pull request description:

  ### Description

  Usually we don't have any prefix except for methods that can *add* to a list or replace the list entirely (e.g. `add_recipients` vs `set_recipients`)

  I missed this during review of #611

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    utACK 92b9597f8b8dc3694508062b5e7c5f23acbc3a4f - I'm sorry I didn't notice it!

Tree-SHA512: 3391068b2761bcd04d740ef41f9e772039fca7bc0e0736afcbc582ec74b6c91eb155d9e09dd7a07462eec29e32ac86e41ba339d9a550af3f754164cab6bdbf61
2022-07-13 14:43:26 +02:00
Alekos Filini
b5a120c649
Missing newlines 2022-07-13 11:13:05 +02:00
Alekos Filini
92b9597f8b
Rename set_current_height to current_height
Usually we don't have any prefix except for methods that can *add* to a
list or replace the list entirely (e.g. `add_recipients` vs
`set_recipients`)
2022-07-13 10:27:38 +02:00
Alekos Filini
556105780b
Merge bitcoindevkit/bdk#653: Fix: Wallet sync may decrement address index
af6bde3997ac2fe4cfdbb691f2af2e802f0ab7c6 Fix: Wallet sync may decrement address index (志宇)

Pull request description:

  ### Description

  Fixes #649

  It is critical to ensure `Wallet::get_address` with `AddressIndex::new` always returns a new and unused address.

  This bug seems to be Electrum-specific. The fix is to check address index updates to  ensure that newly suggested indexes are not smaller than indexes already in database.

  ### Notes to the reviewers

  I have written new tests in `/testutils/blockchain_tests.rs` that tests all `Blockchain` implementations.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  ~* [ ] This pull request breaks the existing API~
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK af6bde3997ac2fe4cfdbb691f2af2e802f0ab7c6

Tree-SHA512: d714bebcf7c2836f8b98129b39b4939b0e36726acf0208e52d501f433be6cdb12f1abebc28bd7da0be8b780ccce6e1e42c8fdc6633dd486bf329bc6f88e1ce67
2022-07-11 16:58:35 +02:00
志宇
af6bde3997
Fix: Wallet sync may decrement address index
This bug seems to be Electrum-specific. The fix is to check the
proposed changes against the current state of the database. Ensure
newly suggested indexes are not smaller than indexes already in
database.

Changes:
* Check index updates before they are applied to database during
  Electrum Blockchain sync (Thank you @rajarshimaitra for providing
  an elegant solution).

Tests added:
* bdk_blockchain_tests!::test_sync_address_index_should_not_decrement
* bdk_blockchain_tests!::test_sync_address_index_should_increment

These tests ensure there will be no unexpected address reuse when
grabbing a new address via `Wallet::get_address` with `AddressIndex::New`.

Other changes:
* Tweak `rpc.rs` so that clippy is happy.
2022-07-11 17:52:36 +08:00
Alekos Filini
4bd1fd2441
Merge bitcoindevkit/bdk#664: Deprecate AddressValidator
45db468c9be0c8bb2dc5fac52fbd52b6b41b4d53 Deprecate `AddressValidator` (志宇)

Pull request description:

  ### Description

  `AddressValidator` should be deprecated as noted by @afilini [on Discord](https://discord.com/channels/753336465005608961/753367451319926827/994899488957272064):

  > address validators are supposed to be used for a slightly different thing, which is when you ask the hardware wallet to independently generate the address for a derivation index and then you compare what you see on your computer/phone with what the hardware wallet is displaying
  > in the case of change addresses i agree that it's not as important (because as you said the device can just refuse to sign) but for consistency we implemented it for both external and internal addresses
  > more broadly, they can be thought of as a way to get a callback every time an address is generated, which may also be useful for other things (for example when i was working on a green-compatible client written in bdk i used that feature to ping the server every time a new address was generated, because that's required in their protocol)
  > that said, i think currently pretty much nobody uses them and i am myself moving away from the concept that "everything needs to happen inside bdk": currently my mindset is targeted more towards reducing complexity by breaking down individual parts and wrapping them or making them "extensible" in some way
  > that is to say: if you want to verify addresses in your hardware wallet you don't necessarily need bdk to do it for you (actually, you would still have to implement the callback manually), you can just call bdk to get a new addr and then ping the device yourself. and this would allow us to reduce complexity and delete some code
  > actually, here's an idea: unless somebody here is opposed to this, i can make a pr to deprecate address validators in the next (0.20) release. if after that again nobody complains we can completely remove them and point users towards different strategies to achieve the same goal

  ### Checklists

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  afilini:
    ACK 45db468c9be0c8bb2dc5fac52fbd52b6b41b4d53

Tree-SHA512: 71071f4494537ece9153f5308cb4f576189016afa8ac87bc57bfdcda03ee94d5f7a3477d04f6dd37eeeea2fada6aaad42ad29c964df0971beeda7418ada65f6d
2022-07-11 11:49:17 +02:00
志宇
45db468c9b
Deprecate AddressValidator 2022-07-11 17:31:59 +08:00
志宇
2c02a44586
Test: No address reuse for single descriptor
This test is to ensure there are no regressions when we later change
internal logic of `Wallet`. A single descriptor wallet should always get
a new address with `AddressIndex::New` even if we alternate grabbing
internal/external keychains.
2022-07-09 20:29:58 +08:00
Steve Myers
01141bed5a
Update CHANGELOG and lib.rs docs version 2022-07-06 13:23:50 -07:00
Steve Myers
87e8646743
Bump version to 0.20.0-rc.1 2022-07-06 12:52:00 -07:00
Steve Myers
dd51380520
Merge bitcoindevkit/bdk#621: Add remove_partial_sigs and try_finalize to SignOptions
e3a17f67d90f11d1d1a27a98ec97674c8cd3d2f7 add try_finalize to SignOptions (KaFai Choi)
c2e4ba8cbd77f1a41d269b621b0001d042c1ea57 add remove_partial_sigs to SignOptions (KaFai Choi)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  This PR is to add 2 keys(`try_finalize` and `remove_partial_sigs`) in `SignOptions`. See this issue for detail https://github.com/bitcoindevkit/bdk/issues/612

  ### Notes to the reviewers

  ~I found the negative naming of these 2 new keys `do_not_finalize` and `do_not_remove_partial_sigs` are a bit confusing(like most negative named paremeter/variable). Should we actually change it back to positive naming(`do_finalize` and `do_remove_partial_sigs`)?~

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ReACK e3a17f67d90f11d1d1a27a98ec97674c8cd3d2f7

Tree-SHA512: 781b31d3ecf0bcd605206c0481fd5de3125f1c8ff18a463dbf4c821e5557847f7d70a3fe8618e100fb89f4f6899655ac0efa3593f77f915ad5bcb7e558bb2a7a
2022-07-06 10:46:30 -07:00
Steve Myers
73d4f6d3b1
Merge bitcoindevkit/bdk#634: Get block hash by its height
2af678aa846a82657d13bcda2ac0b4a9db4e2b80 Get block hash by its height (Vladimir Fomene)

Pull request description:

  ### Description
  This PR create a new trait `blockchain::GetBlockHash` with a `get_block_hash` method which returns a block hash given the block height. This has been implemented for all blockchain backends.
  Fixes #603

  ### Notes to the reviewers

  I haven't updated the `CHANGELOG.md` and docs. Am I suppose to update it for this change?

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

ACKs for top commit:
  notmandatory:
    ACK 2af678aa846a82657d13bcda2ac0b4a9db4e2b80

Tree-SHA512: 9c084a6665ecbf27ee8170fdb06e0dc8373d6a901ce29e5f5a1bec111d1507cb3bee6b03a653a55fd20e0fabe7a5eada3353e24a1e21f3a11f01bb9881ae99e5
2022-07-06 10:17:50 -07:00
Vladimir Fomene
2af678aa84
Get block hash by its height
Create blockchain::GetBlockHash trait
with a method to get block hash given
a block height. Then, implement this
trait for all backends (Electrum, RPC
, Esplora, CBF). Referenced in issue 603.
2022-07-06 18:03:20 +01:00
Alekos Filini
1c94108d7e
Merge bitcoindevkit/bdk#648: test: BDK won't add unconf inputs when fee bumping
5d00f8238886a993ef21056e5b3e216a4aae6951 test that BDK won't add unconf inputs when fee bumping (Daniela Brozzoni)
98748906f6799041341227de33bec20e8c6ef4b0 test: fix populate_test_db conf calculation (Daniela Brozzoni)
1d9fdd01faf3a0f17c57381a7c54d136e9d69ffe Remove wrong TODO comment in build_fee_bump (Daniela Brozzoni)

Pull request description:

  ### Description

  Closes #144

  ### Notes to reviewers

  #144 is describing a bug that doesn't seem to happen in BDK master anymore (BDK not respecting BIP125 rule 2). This PR just adds a test to check that the bug is fixed.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 5d00f8238886a993ef21056e5b3e216a4aae6951

Tree-SHA512: 95833f3566f9716762884d65f3f656346482e45525a3e92efa86710b9f574fdd9af7d235f1f425e4298d6ff380db9af60d1d2008ccde2588d971757db2d136b8
2022-07-06 16:43:47 +02:00
Daniela Brozzoni
5d00f82388
test that BDK won't add unconf inputs when fee bumping
Fixes #144

Also removes a leftover dbg!() in a test
2022-07-06 12:48:19 +02:00
Daniela Brozzoni
98748906f6
test: fix populate_test_db conf calculation
populate_test_db would previously give back a transaction with N + 1
confirmations when you asked for N.

This commit also fixes test_spend_coinbase, which would improperly
ask for a transaction with 0 confirmations instead of 1.
2022-07-06 12:48:18 +02:00
Alekos Filini
dd832cb57a
Merge bitcoindevkit/bdk#585: set coin type based on network
db9d43ed2f4146dbfdc28a72d0c9ae420f831fc3 use network to set coin type (Esraa Jbara)

Pull request description:

  resolves #578

  * [x] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    re-ACK db9d43ed2f4146dbfdc28a72d0c9ae420f831fc3
  afilini:
    re-ACK db9d43ed2f4146dbfdc28a72d0c9ae420f831fc3

Tree-SHA512: 0310a09ef21c6fc792688a9ccc19221b1cffaeceefd34f4c83f206e965abe963a78f9e4ca53db046b39e7bf1be118a101afe5c08c43f06ecf35ed9536102cd9b
2022-07-06 12:24:16 +02:00
KaFai Choi
e3a17f67d9
add try_finalize to SignOptions 2022-07-06 17:13:19 +07:00
KaFai Choi
c2e4ba8cbd
add remove_partial_sigs to SignOptions 2022-07-06 17:10:36 +07:00
Daniela Brozzoni
1d9fdd01fa
Remove wrong TODO comment in build_fee_bump
The proposed solution is bad for privacy as well.
Let's call the initial change output, which is normally shrink when you
fee bump, change#1, and the extra output aforementioned change#2 (as,
in this case, it's going to be a change output as well). If you add change#2
you might not revel change#1, but you're still revealing change#2.
You're not improving your privacy, and you're wasting money in fees.
2022-07-06 11:02:51 +02:00
Esraa Jbara
db9d43ed2f
use network to set coin type
Signed-off-by: Esraa Jbara <jbesraa@gmail.com>
2022-07-06 09:08:24 +03:00
Alekos Filini
ec22fa2ad0
Merge bitcoindevkit/bdk#614: Avoid using immature coinbase inputs
e85aa247cb85601e96f4d82b7a996f709559223f Avoid using immature coinbase inputs (Daniela Brozzoni)
0e0d5a0e957fbf602023011d9114d8bcb8effb67 populate_test_db accepts a `coinbase` param (Daniela Brozzoni)

Pull request description:

  ### Description

  With this PR we start considering how many confirmations a coinbase has. If it's not mature yet, we don't use it for building transactions.
  Fixes #413

  ### Notes to the reviewers

  This PR is based on #611, review that one before reviewing this 😄

  007c5a78335a3e9f6c9c28a077793c2ba34bbb4e adds a coinbase parameter to `populate_test_db`, to specify if you want the db to be populated with immature coins. This is useful for `test_spend_coinbase`, but that's probably going to be the only use case.
  I don't think it's a big deal to have a test function take an almost_always_useless parameter - it's not an exposed API, anyways. But, if you can come up with a different way of implementing `test_spend_coinbase` that doesn't require 007c5a78335a3e9f6c9c28a077793c2ba34bbb4e, even better! I looked for it for a while, but other than duplicating the whole `populate_test_db` code, which made the test way harder to comprehend, I didn't find any other way.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK e85aa24

Tree-SHA512: 30f470c33f9ffe928500a58f821f8ce445c653766459465eb005031ac523c6f143856fc9ca68a8e1f23a485c6543a9565bd889f9557c92bf5322e81291212a5f
2022-07-05 22:26:03 +02:00
Alekos Filini
0e92820af4
Merge bitcoindevkit/bdk#652: Fix: Hang when ElectrumBlockchainConfig::stop_gap == 0
612da165f8cfbc2b0aee0a37b2cdc44d6da017c8 `Blockchain` stop_gap testing improvements (志宇)
8a5f89e129d421a41af02ea85383d5b82f5ff665 Fix hang when `ElectrumBlockchainConfig::stop_gap == 0` (志宇)

Pull request description:

  * Ensure `chunk_size` is > 0 during wallet sync.

  * Slight refactoring for better readability.

  * Add test: `test_electrum_blockchain_factory_sync_with_stop_gaps`

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  `Wallet::sync` hangs indefinitely when syncing with Electrum with `stop_gap` set as 0.

  The culprit is having `chunk_size` set as `stop_gap`. A zero value results in syncing not being able to progress.

  Fixes #651

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  ~* [ ] This pull request breaks the existing API~
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 612da165f8cfbc2b0aee0a37b2cdc44d6da017c8

Tree-SHA512: 56f1bff788855facc21856209922594cff9f639c5c58ecd180a0493322a75a564b72ded330ab0b6d6c90007ce859d2b8a5d2870d619bae5ddf9a3d64837f3753
2022-07-05 12:30:30 +02:00
Daniela Brozzoni
e85aa247cb
Avoid using immature coinbase inputs
Fixes #413
2022-07-05 12:11:48 +02:00
志宇
612da165f8
Blockchain stop_gap testing improvements
This is a continuation of the #651 fix. We should also check whether the
same bug affects esplora as noted by @afilini. To achieve this, I've
introduced a `ConfigurableBlockchainTester` trait that can test multiple
blockchain implementations.

* Introduce `ConfigurableBlockchainTester` trait.
* Use the aforementioned trait to also test esplora.
* Change the electrum test to also use the new trait.
* Fix some complaints by clippy in ureq.rs file (why is CI not seeing
  this?).
* Refactor some code.
2022-07-05 07:53:19 +08:00
Steve Myers
1fd62a7afc
Merge bitcoindevkit/bdk#575: Remove database flush
5ff8320e3b1cb4e3971549a3e3c168f20762d04b add private function ivcec_to_u32 in keyvalue (KaFai Choi)
e68d3b9e63914c1008e1a4bb20a847428659d52e remove Database::flush (KaFai Choi)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  This PR is to remove Database::flush. See this issue for detail https://github.com/bitcoindevkit/bdk/issues/567

  ### Notes to the reviewers
  The 2nd commit is a small refactoring of adding a new private ivec_to_u32 to avoid too much code duplication. Please let me know if it's ok to include this in this PR or I should make it into a separate PR

  Currently existing test cases are shared across for all Databaes implementation so I am not sure if we should add  specific test cases for keyvalue(Tree) for this auto-flush behaviour?(and I feel like it's more a implementation detail). Please let me know how should I proceed for test case in this PR

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    re-ACK 5ff8320e3b1cb4e3971549a3e3c168f20762d04b

Tree-SHA512: eb37de8217efeb89d3ae346da36d0fb55aa67554d591b4759500f793bcf6aa7601c3d717fd473136c88e76aa72dbb6008ecf62b1d4ccf5ba3cbd1598f758522a
2022-07-04 13:40:56 -07:00
志宇
8a5f89e129
Fix hang when ElectrumBlockchainConfig::stop_gap == 0
* Ensure chunk_size is > 0 during wallet sync.
* Slight refactoring for better readability.
* Add test: test_electrum_blockchain_factory_sync_with_stop_gaps
2022-07-04 21:53:26 +08:00
Alekos Filini
063d51fd75
Merge bitcoindevkit/bdk#625: Restrict drain_to usage
6a150368674046f796f5c37755896f16d8345fbc Restrict `drain_to` usage (Daniela Brozzoni)

Pull request description:

  ### Description
  Before this commit, you could create a transaction with `drain_to` set
  without specifying recipients, nor `drain_wallet`, nor `utxos`. What would
  happen is that BDK would pick one input from the wallet and send
  that one to `drain_to`, which is quite weird.
  This PR restricts the usage of `drain_to`: if you want to use it as a
  change output, you need to set recipients as well. If you want to send
  a specific utxo to the `drain_to` address, you specify it through
  `add_utxos`. If you want to drain the whole wallet, you set
  `drain_wallet`. In any other case, if `drain_to` is set, we return a
  `NoRecipients` error.

  Fixes #620

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] This pull request breaks the existing API - kinda?
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 6a150368674046f796f5c37755896f16d8345fbc

Tree-SHA512: 69076977df37fcaac92dd99d2f2c9c37098971817d5b0629fc7e3069390eb5789331199b3b7c5d0569d70473f4f37e683a5a0b30e2c6b4e2ec22a5ef1d0f2d77
2022-06-30 12:28:45 +02:00
Daniela Brozzoni
0e0d5a0e95
populate_test_db accepts a coinbase param
Allows user to ask for a test db populated with clean coins
from coinbases. This is useful for testing the wallet behaviour
when some inputs are coinbases.
2022-06-30 11:50:15 +02:00
Alekos Filini
bb55923a7d
Merge bitcoindevkit/bdk#611: Discourage fee sniping with nLockTime
97bc9dc7170c336e97cd756b1f07ac3c23a39626 Discourage fee sniping with nLockTime (Daniela Brozzoni)

Pull request description:

  ### Description
  By default bdk sets the transaction's nLockTime to current_height
  to prevent fee sniping.
  current_height can be provided by the user through TxParams; if the user
  didn't provide it, we use the last sync height, or 0 if we never synced.

  Fixes https://github.com/bitcoindevkit/bdk/issues/533

  ### Notes to the reviewers:

  If you want to know more about fee sniping: https://bitcoinops.org/en/topics/fee-sniping/

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  afilini:
    ACK 97bc9dc7170c336e97cd756b1f07ac3c23a39626

Tree-SHA512: e92d1ae907687d9fee44d120d790f1ebdf14b698194979e1be8433310fd5636afa63808effed12fce6091f968ec6b76b727cfee6fed54068af0a7450239fdd26
2022-06-29 15:58:07 +02:00
Alekos Filini
f184557fa0
Merge bitcoindevkit/bdk#633: Additional comments for TransactionDetails.
77c7d0aae944dbd5a44ca9b8f239db0c9edcd4f8 Additional comments for `TransactionDetails`. (志宇)

Pull request description:

  ### Description

  I'm not sure if this is needed or helpful, but this PR adds comments to describe how the `sent` and `received` fields of `TransactionDetails` are calculated.

  I wasn't sure how it was done until I looked deeper into the codebase (but maybe I am too much of a beginner and this is common sense for most).

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  danielabrozzoni:
    re-ACK 77c7d0aae944dbd5a44ca9b8f239db0c9edcd4f8

Tree-SHA512: 8d29d249a70bc2d0631078b6772c5543bdc61ee43df3810ab666f5e97ca59b0d4cfc8acad14bbaf8674baba319f24fa2781a42740ca42bccd9688831aaedea72
2022-06-29 15:52:57 +02:00
志宇
77c7d0aae9
Additional comments for TransactionDetails.
Describe how fields `received` and `sent` are calculated for
`TransactionDetails`.
2022-06-29 19:38:12 +08:00
KaFai Choi
5ff8320e3b
add private function ivcec_to_u32 in keyvalue 2022-06-29 12:39:51 +07:00
KaFai Choi
e68d3b9e63
remove Database::flush 2022-06-29 12:39:49 +07:00
Daniela Brozzoni
97bc9dc717
Discourage fee sniping with nLockTime
By default bdk sets the transaction's nLockTime to current_height
to discourage fee sniping.
current_height can be provided by the user through TxParams; if the user
didn't provide it, we use the last sync height, or 0 if we never synced.

Fixes #533
2022-06-28 10:35:03 +02:00
Daniela Brozzoni
6a15036867
Restrict drain_to usage
Before this commit, you could create a transaction with `drain_to` set
without specifying recipients, nor `drain_wallet`, nor `utxos`. What would
happen is that BDK would pick one input from the wallet and send
that one to `drain_to`, which is quite weird.
This PR restricts the usage of `drain_to`: if you want to use it as a
change output, you need to set recipients as well. If you want to send
a specific utxo to the `drain_to` address, you specify it through
`add_utxos`. If you want to drain the whole wallet, you set
`drain_wallet`. In any other case, if `drain_to` is set, we return a
`NoRecipients` error.

Fixes #620
2022-06-28 10:32:48 +02:00
Alekos Filini
17d0ae0f71
Merge bitcoindevkit/bdk#643: Fix README.md link to rust 1.56.1 blog post
d020dede3785f351c0a58a0787c20c396437ff87 Fix README.md link to rust 1.56.1 blog post (Steve Myers)

Pull request description:

  ### Description

  Fix link to rust blog for 1.56.1 as pointed out by ulrichard: https://github.com/weareseba/bdk-reserves/pull/5#issuecomment-1159212838

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits

Top commit has no ACKs.

Tree-SHA512: a5bd76fca97dd64c12617b43230dbc36b1178e47224ce324b67cd13999e5f92d2a05d6a9e909841e6d5c6904f2fa426b6bee1001e757d53cc91fb4fd3803f56b
2022-06-28 08:43:17 +02:00
Steve Myers
d020dede37
Fix README.md link to rust 1.56.1 blog post 2022-06-27 22:04:54 -07:00
Alekos Filini
5c566bb05e
Merge bitcoindevkit/bdk#638: Fix CI, bump MSRV to 1.56.1
b289c4ec2d4e19cd231e65f6e71e2b7422a81be1 Bump MSRV from 1.56.0 to 1.56.1 (Daniela Brozzoni)

Pull request description:

  ### Description
  This PR fixes the CI, which is currently failing after a Github Actions update.
  The MSRV is bumped to 1.56.1 (from 1.56.0), since that's `reqwest`'s current MSRV.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  afilini:
    ACK b289c4ec2d4e19cd231e65f6e71e2b7422a81be1

Tree-SHA512: e3aa8638ffd374371037e71d1c9790dd4fb3aa29f0ade5655b47ef5184b26120ee5281cd1745612af2572beb8a6bb43f84da3d60a73b455f9652853fcf31b62d
2022-06-27 23:25:33 +02:00
Daniela Brozzoni
b289c4ec2d
Bump MSRV from 1.56.0 to 1.56.1
In this way we can continue using reqwest v0.11, whose MSRV is now
1.56.1
The only difference between v1.56.0 and v1.56.1 is a bug fix for
CVE-2021-42574.
2022-06-27 12:29:10 +02:00
Alekos Filini
2283444f72
Merge bitcoindevkit/bdk#622: fix typo
a85ef62698eae748242f31db80fa3aabd3b2b64e fix typo (Buck Perley)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->
  just a small typo fix

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  rajarshimaitra:
    ACK a85ef62698eae748242f31db80fa3aabd3b2b64e
  afilini:
    ACK a85ef62698eae748242f31db80fa3aabd3b2b64e

Tree-SHA512: 089de23adae62492a0b39a27c9cb8cb8afc99e5634194118681b8a9a46ff0b073558f9cd515cd4db4c9c6e6f9c813bfa4b193d4e3f9558b34ad29cbd46cf028c
2022-06-13 11:44:46 +02:00
Steve Myers
a0e5820c32
Merge commit 'refs/pull/629/head' of github.com:bitcoindevkit/bdk 2022-06-10 10:46:27 -07:00
Steve Myers
04dc28d2b4
Bump version to 0.19.1-dev 2022-06-10 10:13:43 -07:00
Steve Myers
fa4c73a4d1
Bump version to 0.19.0 2022-06-10 09:08:43 -07:00
Steve Myers
2bf8121b18
Update CHANGELOG.md to 0.19.0 2022-06-08 15:18:54 -07:00
Alekos Filini
688ff96c8e
Merge bitcoindevkit/bdk#623: Bump versions
3283a200bc5fef4bca38954abad669130125f70c Bump rusqlite (Philipp Hoenisch)
3f9b4cdca9dc05d3e8f63df7235287e192a1838a Bump ahash (Philipp Hoenisch)

Pull request description:

  ### Description

  Not much to say besides that I bumped some version which helps us to resolve some dependency hell :)

  ### Notes to the reviewers

  `ahash` was previously fixed because of an incompatibility with the defined MSRV. The MSRV has been bumped to 1.56 so we can update the dependency.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  rajarshimaitra:
    ACK 3283a200bc5fef4bca38954abad669130125f70c

Tree-SHA512: 4760890529bb4dd87fafdda04188fd06e707398abfa7d36d26077233525e76cc8c7d8888ad996c1cc4ac31ab708ea9a56a602b1d1578b97f9e44b610df3d969b
2022-06-08 12:59:27 +02:00
Steve Myers
ed3ef94071
Bump version to 0.19.0-rc.1 2022-06-07 13:13:23 -07:00
Steve Myers
ed78d18f60
Merge bitcoindevkit/bdk#628: rpc: use importdescriptors with Core >= 0.21
e1a1372baec86da784af697e025615b8e0bccf4e rpc: use `importdescriptors` with Core >= 0.21 (Alekos Filini)

Pull request description:

  ### Description

  Only use the old `importmulti` with Core versions that don't support descriptor-based (sqlite) wallets.

  Add an extra feature to test against Core 0.20 called `test-rpc-legacy`.

  This also makes us compatible with Core 23.0 and is thus a replacement for #613, which actually looking back at it was adding support for 23.0 but probably breaking older wallets by adding the extra argument to `createwallet`.

  I believe #613 should now only focus on getting the tests to work against 23.0, which is still important but not such a high priority as being compatible with the latest version of Core.

  Also fixes #598

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  notmandatory:
    ACK e1a1372baec86da784af697e025615b8e0bccf4e

Tree-SHA512: 7891b8ab2fc900ea2a186f64a32aea970f28a50339063ed0e1a8d13248e5c038b8fff3d9e26b93cb7daafd0c873379e64a28836dbe4e4b82f1983577a88971ff
2022-06-07 13:02:13 -07:00
Alekos Filini
e1a1372bae
rpc: use importdescriptors with Core >= 0.21
Only use the old `importmulti` with Core versions that don't support
descriptor-based (sqlite) wallets.

Add an extra feature to test against Core 0.20 called `test-rpc-legacy`
2022-06-07 15:07:58 +02:00
Philipp Hoenisch
3283a200bc
Bump rusqlite
Signed-off-by: Philipp Hoenisch <philipp@hoenisch.at>
2022-06-07 08:48:58 +10:00
Philipp Hoenisch
3f9b4cdca9
Bump ahash
We can upgrade this now as MSRV was bumped to 1.56

Signed-off-by: Philipp Hoenisch <philipp@hoenisch.at>
2022-06-07 08:48:49 +10:00
Buck Perley
a85ef62698
fix typo 2022-06-05 14:19:37 -05:00
Steve Myers
32699234b6
Merge bitcoindevkit/bdk#619: Fix index out of bound error
d9b9b3dc464d6a9cd4157cc4135a2e7b88ce4ab3 Fix InvalidColumnIndex error (Philipp Hoenisch)

Pull request description:

  This query returns 7 rows, so last row is index 6

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] I've added tests to reproduce the issue which are now passing

ACKs for top commit:
  danielabrozzoni:
    tACK d9b9b3dc464d6a9cd4157cc4135a2e7b88ce4ab3
  rajarshimaitra:
    tACK d9b9b3dc464d6a9cd4157cc4135a2e7b88ce4ab3

Tree-SHA512: 8a3d8a291daa4af86a2a2eacc31f002972dd9cdb9bf300a4b09e2e015c4a967dc4fa7e925afbcce8b104a01e1d7f7c8cb0badda8e1ac5ade511681f490c719d5
2022-06-05 10:13:49 -07:00
Alekos Filini
8fbe40a918
Merge bitcoindevkit/bdk#593: Add support for Taproot and tr() descriptors
20d36c71d470ea5ece98dd218f4dbdb0ba872d11 Update CHANGELOG.md for Taproot (Alekos Filini)
ef08fbd3c7f424cb77e231c2daaed2039b28b938 Update to the newest release of rust-bitcoin (Alekos Filini)
5320c8353e05adecf0d18336d48934567257e64d taproot-tests: validate `tap_tree` in psbt outputs (Alekos Filini)
c1bfaf9b1ebd92ac8952afd0d5867897672acfb4 Add blockchain tests for parsing, signing, finalizing taproot core psbts (Steve Myers)
0643f76c1fac5ee25f8a9de4c3a2cd57a3974b5e taproot-tests: Add tests for the policy module (Alekos Filini)
89cb425e69303fe62fe7332d8528011b7a98b4df taproot-tests: Add test coverage for tx signing (Alekos Filini)
461397e590471a8d10590b7d754e206310bceef5 taproot-tests: Test taproot key and script spend in the blockchain tests (Alekos Filini)
c67116fb55de525a9045527eefcb5cdb6f4d34a9 policy: Consider `tap_key_origins` when looking for sigs in PSBTs (Alekos Filini)
572c3ee70d6d335af0e2e541d2497f8bdcfb63c9 policy: Build `SatisfiableItem::*Signature` based on the context (Alekos Filini)
ff1abc63e03e5c24d375eb2c4f20302c9187d24d policy: Refactor `PkOrF` into an enum (Alekos Filini)
308708952b598f8f0f1f6cb5f3743e443485cb1e Fix type inference for the `tr()` descriptor, add basic tests (Alekos Filini)
fe1877fb185af7a235ceb1a9696d1edd66f957d8 Support `tr()` descriptors in dsl (Alekos Filini)
cdc7057813a4a2acba5224c966da2c3473efa669 Add `tr()` descriptors to the `descriptor!()` macro (Alekos Filini)
c121dd0252f392ac4bd5e787c9cb570dedcec478 Use `tap_key_origins` in PSBTs to derive descriptors (Alekos Filini)
855382113380612ca4f4c7da0a4a93c7a4f9aab9 Populate more taproot fields in PSBTs (Alekos Filini)
8a5a87b0752e0bdaa003ff7c3f1d153a447dbe85 Populate `tap_key_origin` in PSBT inputs and outputs (Alekos Filini)
1312184ed7a9c5c7a6f99cf8bb08d43775ba5083 Attach a context to our software signers (Alekos Filini)
906598ad9254643a204df7711693dcc0a73a0332 Refactor signer traits, add support for taproot signatures (Alekos Filini)

Pull request description:

  ### Description

  This is a work-in-progress PR to update BDK to rust-bitcoin `0.28` which introduces taproot support and a few other improvements. While updating we also introduce taproot support in BDK.

  High level list of subtasks for this PR:
  - [x] Update rust-bitcoin and rust-miniscript
  - [x] Stop using deprecated structs
  - [x] Add taproot metadata to psbts
  - [x] Produce schnorr signatures
  - [x] Finalize taproot txs
  - [x] Support `tr()` descriptors in the `descriptor!()` macro
  - [x] Write a lot of tests
    - [x] Interoperability with other wallets (Core + ?)
       - [x] Signing/finalizing a psbt made by core
       - [x] Producing a psbt that core can sign and finalize
    - [x] Creating psbts
      - [x] Verify the metadata are correct
      - [x] Verify sighashes are applied correctly
      - [x] Create a tx with a foreign taproot and non-taproot utxo
    - [x] Signing psbts
      - [x] Signing for a key spend
      - [x] Signing for a script spend
      - [x] Signing with a single (wif) key
      - [x] Signing with an xprv (with and without knowing the utxo being spent in the db)
      - [x] Signing with weird sighashes
    - [x] Policy module
      - [x] Simple key spend
      - [x] More complex tap tree with a few keys
      - [x] Verify both `contribution` and `satisfaction` of a PSBT input
    - [x] Wallet module
      - [x] Generate addresses

  Fixes #63

  ### Notes to the reviewers

  #### Milestone

  I'm adding this to the `0.19` milestone because now that rust-bitcoin and rust-miniscript have been released we should not waiting too long to release a version of BDK that supports the new libraries.

  #### API Breaks

  Since this is an API-break because of the new version of rust-bitcoin and rust-miniscript, I'm also taking the chance to update a few things in our lib that I had been thinking about for a while.

  One example is the signer interface, which had that weird `sign_whole_tx()` method. This has now been removed, and the `Signer` trait replaced with `TransactionSigner` and `InputSigner`. I'm also starting to think that the signer should not only look at the psbt to figure out what to do, but ideally it should also receive some information about the descriptor (for example, the type) to simplify the code.

  One option is to add an extra parameter, but that would probably only be used by our internal signers and not much else (for example, if you ask an hardware wallet to sign, it will probably already know what kind of wallet you have).

  Another option is to wrap `PrivateKey` and `DescriptorXKey<ExtendedPrivKey>` which are the two internal signers we support with a struct that contains metadata about the descriptor, and then implement the signer traits on that struct. We could construct this in `Wallet::new()`, after miniscript parses the descriptor.

  #### MSRV Bump

  Due to the update of `rust-electrum-client`, which in turn depends on an updated `webpki`, we will have to bump our MSRV beacuse 1.46 is not supported by the new `webpki` version.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

Top commit has no ACKs.

Tree-SHA512: 44ec6c4e7fe0bc87862bb76581ddae7905c8796a4a130c90b48b73b4b7d01ea1a20043b8a0ff449fc2db2f7aecc490def8daee2d420809ded1ece7f085a48f55
2022-06-03 16:43:20 +02:00
Philipp Hoenisch
d9b9b3dc46
Fix InvalidColumnIndex error
This query returns 7 columns, so last columns is index 6
2022-06-03 15:28:43 +10:00
Alekos Filini
20d36c71d4
Update CHANGELOG.md for Taproot 2022-06-01 14:55:43 +02:00
Alekos Filini
ef08fbd3c7
Update to the newest release of rust-bitcoin 2022-06-01 14:51:40 +02:00
Alekos Filini
5320c8353e
taproot-tests: validate tap_tree in psbt outputs
Co-authored-by: Daniela Brozzoni <danielabrozzoni@protonmail.com>
2022-06-01 14:51:38 +02:00
Steve Myers
c1bfaf9b1e
Add blockchain tests for parsing, signing, finalizing taproot core psbts 2022-06-01 14:51:36 +02:00
Alekos Filini
0643f76c1f
taproot-tests: Add tests for the policy module 2022-06-01 14:51:34 +02:00
Alekos Filini
89cb425e69
taproot-tests: Add test coverage for tx signing 2022-06-01 14:51:32 +02:00
Alekos Filini
461397e590
taproot-tests: Test taproot key and script spend in the blockchain tests
This is to ensure a Bitcoin node accepts our transactions
2022-06-01 14:51:30 +02:00
Alekos Filini
c67116fb55
policy: Consider tap_key_origins when looking for sigs in PSBTs
We used to only look at `bip32_derivations` which is only used for ECDSA
keys.
2022-06-01 14:51:28 +02:00
Alekos Filini
572c3ee70d
policy: Build SatisfiableItem::*Signature based on the context
Also refactor our code to lookup signatures in PSBTs to use the context
2022-06-01 14:51:26 +02:00
Alekos Filini
ff1abc63e0
policy: Refactor PkOrF into an enum
For whatever reason we were using a struct as an enum, so we might as
well fix it in this PR since we are already breaking the API quite
badly.
2022-06-01 14:51:16 +02:00
Alekos Filini
308708952b
Fix type inference for the tr() descriptor, add basic tests 2022-05-31 18:16:24 +02:00
Alekos Filini
fe1877fb18
Support tr() descriptors in dsl 2022-05-31 18:16:22 +02:00
Alekos Filini
cdc7057813
Add tr() descriptors to the descriptor!() macro 2022-05-31 18:16:21 +02:00
Alekos Filini
c121dd0252
Use tap_key_origins in PSBTs to derive descriptors 2022-05-31 18:16:17 +02:00
Alekos Filini
8553821133
Populate more taproot fields in PSBTs 2022-05-31 18:13:08 +02:00
Alekos Filini
8a5a87b075
Populate tap_key_origin in PSBT inputs and outputs 2022-05-31 18:06:59 +02:00
Alekos Filini
1312184ed7
Attach a context to our software signers
This allows the signer to know the signing context precisely without
relying on heuristics on the psbt fields.

Due to the context being static, we still have to look at the PSBT when
producing taproot signatures to determine the set of leaf hashes that
the key can sign for.
2022-05-27 11:48:50 +02:00
Alekos Filini
906598ad92
Refactor signer traits, add support for taproot signatures 2022-05-27 11:48:41 +02:00
Steve Myers
fbd98b4c5a
Merge bitcoindevkit/bdk#605: Fix sqlite database set_utxo to insert or update utxos
35feb107ed5969720ce54a6aa76b7b2176f6c7c1 [CI] Fix cont_integration test-blockchains to run all tests (Steve Myers)
24719081511969299459d01566b0d669a7b51f7b Update CHANGELOG with warning about sqlite-db deleted wallet data (Steve Myers)
0b1a399f4e556a981bb992cc9b1d34318e260a7c Update sqlite schema with unique index for utxos, change insert_utxo to upsert (Steve Myers)
cea79872d717b395560a344cc4dd0e022c3bd9a9 Update database tests to verify set_utxo upserts (Steve Myers)

Pull request description:

  ### Description

  This PR fixes #591 by:
  1. Add sqlite `MIGRATIONS` statements to remove duplicate utxos and add unique utxos index on txid and vout.
  2. Do an upsert (if insert fails update) instead of an insert in `set_utxo()`.
  3. Update database::test::test_utxo to also verify `set_utxo()` doesn't insert duplicate utxos.

  ### Notes to the reviewers

  I verified the updated `test_utxo` fails as expected before my fix and passes after the fix. I tested the new migrations using the below `bdk-cli` command and a manually updated sqlite db with duplicate utxos.
  ```shell
  cargo run --no-default-features --features cli,sqlite-db,esplora-ureq -- wallet -w test1 --descriptor "wpkh(tpubEBr4i6yk5nf5DAaJpsi9N2pPYBeJ7fZ5Z9rmN4977iYLCGco1VyjB9tvvuvYtfZzjD5A8igzgw3HeWeeKFmanHYqksqZXYXGsw5zjnj7KM9/*)" sync
  ```

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    utACK 35feb107ed5969720ce54a6aa76b7b2176f6c7c1 - Code looks good, but I didn't do any local test to see if the db gets wiped

Tree-SHA512: 753c7a0cfd0e803b5e12f39181d9a718791c4ce229d5072e6498db75a7008e94d447b3d0b4b0c205e7a8f127f60102e12bac2d271b8bad3a3038856bfd54e99c
2022-05-24 08:25:24 -07:00
Alekos Filini
87b07456bd
Merge bitcoindevkit/bdk#610: Populate the redeemScript for sh(wsh(sortedmulti()))
82de8b50da6e8b9752332b80da395c792c371def Populate the redeemScript for `sh(wsh(sortedmulti()))` (Alekos Filini)

Pull request description:

  ### Description

  Also explicitly match all the individual variants to ensure a similar problem
  doesn't happen again.

  Fixes #609

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 82de8b50da6e8b9752332b80da395c792c371def

Tree-SHA512: 7cccae44679089b70e8d9df466a165debe17c4cf30ae11cb27357fbda830d3d7ce53161e414b354b1f2be46efe413b8e44132f5e6d625298b740d44112ca286a
2022-05-24 10:15:34 +02:00
Alekos Filini
82de8b50da
Populate the redeemScript for sh(wsh(sortedmulti()))
Also explicitly match all the individual variants to ensure a similar problem
doesn't happen again.

Fixes #609
2022-05-23 21:02:42 +02:00
Steve Myers
35feb107ed
[CI] Fix cont_integration test-blockchains to run all tests 2022-05-19 14:00:40 -07:00
Steve Myers
2471908151
Update CHANGELOG with warning about sqlite-db deleted wallet data 2022-05-19 13:20:54 -07:00
Steve Myers
0b1a399f4e
Update sqlite schema with unique index for utxos, change insert_utxo to upsert 2022-05-19 13:20:11 -07:00
Steve Myers
cea79872d7
Update database tests to verify set_utxo upserts 2022-05-19 13:20:09 -07:00
Steve Myers
4c1749a13a
Merge bitcoindevkit/bdk#604: unpinning dependency tokio to just 1
939a1156c65d0f347cb4397e0883573737d39761 unpinning dependency tokio to 1 (Richard Ulrich)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  unpinning dependency tokio to just 1

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 939a1156c65d0f347cb4397e0883573737d39761

Tree-SHA512: 7b33522411f6b63d844d12cc86c8992aa4105c29e91dbef67362a6c600f3ef39e802ff5893054bf8feeb7fa5bf383765025096cbc2ccb9a6b83bc5c919a5a43d
2022-05-17 11:14:30 -07:00
Richard Ulrich
939a1156c6
unpinning dependency tokio to 1 2022-05-17 14:44:45 +02:00
Alekos Filini
e5486536ae
Merge bitcoindevkit/bdk#606: Upgrade to rust-bitcoin 0.28
00164588f2ddab91bb4468ec010dc1bbca277eb5 Stop using deprecated structs (Alekos Filini)
a16c18255ceb3e13ff92ee41b2b6f6510491eeb8 Upgrade to rust-bitcoin 0.28 and miniscript 7.0 (Alekos Filini)

Pull request description:

  ### Description

  Upgrade all our dependencies to work with the new release of rust-bitcoin

  ### Notes to the reviewers

  The commits in this pr were originally part of #593

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  rajarshimaitra:
    ACK 00164588f2ddab91bb4468ec010dc1bbca277eb5

Tree-SHA512: eef7e94246e619686b4dfffd6e4cb685630fe2eaf9447f2f0b49ed2643d67f81c50e0d89b66267db4552a05e58f638d885eb7056270648403f716803fce9e275
2022-05-12 20:29:59 +02:00
Alekos Filini
00164588f2
Stop using deprecated structs 2022-05-12 17:31:48 +02:00
Alekos Filini
a16c18255c
Upgrade to rust-bitcoin 0.28 and miniscript 7.0 2022-05-12 12:51:21 +02:00
Steve Myers
7aa2746c51
Merge bitcoindevkit/bdk#569: [blockchain] Add traits to reuse Blockchains across multiple wallets
8795da48397800effeffae8417c6e749ec488212 wallet: Move `wallet_name_from_descriptor` above the tests (Alekos Filini)
9c405e9c70e417dea0e610f9d44e99911d6b4e44 [blockchain] Add traits to reuse `Blockchain`s across multiple wallets (Alekos Filini)
2d83af49051f5d33105315164f3edf7f72f3741f Move testutils macro module before the others (Alekos Filini)

Pull request description:

  ### Description

  Add three new traits:
  - `StatelessBlockchain` is used to tag `Blockchain`s that don't have any wallet-specic state, i.e. they can be used as-is to sync multiple wallets.
  - `StatefulBlockchain` is the opposite of `StatelessBlockchain`: it provides a method to "clone" a `Blockchain` with an updated internal state (a new wallet checksum and, optionally, a different number of blocks to skip from genesis). Potentially this also allows reusing the underlying connection on `Blockchain` types that support it.
  - `MultiBlockchain` is a generalization of this concept: it's implemented automatically for every type that implements `StatefulBlockchain` and for every `Arc<T>` where `T` is a `StatelessBlockchain`. This allows a piece of code that deals with multiple sub-wallets to just get a `&B: MultiBlockchain` without having to deal with stateful and statless blockchains individually.

  These new traits have been implemented for Electrum, Esplora and RPC (the first two being stateless and the latter stateful). It hasn't been implemented on the CBF blockchain, because I don't think it would work in its current form (it throws away old block filters, so it's hard to go back and rescan).

  This is the first step for #549, as BIP47 needs to sync many different descriptors internally.

  It's also very useful for #486.

  ### Notes to the reviewers

  This is still a draft because:
  - I'm still wondering if these traits should "inherit" from `Blockchain` instead of the less-restrictive `WalletSync` + `GetHeight` which is the bare minimum to sync a wallet
  - I need to write tests, at least for rpc which is stateful
  - I need to add examples

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  rajarshimaitra:
    tACK 8795da48397800effeffae8417c6e749ec488212

Tree-SHA512: 03f3b63d51199b26a20d58cf64929fd690e2530f873120291a7ffea14a6237334845ceb37bff20d6c5466fca961699460af42134d561935d77b830e2e131df9d
2022-05-10 21:35:28 -07:00
Alekos Filini
616aa8259a
Merge bitcoindevkit/bdk#602: wrong Network path fixed
b4100a71896cdbd7cf2c38cdce9f846ea74b6d44 wrong Network path fixed (Pedro Felix)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description
  This change needs to be made for this example to compile correctly.
  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK b4100a71896cdbd7cf2c38cdce9f846ea74b6d44

Tree-SHA512: b4b7d186cabc7b3ed2d5b6411414d56eeee09c4e8d9d704a26f8817d6573b6b182d7ef1ff8139b6f4f6fb3e4ec99c2c09758804a6bb25051e45b0885c0def5e3
2022-05-10 17:25:57 +02:00
Alekos Filini
8795da4839
wallet: Move wallet_name_from_descriptor above the tests 2022-05-09 19:34:06 +02:00
Alekos Filini
9c405e9c70
[blockchain] Add traits to reuse Blockchains across multiple wallets
Add two new traits:
- `StatelessBlockchain` is used to tag `Blockchain`s that don't have any
  wallet-specic state, i.e. they can be used as-is to sync multiple wallets.
- `BlockchainFactory` is a trait for objects that can build multiple
  blockchains for different descriptors. It's implemented automatically
  for every `Arc<T>` where `T` is a `StatelessBlockchain`. This allows a
  piece of code that deals with multiple sub-wallets to just get a
  `&B: BlockchainFactory` to sync all of them.

These new traits have been implemented for Electrum, Esplora and RPC
(the first two being stateless and the latter having a dedicated
`RpcBlockchainFactory` struct). It hasn't been implemented on the CBF
blockchain, because I don't think it would work in its current form
(it throws away old block filters, so it's hard to go back and rescan).

This is the first step for #549, as BIP47 needs to sync many different
descriptors internally.

It's also very useful for #486.
2022-05-09 19:34:04 +02:00
Alekos Filini
2d83af4905
Move testutils macro module before the others
This allows using the `testuitils` macro in their tests as well
2022-05-09 19:30:51 +02:00
Pedro Felix
b4100a7189
wrong Network path fixed
Signed-off-by: Pedro Felix <NEWAGAIN@Pedros-MacBook-Pro.local>
Signed-off-by: Pedro Felix <p.felixgarcia@gmail.com>
2022-05-06 17:30:21 -07:00
Alekos Filini
cfb67fc25b
Merge bitcoindevkit/bdk#600: Change wallet::get_funded_wallet to return Wallet<AnyDatabase>
e7a56a92685ce1948d2ec7232fccd7e072d4abb3 Change wallet::get_funded_wallet to return Wallet<AnyDatabase> (Steve Myers)

Pull request description:

  ### Description

  Change testing function `wallet::get_funded_wallet` to return `Wallet<AnyDatabase>` instead of `Wallet<MemoryDatabase>`. This will allow us to use this function for testing `bdk-ffi` which only works with `Wallet<AnyDatabase>`.

  ### Notes to the reviewers

  This is required to complete https://github.com/bitcoindevkit/bdk-ffi/pull/148.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK e7a56a92685ce1948d2ec7232fccd7e072d4abb3

Tree-SHA512: 47b53ab6dcee63fc7b24666d3cf9a0ad832782081dd2fe92961c8c9b4c302df90db96b0b518af71d6cbc85319434971219100f8cedb35ce7212d944db29a4295
2022-05-06 10:28:57 +02:00
Alekos Filini
7201e09db9
Merge bitcoindevkit/bdk#599: Fix typo in docs for TxBuilder allow_shrinking method
4628a10191f451a7b0ade674e9f8568bf695e49c Fix typo in docs for TxBuilder allow_shrinking method (thunderbiscuit)

Pull request description:

  ### Description
  This PR fixes a small typo in the documentation for the `allow_shrinking()` method on the `TxBuilder`.

  ### Notes to the reviewers
  The sentence
  ```txt
  Explicitly tells the wallet that it is allowed to reduce the fee of the output matching this `script_pubkey` in order to bump the transaction fee. Without specifying this the wallet will attempt to find a change output to shrink instead.
  ```
  was changed for
  ```txt
  Explicitly tells the wallet that it is allowed to reduce the amount of the output matching this `script_pubkey` in order to bump the transaction fee. Without specifying this the wallet will attempt to find a change output to shrink instead.
  ```

  To reflect the fact that it's the _amount_ of the output that is being reduced in order to leave more for the fees.

  ### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 4628a10191f451a7b0ade674e9f8568bf695e49c

Tree-SHA512: ca135764d78144295fdbdb4673ca6dec153c6f83ee7fb5d7d3051e0d46b04d23b2f3c3fd66e44491da842c778e72b52f8996d00e4c20986d7ccb11587f0d7d27
2022-05-06 10:27:00 +02:00
Steve Myers
e7a56a9268
Change wallet::get_funded_wallet to return Wallet<AnyDatabase> 2022-05-05 16:43:10 -07:00
thunderbiscuit
4628a10191
Fix typo in docs for TxBuilder allow_shrinking method 2022-05-05 15:15:04 -04:00
Steve Myers
2f325328c5
Merge bitcoindevkit/bdk#596: Bump MSRV to 1.56
cca69481eb7edb28532a4ed78185248d410050ac Bump MSRV to 1.56 (Alekos Filini)

Pull request description:

  ### Description

  Following the discussion in #331, bump the MSRV to `1.56`. We already have other PRs bumping it to at least `1.51` (#593), but I'm felling like we are always lagging behind and our CI breaks regularly. As @LLFourn suggested, this PR makes a relatively large bump, hoping this buys us enough time to finish splitting up BDK, which will allow us to have a lower MSRV for the "core" crate.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  notmandatory:
    ACK cca69481eb7edb28532a4ed78185248d410050ac

Tree-SHA512: bc6572dc94e1c4cbb6d21f6e06a9730af5763fb4811311a61a6a6ec850b5a65664a21e4a7070a3ebcd702529fbba97b2e9a43c1277b9b9f092e194f16a39bc1a
2022-05-04 09:57:30 -07:00
Alekos Filini
cca69481eb
Bump MSRV to 1.56 2022-05-04 17:29:07 +02:00
Alekos Filini
6e8744d59d
Merge bitcoindevkit/bdk#557: add OldestFirstCoinSelection
6931d0bd1f044bf73c0cb760c0eb0be19aea8de1 add private function select_sorted_utxso to be resued by multiple CoinSelection impl (KaFai Choi)
545beec743412717895d0ba5d32ccd9aac68f4a6 add OldestFirstCoinSelection (KaFai Choi)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description
  This PR is to add `OldestFirstCoinSelection`. See this issue for detail https://github.com/bitcoindevkit/bdk/issues/120
  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers
  Apologize in advance if the quality of this PR is too low.(I am newbie in both bitcoin wallet and rust).

  While this PR seemed very straight-forward to me in the first glance, it's actually a bit more complicated than I thought as it involves calling DB get the blockheight before sorting it.

  The current implementation should be pretty naive but I would like to get some opinion to see if I am heading to a right direction first before working on optimizations like

  ~~1. Avoiding calling DB for optional_utxos if  if the amount from required_utxos are already enough.~~ Probably not worth to do such optimization to keep code simpler?

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 6931d0bd1f044bf73c0cb760c0eb0be19aea8de1

Tree-SHA512: d297bbad847d99cfdd8c6b1450c3777c5d55bc51c7934f287975c4d114a21840d428a75a172bfb7eacbac95413535452b644cab971efb8c0b5caf0d06d6d8356
2022-04-25 16:46:41 +02:00
Alekos Filini
79f73df545
Merge bitcoindevkit/bdk#582: Expose bip39::Error
c752ccbddeaa5ae441cc74a1386c1e412a447104 Expose bip39::Error (志宇)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Expose `bip39::Error` (fixes #581 )

  ### Notes to the reviewers

  I am aware that the `bip39` module plans to be rewritten (as per #561 ), however this seems like a rather straightforward and quick change that may be useful in the short/mid term.

  ### Checklists

  #### Bugfixes:

  * [x] Expose `bip39::Error`

ACKs for top commit:
  afilini:
    ACK c752ccbddeaa5ae441cc74a1386c1e412a447104

Tree-SHA512: 98b7ac1ba88aed07d9160830ee80496c32d531c15ada0e9b50a97f0883fbfced22fa83a7c7f8366aadb7e7a667d8a63dde869d31cc375206d277e55b2ec3089d
2022-04-25 16:14:46 +02:00
Alekos Filini
9db8d3a410
Merge bitcoindevkit/bdk#584: Release 0.18.0
b5c8ce924bc47d26a0d577bfcbdaf241c56aa253 Bump version to 0.19.0-dev (Steve Myers)
e3ce50059fca2d58587fdf4dd806ffacfef3d302 Bump version to 0.18.0 (Steve Myers)
8a2a6bbceeec3f682c789537ca619da821d34732 Add `n:` wrapper to vulnerable scripts (Alekos Filini)
122e6e71405f65ecb3c75adaff1e35ab5ef3a06e Bump 'miniscript' dependency version to '^6.1' (Steve Myers)
9ed36875f1112d884f6c3c2beab89faf8aa5d2e0 export: Rename `WalletExport` to `FullyNodedExport` (Alekos Filini)
f90e3f978e3c7ec5dde0a592d79da419a7c9ec3a Update changelog with addition of keychain to AddressInfo (Steve Myers)
68e1b32d81978746dba0abdd14af94edbfdcf9b4 Bump version to 0.18.0-rc.1 (Steve Myers)

Pull request description:

  ### Description

  Release 0.18.0.

  ### Notes to the reviewers

  This branch also includes the following changes which are not yet in the `master` branch:

  - Rename `WalletExport` to `FullyNodedExport`, deprecate the former.
  - Bump `miniscript` dependency version to `^6.1`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  afilini:
    ACK b5c8ce924bc47d26a0d577bfcbdaf241c56aa253

Tree-SHA512: d6a8c1ca2c13d3a84704592053cc450557c96229b0092e655ccf97775c3e0a23e9e1499cf8c9fc5a24fc0665ec0333d0ec6d6b06cb15eb2e14c033f06c3032c2
2022-04-21 17:17:32 +02:00
Steve Myers
b5c8ce924b
Bump version to 0.19.0-dev 2022-04-20 10:31:31 -07:00
Steve Myers
e3ce50059f
Bump version to 0.18.0 2022-04-20 09:58:13 -07:00
Alekos Filini
8a2a6bbcee
Add n: wrapper to vulnerable scripts 2022-04-20 18:25:26 +02:00
Steve Myers
122e6e7140
Bump 'miniscript' dependency version to '^6.1' 2022-04-20 08:16:53 -07:00
Steve Myers
1018bb2b17
Merge bitcoindevkit/bdk#589: export: Rename WalletExport to FullyNodedExport
9ed36875f1112d884f6c3c2beab89faf8aa5d2e0 export: Rename `WalletExport` to `FullyNodedExport` (Alekos Filini)

Pull request description:

  ### Description

  The `WalletExport` type can still be used as an alias to `FullyNodedExport` but it has been marked as deprecated and will be removed in the next release.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  bucko13:
    Concept ACK 9ed3687
  notmandatory:
    ACK 9ed36875f1112d884f6c3c2beab89faf8aa5d2e0

Tree-SHA512: fe07307092d3040b30ae96901d5fc4afecee635412bca4a0d2e78d90f07990e7bbcd6b87ed923bf5804385356f419cacadbfefbaf97ebc9a622e34548438ee00
2022-04-19 19:21:11 -07:00
Alekos Filini
9ed36875f1
export: Rename WalletExport to FullyNodedExport
The `WalletExport` type can still be used as an alias to
`FullyNodedExport` but it has been marked as deprecated and will be
removed in the next release.
2022-04-19 11:44:50 +02:00
Steve Myers
502882d27c
Merge branch 'master' into release/0.18.0 2022-04-14 10:06:47 -07:00
Steve Myers
a328607d27
Merge bitcoindevkit/bdk#583: Improve keys traits, simplify rpcwallet example
44758f9483b049acbcd9f8948e29cd6f6add0cc2 Simplify the `rpcwallet` example using the improved keys traits (Alekos Filini)
c350064dae43fd9c892bb7dd272b14ce62f9e82d Update changelog changes in `keys` mod (Alekos Filini)
92746440db964b5e50f4017828516b36eb14e765 [keys] Make `GenerateKey<K>` clonable if K is (Alekos Filini)
e4eb95fb9cfbae3596deb310984fa18462d1b30c [keys] Implement `DerivableKey<Ctx>` for `(GeneratedKey<Mnemonic, Ctx>, Option<String>)` (Alekos Filini)

Pull request description:

  ### Description

  I recently looked at the `rpcwallet` example and immediately thought the key generation part was very confusing. I made a few little changes to our traits and now I believe it's much better.

  I'm copying the next few paragraphs from the first commit in this PR which explains why it's better not to extract the key from the `GeneratedKey` wrapper:

  > This lets us use a tuple of (generated mnemonic, optional passphrase) as a `DerivableKey` directly, without extracting the inner mnemonic from the `GeneratedKey` wrapper. For BIP39 keys specifically it doesn't make much difference because the mnemonic format doesn't encode the network, but in general this is not the case and having a consistent API will make it harder for people to make mistakes.

  > To explain why we should not extract the key: some key formats (like BIP32 extended keys) are network-specific, meaning that if somebody tries to use a Testnet key on a Mainnet BDK wallet, it won't work.

  > However, when we generate a new key we would like to be able to use that key on any network, but we need to set some kind of placeholder for the `network` field in the structure. This is why (or at least one of the reasons why) we wrap the key in the `GeneratedKey` struct: we keep track of the "valid_networks" separately, which means that even if we set our BIP32 xprv to be a "Mainnet" key, once we go try creating a wallet with that key BDK is smart enough to understand that `GeneratedKey`s have  their own separate set of valid networks and it will use that set to validate whether the key can be used in the wallet or not.

  ### Notes to the reviewers

  I'm adding this to the `0.18` milestone even if the feature freeze is today. I don't think we should wait for this PR to start the release branch, but since it's just a minor addition to our traits I believe we could merge this afterwards to the release branch if we manage to get it reviewed and ready within the next week.

  Otherwise it'll just wait for `0.19`, it's not a big deal.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  notmandatory:
    tACK 44758f9483b049acbcd9f8948e29cd6f6add0cc2

Tree-SHA512: 31a8b5a3cd56c7c39688c4804026a8b6cee950c50ea880efcddc150ef523e2ddcc544831bf996a58b5cf3b7bc4a086c1008dc0728604e5134d331c68855c2d5b
2022-04-14 09:58:10 -07:00
Steve Myers
f90e3f978e
Update changelog with addition of keychain to AddressInfo 2022-04-13 13:51:12 -07:00
Steve Myers
68e1b32d81
Bump version to 0.18.0-rc.1 2022-04-13 13:40:16 -07:00
Alekos Filini
44758f9483
Simplify the rpcwallet example using the improved keys traits 2022-04-13 12:56:43 +02:00
Alekos Filini
c350064dae
Update changelog changes in keys mod 2022-04-13 12:56:04 +02:00
Alekos Filini
92746440db
[keys] Make GenerateKey<K> clonable if K is 2022-04-13 12:55:23 +02:00
Alekos Filini
e4eb95fb9c
[keys] Implement DerivableKey<Ctx> for (GeneratedKey<Mnemonic, Ctx>, Option<String>)
This lets us use a tuple of (generated mnemonic, optional passphrase) as
a `DerivableKey` directly, without extracting the inner mnemonic from the
`GeneratedKey` wrapper. For BIP39 keys specifically it doesn't make much
difference because the mnemonic format doesn't encode the network, but in
general this is not the case and having a consistent API will make it
harder for people to make mistakes.

To explain why we should not extract the key: some key formats (like
BIP32 extended keys) are network-specific, meaning that if somebody
tries to use a Testnet key on a Mainnet BDK wallet, it won't work.

However, when we generate a new key we would like to be able to use that
key on any network, but we need to set some kind of placeholder for the
`network` field in the structure. This is why (or at least one of the
reasons why) we wrap the key in the `GeneratedKey` struct: we keep track
of the "valid_networks" separately, which means that even if we set our
BIP32 xprv to be a "Mainnet" key, once we go try creating a wallet with
that key BDK is smart enough to understand that `GeneratedKey`s have
their own separate set of valid networks and it will use that set to
validate whether the key can be used in the wallet or not.
2022-04-13 12:37:27 +02:00
Alekos Filini
c307bacb9c
Merge bitcoindevkit/bdk#577: Deprecate Database::flush() function
a111d254769bfa698043cb9172a3e1cc84329ee4 Deprecate Database::flush() function (Steve Myers)

Pull request description:

  ### Description

  The Database::flush() function is only needed for the sled database on mobile, instead for mobile use the sqlite database.

  ### Notes to the reviewers

  This PR is in preparation for removing the Database::flush() function. See https://github.com/bitcoindevkit/bdk/pull/575#issuecomment-1082916667.

  After the `release/0.18.0` feature freeze branch is created then #575 should be merged.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  afilini:
    ACK a111d254769bfa698043cb9172a3e1cc84329ee4

Tree-SHA512: 18434dc95dbef47118a0d4fface908bdf920a7ffcef927b36bb740c15f8efcf11dea9198b364648f16f74aaec4aa18e92a3c5e925299b2f3b9d69e566f89e790
2022-04-13 12:00:35 +02:00
Steve Myers
a111d25476
Deprecate Database::flush() function
The Database::flush() function is only needed for the sled database on mobile, instead for mobile use the sqlite database.
2022-04-12 14:16:09 -07:00
志宇
c752ccbdde
Expose bip39::Error 2022-04-07 19:50:17 +08:00
Steve Myers
0621ca89d5
Merge bitcoindevkit/bdk#579: Faster sync by collecting esplora ureq thread handles
adef166b22d5c95006df39fd8c57574624071189 Create vector of thread handles to spawn threads (nickfarrow)

Pull request description:

  ### Description
  Speeds up esplora ureq syncing. Taken from https://github.com/bitcoindevkit/bdk/pull/560

  The current sync just creates a map of scripts to joinhandles which doesn't yet spawn the sync threads due to lazy evaluation. In the following `handles.map()`, the thread handles are *sequentially* evaluated and joined. With the fix, the handles are collected so that the threads spawn in parallel, and then joined

  ### Notes to the reviewers

  I had to add a `#[allow(clippy::needless_collect)]` so that it wouldn't complain about collecting and then iterating. (Perhaps clippy is partially responsible for this issue!)

  Tested sync performance by doing a fresh sync on an existing [gun](https://gun.fun) wallet.
  ```
  ---- Before fix ---
  real0m13.121s
  real0m13.367s
  real0m13.211s

  ---- After fix ----
  real0m5.516s
  real0m5.251s
  real0m5.594s
  ```

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK adef166b22d5c95006df39fd8c57574624071189

Tree-SHA512: 47c617117afde9b4706bfa63759bf06d1ec60ff95d8a80931e5b7e40e3293c855d2f7dac0c681173d43aecf77201a842e739b82291da09ac81909cf526a51c8d
2022-04-06 12:42:03 -07:00
nickfarrow
adef166b22
Create vector of thread handles to spawn threads
Signed-off-by: nickfarrow <nick@nickfarrow.com>
2022-04-06 16:10:59 +10:00
Steve Myers
213f18f7b7
Merge bitcoindevkit/bdk#562: Expose more getters in Wallet and other useful descriptor traits
1b9014846c5cb690f5c37f70556717b788a0733b Update changelog (Alekos Filini)
86abd8698f34d91f94bfce896affb535cca27146 [descriptor] Expose utilities to deal with derived descriptors (Alekos Filini)
0d9c2f76e00af801668fa2a70fcd13f9e399c0d2 [export] Use the new getters on `Wallet` to generate export JSONs (Alekos Filini)
63d5bcee934febe4d38622b677131bbe2e1a0abe [wallet] Add more getters (Alekos Filini)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Expose more getters and internal utilities for people who need to work with descriptors.

  A good example of how this can be leveraged is in the second commit, which refactors the wallet export functionality to use the new public APIs rather than using members on `Wallet` directly.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  notmandatory:
    ACK 8cd055090d75669c67a44467cc0281465ef31270

Tree-SHA512: 3e8833670ebc56316fce01fc572fcc9391d602ef85f0cde8edcb446295570a9012e18f6ba8af0984153e4688f66f7eea6803ef610ceb395867e464e05c01c137
2022-04-04 20:53:18 -07:00
Steve Myers
8cd055090d
Merge branch 'master' into feature/more-getters 2022-04-04 19:32:55 -07:00
Alekos Filini
1b9014846c
Update changelog 2022-04-04 18:57:33 -07:00
Steve Myers
9c0141b5e3
Merge bitcoindevkit/bdk#563: update AddressInfo struct
2698fc0219eb360e84a89ceabba4793777bf550b update AddressInfo struct (eunoia_1729)

Pull request description:

  ### Description

  Resolves #541.
  - Updates `AddressInfo` struct to include `keychainKind`
  - Updates the related `get_address` functions to pass in this field
  - Updates corresponding tests
  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: b1d22e5f322e1a35390fb06a5185457bd53af7c4a9c4e6e2fd5e93b967fa3f56af5848ac314e63e2b0becd60dbc8a4eeb761a2bdebfe8ba43ce49b13da4190b2
2022-04-04 17:36:16 -07:00
eunoia_1729
2698fc0219
update AddressInfo struct 2022-04-04 11:14:00 +05:30
KaFai Choi
6931d0bd1f
add private function select_sorted_utxso to be resued by multiple CoinSelection impl 2022-04-02 10:59:08 +07:00
KaFai Choi
545beec743
add OldestFirstCoinSelection 2022-04-02 10:59:04 +07:00
Steve Myers
bac15bb207
Merge bitcoindevkit/bdk#554: Fix hierarchy of headers on docs landing page
364ad95e85bd09a01cb4cbf3ceb9e9fcc074c8b4 Fix hierarchy of headers on docs landing page (thunderbiscuit)

Pull request description:

  ### Description

  This PR fixes the hierarchy of headers on the lib.rs docs. I noticed it as I was reading through the docs. The new hierarchy is the following:

  - About (h1)
  - A tour of BDK (h1)
  - Examples (h1)
    - Sync the balance of a descriptor (h2)
    - Generate a few addresses (h2)
    - Create a transaction (h2)
    - Sign a transaction (h2)
  - Feature flags (h1)
  - Internal features (h1)

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  rajarshimaitra:
    tACK 364ad95e85

Tree-SHA512: b4439a200c320a1815c572ac36b81c4d684209cb5cf1b90d3f761893ad672a270722be7d7b61d77434a7f98c4276d6fc9694d0c86cacf03c72dc35ca17b5e7d3
2022-04-01 19:33:21 -07:00
Steve Myers
06b80fdb15
Merge branch 'master', commit 'refs/pull/566/head' of github.com:bitcoindevkit/bdk 2022-03-30 09:54:34 -07:00
Steve Myers
ff6db18726
Merge bitcoindevkit/bdk#519: Add wallet creation example using RPC
8a98e69e788dd79d030798465fbc0dec044d86f1 Add rpc wallet creation example (rajarshimaitra)

Pull request description:

  ### Description

  As mentioned in https://github.com/bitcoindevkit/bitcoindevkit.org/issues/83#issuecomment-1005190174 it would be helpful
  to have wallet creation example code in the `example` directory.

  This is an attempt to create the most simplistic bdk wallet with a RPC backend and demonstrate receiving, creating, signing
  and broadcasting transaction.

  The code is a refinement of the RPC tutorial https://bitcoindevkit.org/blog/bitcoin-core-rpc-demo/ with more elaborate doc comments.

  ### Notes to the reviewers

  To automate the background RPC process `electrsd` is used which is already a `dev-dependency` of bdk.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    tACK 8a98e69e788dd79d030798465fbc0dec044d86f1

Tree-SHA512: f00c1ce57ef91c3d3ab2ce08af3571c41bbe98f18f705c61ba4217c2f8061196e5eaf6122742293cd6fa16939bbbfacd0f8506cd4151b55f19a05325fd94a74a
2022-03-29 09:56:09 -07:00
Alekos Filini
86abd8698f
[descriptor] Expose utilities to deal with derived descriptors 2022-03-25 11:18:56 +01:00
Alekos Filini
0d9c2f76e0
[export] Use the new getters on Wallet to generate export JSONs 2022-03-25 11:18:54 +01:00
Alekos Filini
63d5bcee93
[wallet] Add more getters 2022-03-25 11:18:52 +01:00
rajarshimaitra
8a98e69e78
Add rpc wallet creation example
This adds an example wallet creation code with sled DB and RPC
Blockchain.

The backend RPC is managed using electrsd::bitcoind
2022-03-23 11:59:51 +05:30
Steve Myers
c6eeb7b989
Add sqlite-bundled feature 2022-03-22 10:00:55 -05:00
Steve Myers
3334c8da07
Merge commit 'refs/pull/564/head' of github.com:bitcoindevkit/bdk 2022-03-21 09:58:01 -05:00
Steve Myers
ce09203431
Bump version to 0.17.1-dev 2022-03-18 09:35:46 -05:00
Steve Myers
cac312d34f
Bump version to 0.17.0 2022-03-17 11:17:55 -05:00
Steve Myers
4b1be68965
Merge bitcoindevkit/bdk#545: Update electrsd to v0.15
1803f5ea8a7a2f8f9ebdfa520baad91f84bd6ba0 Update `electrsd` to v0.15 (Alekos Filini)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  PR RCasatta/electrsd#33 has been merged and the new changes released as part of `v0.15.0`: the PR allows setting an env variable (`ELECTRSD_EXE`) to use a custom electrsd binary, which can be useful when the one that is downloaded automatically doesn't work for whatever reason.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  LLFourn:
    ACK 1803f5e
  notmandatory:
    ACK 1803f5ea8a7a2f8f9ebdfa520baad91f84bd6ba0

Tree-SHA512: 01d84763a5acf3aa1686b91ba7cb0c7ec3a0ca6c7b9bac29aa74a72f54ed31c476b7a8b0f8c6c8a8ccf530ad8a19e90e144ac4cacbe436699ef9e319b5732f1c
2022-03-17 10:50:41 -05:00
LLFourn
559cfc4373
Fix pre-segwit inputs with esplora 2022-03-17 10:37:03 -05:00
Steve Myers
1e9a684b54
Merge bitcoindevkit/bdk#571: Fix pre-segwit inputs with esplora
52bc63e48f5d16cb03c8a58f7b0bd07cbb058dde Fix pre-segwit inputs with esplora (LLFourn)

Pull request description:

  Unexpectedly pre-segwit inputs have an empty JSON witness field in esplora.

  Fixes #570

  * [x] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  notmandatory:
    ACK 52bc63e48f5d16cb03c8a58f7b0bd07cbb058dde
  afilini:
    ACK 52bc63e48f5d16cb03c8a58f7b0bd07cbb058dde

Tree-SHA512: 1da82aeb2739111e1a516d94c79fe7d7c7879526a8cd780dcd63ff5ae9ccb1bed4eb20e5c575a45e37b6d1818d63ce6d3812e7b9ae34ebb02bc190a47b9750f8
2022-03-17 10:06:05 -05:00
LLFourn
52bc63e48f
Fix pre-segwit inputs with esplora 2022-03-16 10:39:53 +11:00
Alekos Filini
9a6db15d26
Merge bitcoindevkit/bdk#515: Never delete spent utxos from the database
f2f0efc0b3367abf40e33b84fc577fb11f625b04 Never delete spent utxos from the database (Daniela Brozzoni)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  A `is_spent` field is added to LocalUtxo; when a txo is spent we set
  this field to true instead of deleting the entire utxo from the
  database.
  This allows us to create txs double-spending txs already in blockchain.
  Listunspent won't return spent in mempool utxos, effectively excluding them from the coin selection and balance calculation
  Fixes #414

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've updated `CHANGELOG.md`
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    Re-ACK f2f0efc

Tree-SHA512: 7984b69c56b3b12746c2301072d637dea1346730aa132f1ea67c5bd8bf685bd557fc7cbdc2fc1185e63c71db07d36cd979514921b2c83c55737cd4b96102377e
2022-03-14 16:06:23 +01:00
Steve Myers
52bcd105eb
Bump version to 0.17.0-rc.1 2022-03-10 17:01:44 -06:00
Alekos Filini
1803f5ea8a
Update electrsd to v0.15 2022-03-10 12:03:15 +01:00
Daniela Brozzoni
f2f0efc0b3
Never delete spent utxos from the database
A `is_spent` field is added to LocalUtxo; when a txo is spent we set
this field to true instead of deleting the entire utxo from the
database.
This allows us to create txs double-spending txs already in blockchain.
Listunspent won't return spent utxos, effectively excluding them from the
coin selection and balance calculation
2022-03-10 11:58:23 +01:00
Steve Myers
3e4678d8e3
Merge bitcoindevkit/bdk#535: Remove blockchain from wallet
0cc4700bd67be84bb5cb0814bf5c8aa9fc3f3cdc Fix typo in CHANGELOG and doc in wallet/mod.rs (Steve Myers)
660faab1e20defe86a7baf132e52928f538b9cbb Fix typo in CHANGELOG (LLFourn)
45767fcaf7c65d5020f99fdc35c147acd6e8d037 Remove max_addresses sync param (LLFourn)
fbb50ad1c886a9cb716146fa823558d7d655c7b7 apply doc suggestions from @notmandatory (Lloyd Fournier)
035307ef54ebc330b1760bbdd17bdab3b167cfeb [rpc] Filter out unrelated transactions (LLFourn)
c0e75fc1a8560cdacf705ff60ef8833befd8280c Split get_tx into its own trait (LLFourn)
dcd90f8b61287164dae60f039848d3605eab8616 Restore but depreciate new_offline (LLFourn)
410a51355bb47dbf3401cbe6f19546255c6721e0 Add SyncOptions as the second argument to Wallet::sync (LLFourn)
326bfe82a89eaa79acf90c34442234c7e53e1caf Remove Blockchain from wallet (LLFourn)

Pull request description:

  While trying to finish #490 I thought that it'd be better to try the idea of getting rid of a lot of the async macros and just having tow different traits for sync and async stuff. While trying to do that I felt that this needed to be done first.

  The goal of this change is to decouple the wallet from the blockchain trait. A wallet is something that keeps track of UTXOs and transactions (and can sign things). The only reason it should need to talk to the blockchain is if doing a `sync`. So we remove all superfluous calls to the blockchain and precisely define the requirements for the blockchain to be used to sync with two new traits: `WalletSync` and `GetHeight`.

  1. Stop requesting height when wallet is created
  2. `new_offline` is just `new` now.
  3. a `WalletSync + GetHeight` is now the first argument to `sync`.
  4. `SyncOptions` replaces the existing options to `sync` and allows for less friction when making breaking changes in the fuutre (no more noop_progress!).
  5. We `Box` the `Progress` now to avoid type parameters
  6. broadcast has been removed from `Wallet`. You just use the blockchain directly to broadcast now.

  ### Notes to the reviewers

  This needs #502 before it can be merged but can reviewed now.
  Be on the look up for stale documentation from this change.
  Our doc build looks broken because of ureq or something.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing
  * [x] I've updated `CHANGELOG.md`

Top commit has no ACKs.

Tree-SHA512: a8f3e21e45359be642b1f30d4ac1ba74785439e1b770dbeab0a5a4b8aab1eef4bb6b855aea4382e289257bc890fa713ca832a8b6c9655f7a59e96d412b4da3e6
2022-03-09 11:15:52 -06:00
Steve Myers
0cc4700bd6
Fix typo in CHANGELOG and doc in wallet/mod.rs 2022-03-08 20:02:47 -06:00
LLFourn
660faab1e2
Fix typo in CHANGELOG 2022-03-08 14:00:29 +11:00
LLFourn
45767fcaf7
Remove max_addresses sync param
You can do this with ensure_addresses_cached if you really want to.
2022-03-07 10:44:41 +11:00
LLFourn
d03aa85108
Merge branch 'master' into remove-blockchain-from-wallet 2022-03-03 13:13:45 +11:00
Steve Myers
adf7d0c126
Merge bitcoindevkit/bdk#537: refactor wallet address caching into its own public method
edf2f0ce06d27a1434202b79306cd1e998b5614c refactor wallet address caching into its own public method for offline wallet use (a5an0)

Pull request description:

  ### Description

  Currently, the only way to ensure that a wallet's internal database has addresses loaded and cached is through `Wallet::sync`: that function generates and caches up to a number of addresses if they aren't already in the database, and then uses the wallet's blockchain client to sync those addresses. If you are using an offline wallet, there is no mechanism to ensure that the database has addresses loaded. This is a problem for usecases like an offline wallet being used as a multisig signer and wanting to validate change addresses as `Wallet::is_mine` will only work properly if the owned-address is loaded in the database.

  This PR takes the address caching functionality out of `Wallet::sync` and puts it in a new public method that is available to offline wallets. `Wallet::sync` uses this method internally.

  ### Checklists

  #### All Submissions:

  * [X] I've signed all my commits
  * [X] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [X] I ran `cargo fmt` and `cargo clippy` before committing
  * [X] I've added docs for the new feature
  * [X] I've updated `CHANGELOG.md`

Top commit has no ACKs.

Tree-SHA512: 8ddc58d71457163bb20ff663ac508feb4e77000688161b63841a94db30b3f29f60f35fa2467bd99546123148873e3aed11e2f13ae6cbceda6605b83c227d9079
2022-03-01 21:28:31 -08:00
Steve Myers
4291f84d79
Merge branch 'master' into offline-address-cache 2022-03-01 21:00:56 -08:00
Steve Myers
f0188f49a8
Merge bitcoindevkit/bdk#522: Add API for internal addresses
022256c91ac7a4d9324a1a7925394a948feec808 Fix comment on peek_address (Lloyd Fournier)
00f0901bac805360695d0c492df8fa809918863e Add API for internal addresses (LLFourn)

Pull request description:

  There are good reasons for applications to need to get internal
  addresses too. For example creating a transactions that splits an output
  into several smaller ones.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [x] I've added tests for the new feature
  * [x] I've added docs for the new feature
  * [x] I've updated `CHANGELOG.md`

ACKs for top commit:
  notmandatory:
    ACK 022256c91ac7a4d9324a1a7925394a948feec808

Tree-SHA512: 0ead6669c9974332708ae6cba1a5be69cd4b3b6c7a21896efdce178d4406265ba072e1cf02d1913178d0a551f3b276d99b75676c632833964f87484e262a61b1
2022-03-01 20:54:07 -08:00
a5an0
edf2f0ce06
refactor wallet address caching into its own public method for offline wallet use 2022-02-25 12:15:08 -05:00
thunderbiscuit
364ad95e85
Fix hierarchy of headers on docs landing page 2022-02-24 10:48:47 -05:00
Lloyd Fournier
fbb50ad1c8
apply doc suggestions from @notmandatory
Co-authored-by: Steve Myers <github@notmandatory.org>
2022-02-24 20:59:21 +11:00
LLFourn
035307ef54
[rpc] Filter out unrelated transactions
For some reason while doing the "remove blockchain from wallet PR" I
changed the tests around in what I thought was a benign way. But it
meant (apparently) that both parties "test_sync_double_receive" were
using the same "blockchain". This meant that when the blockchain was RPC
they both imported their addresses to it and got each other's results
when syncing. This bugged out the sync and this commit fixes that.
2022-02-24 20:39:00 +11:00
LLFourn
c0e75fc1a8
Split get_tx into its own trait
to make supporting verify_tx easier
2022-02-24 20:39:00 +11:00
LLFourn
dcd90f8b61
Restore but depreciate new_offline 2022-02-24 20:39:00 +11:00
LLFourn
410a51355b
Add SyncOptions as the second argument to Wallet::sync
The current options are awkward and it would be good if we could
introduce more in the future without breaking changes.
2022-02-24 20:39:00 +11:00
LLFourn
326bfe82a8
Remove Blockchain from wallet
Although somewhat convenient to have, coupling the Wallet with
the blockchain trait causes development friction and complexity.
What if sometimes the wallet is "offline" (no access to the blockchain)
but sometimes its online?
The only thing the Wallet needs the blockchain for is to sync.
But not all applications will even use the sync method and the sync
method doesn't require the full blockchain functionality.
So we instead pass the blockchain in when we want to sync.

- To further reduce the coupling with blockchain I removed the get_height call from `new` and just use the height of the
last sync in the database.
- I split up the blockchain trait a bit into subtraits.
2022-02-24 20:39:00 +11:00
Steve Myers
b23a0747b5
Merge commit 'refs/pull/552/head' of github.com:bitcoindevkit/bdk 2022-02-23 14:10:28 -08:00
Lloyd Fournier
022256c91a
Fix comment on peek_address
Co-authored-by: Raj <36541669+rajarshimaitra@users.noreply.github.com>
2022-02-23 09:28:13 +11:00
LLFourn
00f0901bac
Add API for internal addresses
There are good reasons for applications to need to get internal
addresses too. For example creating a transactions that splits an output
into several smaller ones.
2022-02-23 09:28:08 +11:00
Steve Myers
19f028714b
Merge bitcoindevkit/bdk#502: Refactor verification logic
1999d97aeb3d97ee24a9b59a2f1453a26943b595 Remove `verify` flag from `TransactionDetails` via new MIGRATIONS (Steve Myers)
0195bc0636d9a58013f0cbc3781d213b0cfc1509 Update CHANGELOG (rajarshimaitra)
1d7ea89d8a792013212b1d269895b02fe3b410bd Refactor sync time verification (rajarshimaitra)
b05ee78c7335f7e3a1593dc4ff7686e6f72ff5c0 Remove verifcation flag from compact_filters (rajarshimaitra)
53c30b0479c74dde17cd27f8eac7f540e492067d Add verification tests in CI (rajarshimaitra)
6a09075d1a87509e9117eab727132efdf8ea6e1d Remove verify flag from sqlite DB (rajarshimaitra)
61a95d0d15b9944e8b5d13db64ef6ffd9a8d6e29 Update changelog (rajarshimaitra)
08f312a82f889f6bf5dfedfaa565ac2cb59683ae Remove `verify` flag from `TransactionDetails` (rajarshimaitra)
acbf0ae08e0732579652aece9bc48169351884cf Add sync verification for `esplora` (rajarshimaitra)
4761155707a819c4db437e71a36621a027d5302a Add sync verification in `electrum` (rajarshimaitra)
98a3b3282a0ff59bbdf900adc765f6912d1975c1 Remove sync verification (rajarshimaitra)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  As discussed in https://github.com/bitcoindevkit/bdk/issues/498 and also in team call,
   - default verification from wallet sync is removed
   - `verify_tx` refactored as an wallet API
   - in `sync` verification added for electrum and esplora backends, gated by `verify` flag.
   - `verify` flag is removed from `TransactionDetails`.

  ### Notes to the reviewers

  I haven't looked into `comapct_filters` to see how verification can fit there, but that will probably be required in future.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Wallet API change:

  * [x] I've updated `CHANGELOG.md`

Top commit has no ACKs.

Tree-SHA512: 72e307008a137468d96d5c2a6ec804b18fa52363606f3c978208ae5dc22973a7f0aa37488e9bb98dde88409a12d59cc5f00c675d2d408e57e661bf6210bee67b
2022-02-21 19:23:49 -08:00
Steve Myers
ad65dd5c23
Merge branch 'master' into verifcation-refactor 2022-02-21 17:47:09 -08:00
Steve Myers
1999d97aeb
Remove verify flag from TransactionDetails via new MIGRATIONS 2022-02-21 17:31:48 -08:00
rajarshimaitra
0195bc0636
Update CHANGELOG 2022-02-21 17:31:46 -08:00
Alekos Filini
760a6ca1a1
Merge bitcoindevkit/bdk#551: Fix sent calculation in the RPC backend
bfd0d13779003f11fa099a0b665052c18ce6e500 [blockchain] Fix `sent` calculation in the RPC backend (Daniela Brozzoni)
128c37595c5cfeacdb8e999da5795a9aa28ad67b [tests] Pass tx inputs to the testutils macro (Daniela Brozzoni)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### Bugfixes:

  * [x] I've added tests to reproduce the issue which are now passing

ACKs for top commit:
  afilini:
    ACK bfd0d13779003f11fa099a0b665052c18ce6e500

Tree-SHA512: 1c214819c5dc1f1c30b1c6ef18a44a3013d587651890b26aecfc5203d128173fd91497337186bbee6934f77d3cfe1686e67b83ca6fe6e47b4c1d4b1dbcc656ee
2022-02-20 11:20:09 +01:00
Steve Myers
552765bb58
Bump version to 0.16.2-dev 2022-02-19 13:10:04 -08:00
Steve Myers
f3e479fa7f
Bump version to 0.16.1 2022-02-19 12:46:17 -08:00
Steve Myers
5698c683c6
Pin tokio version to ~1.14 2022-02-19 11:33:57 -08:00
Steve Myers
a83aa0461c
[ci] Pin nightly docs workflow rust version to nightly-2022-01-25 2022-02-19 11:33:01 -08:00
Daniela Brozzoni
bfd0d13779
[blockchain] Fix sent calculation in the RPC backend
We used to consider a tx input as ours if we had the
tx that creates it in the database.
This commit actually checks if an input is ours before adding
its value to the `sent` field.
2022-02-18 12:54:51 +01:00
Daniela Brozzoni
128c37595c
[tests] Pass tx inputs to the testutils macro 2022-02-18 12:54:51 +01:00
Steve Myers
5c5bb7833c
Merge bitcoindevkit/bdk#550: Pin tokio version to ~1.14
b04bb590f385db349f8dc70cc169674b530c4205 Pin tokio version to ~1.14 (Steve Myers)

Pull request description:

  ### Description

  The `tokio` project recently changed their MSRV to `1.49.0`. This PR will pin the `tokio` dependency version to `~1.14` which is prior to their MSRV increase.

  ### Notes to the reviewers

  The LDK team took this approach for their `tokio` dev-dependency, see https://github.com/lightningdevkit/rust-lightning/pull/1315.

  As long as `tokio` backports bug fixes  to`1.14.x` releases this should be safe. If we need any new features we can revisit this decision.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've updated `CHANGELOG.md`

ACKs for top commit:
  LLFourn:
    ACK b04bb590f385db349f8dc70cc169674b530c4205

Tree-SHA512: a44d61e0d644900837b5a99e0f2b9e5706cf9932f7430c3a2c8adbff37c82e4a6a545849fe031da748fcd8c8a70f5266d6974c5b6634b50af5eae148b9a26635
2022-02-17 18:09:58 -08:00
Steve Myers
b04bb590f3
Pin tokio version to ~1.14 2022-02-17 11:47:28 -08:00
Alekos Filini
0efbece41a
Merge bitcoindevkit/bdk#542: Implement XKeyUtils on InnerXKey
b6fe01c4668b1b6737e5e24ae2282f0f55da39cd Implement XKeyUtils on InnerXKey (Gianluca Acerbis)

Pull request description:

  Closes #395

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature
  * [ ] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  danielabrozzoni:
    ACK b6fe01c4668b1b6737e5e24ae2282f0f55da39cd - the code looks good to me, I tested locally and all tests pass
  notmandatory:
    ACK b6fe01c4668b1b6737e5e24ae2282f0f55da39cd

Tree-SHA512: 00a3ed9532a0589ac4be55a7d0c6ac5251f03f716adb2086eb934d9a9b04bcb7fd95aaeba38b68c5c90876644ce53ac5e39a912a4096e789887342f8727ae434
2022-02-14 20:16:10 +01:00
Gianluca Acerbis
b6fe01c466
Implement XKeyUtils on InnerXKey
Closes #395
2022-02-12 17:14:07 +01:00
rajarshimaitra
1d7ea89d8a
Refactor sync time verification
Instead of verifying txs at sync time in every backend, its moved to
script_sync to by default be available to any backend.
2022-02-09 16:59:53 +05:30
rajarshimaitra
b05ee78c73
Remove verifcation flag from compact_filters 2022-02-09 12:30:32 +05:30
rajarshimaitra
53c30b0479
Add verification tests in CI 2022-02-09 12:30:32 +05:30
rajarshimaitra
6a09075d1a
Remove verify flag from sqlite DB 2022-02-09 12:30:32 +05:30
rajarshimaitra
61a95d0d15
Update changelog 2022-02-09 12:30:25 +05:30
rajarshimaitra
08f312a82f
Remove verify flag from TransactionDetails 2022-02-09 12:29:47 +05:30
rajarshimaitra
acbf0ae08e
Add sync verification for esplora 2022-02-09 12:29:47 +05:30
rajarshimaitra
4761155707
Add sync verification in electrum 2022-02-09 12:29:47 +05:30
rajarshimaitra
98a3b3282a
Remove sync verification
The default sync verification is removed from wallet module.
By default sync time verification only makes sense for `electrum` and
`esplora` backend as they are usually untrusted 3rd party services.

script verification for transaction is costly, so removing default
script verification optimizes performance.
2022-02-09 12:29:46 +05:30
Alekos Filini
e745122bf5
Merge bitcoindevkit/bdk#539: [ci] Pin nightly docs workflow rust version to nightly-2022-01-25
07c270db03bac07604911e6bd253c18713de0ab0 [ci] Pin nightly docs workflow rust version to nightly-2022-01-25 (Steve Myers)

Pull request description:

  ### Description

  Pin nightly docs workflow rust version to `nightly-2022-01-25` to fix #538 .

  ### Notes to the reviewers

  The nightly docs should be changed to the `stable` version once it supports `feature(doc_cfg)`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

  #### Bugfixes:

  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  afilini:
    ACK 07c270db03bac07604911e6bd253c18713de0ab0

Tree-SHA512: a8e5de051e1963c10d686d5cb5d1785e20f6cd322b9bfcf2d2f5c381d9124a9b8518671dfbedb11550bdfa66c8c64ad505c7e1604e2bfe23600de39cb20467dd
2022-02-07 11:01:48 +01:00
Steve Myers
07c270db03
[ci] Pin nightly docs workflow rust version to nightly-2022-01-25 2022-02-04 08:55:00 -06:00
Alekos Filini
375674ffff
Merge bitcoindevkit/bdk#532: Release/0.16.0
fcf422752bb440f08aa9b5384297bbb06bca8cb3 Fix 0.16.0 changelog, include WIF fix (Steve Myers)
6fb42fdea10fcff9a45dd07f966ec4f3746c369d Bump version to 0.16.1-dev (Steve Myers)
3f65e8c64bd620685e40d3b54a0893993513441b Bump version to 0.16.0 (Steve Myers)
3f0101d317ec5a1d0df60c274741ee380563d7fe Bump version to 0.16.0-rc.1 (Steve Myers)

Pull request description:

  ### Description

  Merge the 0.16.0 release branch back into the master branch.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  afilini:
    ACK fcf422752bb440f08aa9b5384297bbb06bca8cb3

Tree-SHA512: 7a1e9297f4e93284e5e57124c7afe37d1fbef1da48375b310aad7fe8556be6bba00c3263e9d15540209fc99ba5e928d3fc751d0df6592c2af871599f00941a7b
2022-01-27 10:44:57 +01:00
Steve Myers
fcf422752b
Fix 0.16.0 changelog, include WIF fix 2022-01-21 14:27:36 -06:00
Steve Myers
6fb42fdea1
Bump version to 0.16.1-dev 2022-01-21 14:27:02 -06:00
Steve Myers
3f65e8c64b
Bump version to 0.16.0 2022-01-21 12:39:27 -06:00
Steve Myers
3f0101d317
Bump version to 0.16.0-rc.1 2022-01-12 18:01:32 +01:00
Steve Myers
b1346d4ccf
Merge bitcoindevkit/bdk#505: Using dust value from rust-bitcoin in `is_dust`
5ac51dfe74c51c83fe270570d7ffc50888cf554f fix and test is_dust (James Taylor)
a0c140bb29ab37103e4a24d296ac6fcea91da69e add doc comment for IsDust trait (James Taylor)
bf5994b14ade1fc0c37d3e3cda6946c26ceea631 fixed fee in test, removed unnecessary comment (James Taylor)
ca682819b396c44c9139086b1537d32b212499a1 using dust value from rust-bitcoin (James Taylor)

Pull request description:

  ### Description

  This PR aims to fix #472 . We can retrieve the dust value for a given ``bitcoin::blockdata::script::Script``, so I adjusted the ``is_dust`` function within the ``IsDust`` trait to receive such a ``&Script``. Thus, the ``is_dust`` function can make the proper comparison.
  Let me know if you think that there could be a better interface than this.

  Furthermore, because this new ``is_dust`` function provides a tighter upper bound on Bitcoin Core's ``GetDustThreshold()``, it actually invalidated a test. In the test, the drain output for a transaction was no longer considered dust and no longer included in the fee. Instead, the drain output was kicked back to the sender, invalidating the asserts in line 3436, 3437 and 3441 in ``src/wallet/mod.rs``. I increased the ``FeeRate`` in the test just enough that the drain output would be small enough to considered dust again and included in the total fee.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  afilini:
    ACK 5ac51dfe74c51c83fe270570d7ffc50888cf554f
  notmandatory:
    re ACK 5ac51dfe74c51c83fe270570d7ffc50888cf554f

Tree-SHA512: addf38fe065de581ddfcd3b4e6db92cd35d5bfa8cac78bd08c01f7a01292724a203ef59b09f3f5cd8e0fa0bb6d89efe72afda36efc11ded0424fc8105326af3f
2022-01-12 17:49:16 +01:00
Steve Myers
5107ff80c1
Merge bitcoindevkit/bdk#495: Disable reqwest's default features
380a4f2588cf9800bde739eb3ba58ca67b785291 Disable reqwest's default features (Thomas Eizinger)

Pull request description:

  ### Description

  By default, reqwest uses openssl for TLS. Any consumer wanting to use
  rustls will thus pull in unnecessary dependencies.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * ~[ ] I've added tests for the new feature~
  * ~[ ] I've added docs for the new feature~
  * [x] I've updated `CHANGELOG.md`

  #### Bugfixes:

  * ~[ ] This pull request breaks the existing API~
  * ~[ ] I've added tests to reproduce the issue which are now passing~
  * ~[ ] I'm linking the issue being fixed by this PR~

ACKs for top commit:
  notmandatory:
    ACK 380a4f2588cf9800bde739eb3ba58ca67b785291

Tree-SHA512: 17827fdd7656a1e97b4cc302bc3c4907a8493505c798fafd9b15fde12531a32cf60e7d63e878eb2001d6b3e95f7ae3da730e227eb85c73d9de55b56456cfb3a0
2022-01-12 09:16:24 +01:00
James Taylor
5ac51dfe74
fix and test is_dust 2022-01-11 18:21:35 -05:00
Steve Myers
04d58f7903
Merge commit 'refs/pull/508/head' of github.com:bitcoindevkit/bdk 2022-01-11 10:08:33 +01:00
Thomas Eizinger
380a4f2588
Disable reqwest's default features
By default, reqwest uses openssl for TLS. Any consumer wanting to use
rustls will thus pull in unnecessary dependencies. To make getting started
with bdk and reqwest easier, we add a `reqwest-default-tls` feature
that can be used to activate reqwest's `default-tls` feature. TLS is
necessary for the esplora integration. Adding this feature makes it possible
for people to use bdk with esplora without adding a reqwest dependency to
their manifest.
2022-01-10 13:57:22 +11:00
Steve Myers
9e30a79027
Fix CHANGELOG link for v0.15.0 2021-12-29 13:17:11 -08:00
Alekos Filini
fdb272e039
Merge bitcoindevkit/bdk#511: Fix nightly_docs.yml publish_docs 'Commit' step
947a9c29db7c7bb4855c84e70d986b9ab61339d6 Fix nightly_docs.yml publish_docs 'Commit' step (Steve Myers)

Pull request description:

  ### Description

  I forgot to fix in #503 the `nightly_docs.yaml` `publish_docs` `Commit` step to add new files for the path `./docs/.vuepress/public/docs-rs`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

ACKs for top commit:
  afilini:
    ACK 947a9c2

Tree-SHA512: d2bdbcb6cea46ec1949eba6f334acd5dbbe9b4b1323bb4713dc5d7f749666260ab05c29247c35f08c587b46d6bfb765c6a612c6522fd15211c84f7590f8c4748
2021-12-29 10:59:32 +01:00
Steve Myers
d2b6b5545e
Bump version to 0.15.1-dev 2021-12-23 10:40:42 -08:00
Steve Myers
db6ffb90f0
Merge commit 'refs/pull/510/head' of github.com:bitcoindevkit/bdk 2021-12-23 10:34:58 -08:00
Steve Myers
947a9c29db
Fix nightly_docs.yml publish_docs 'Commit' step 2021-12-23 10:23:11 -08:00
Alekos Filini
61ee2a9c1c
Merge commit 'refs/pull/504/head' of github.com:bitcoindevkit/bdk 2021-12-23 12:24:52 +01:00
Alekos Filini
44e4c5dac5
Merge commit 'refs/pull/509/head' of github.com:bitcoindevkit/bdk 2021-12-23 12:22:09 +01:00
Alekos Filini
e09aaf055a
Add a custom logo to our docs
As suggested in #497, add our logo to the docs as well
2021-12-23 11:37:41 +01:00
Alekos Filini
c40898ba08
Merge commit 'refs/pull/503/head' of github.com:bitcoindevkit/bdk 2021-12-23 11:34:34 +01:00
Steve Myers
2f98db8549
Add back old logo to static/bdk.svg
This is required so that old releases of bdk on crates.io won't show a
broken image link. Should be replaced with SVG version of new logo.
2021-12-22 21:38:54 -08:00
Steve Myers
4d7c4bc810
Bump version to 0.15.0 2021-12-22 21:10:27 -08:00
James Taylor
a0c140bb29
add doc comment for IsDust trait 2021-12-22 01:50:17 -05:00
James Taylor
bf5994b14a
fixed fee in test, removed unnecessary comment 2021-12-19 18:37:05 -05:00
James Taylor
ca682819b3
using dust value from rust-bitcoin 2021-12-19 02:55:24 -05:00
mcroad
ee41d88f25
Test WIF from BIP39 words has correct network 2021-12-18 15:34:18 -06:00
mcroad
beb1e4114d
Add fix to changelog 2021-12-18 15:13:09 -06:00
mcroad
af047f90db
Set the correct inner private_key network 2021-12-18 15:10:25 -06:00
mcroad
d01ec6d259
Add test to ensure WIF uses the correct network 2021-12-18 15:08:16 -06:00
Alekos Filini
77bce06caf
Update logo 2021-12-18 15:17:45 +01:00
Steve Myers
98c26a1ad9
Bump version to 0.15.0-rc.1 2021-12-17 21:41:06 -08:00
Steve Myers
1a907f8a53
[ci] Fix publish_docs job 2021-12-17 21:28:39 -08:00
Steve Myers
e82edbb7ac
Merge bitcoindevkit/bdk#501: Only run clippy for the stable rust version
57a1185aef82718b8e6ad1272237f4d8f644fdc2 Only run clippy for the stable rust version (Steve Myers)

Pull request description:

  ### Description

  It was decided during the team call today (2021-12-14)  to only run clippy for the stable rust version.

  ### Notes to the reviewers

  This is required to fix the below build issues when running clippy on rust version 1.46.0.

  ```shell
  cargo clippy --all-targets --features async-interface --no-default-features -- -D warnings
  ```

  ```text
  ...

  Checking bitcoincore-rpc v0.14.0
  error: unknown clippy lint: clippy::no_effect_underscore_binding
    --> src/blockchain/mod.rs:88:1
     |
  88 | #[maybe_async]
     | ^^^^^^^^^^^^^^
     |
     = note: `-D clippy::unknown-clippy-lints` implied by `-D warnings`
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unknown_clippy_lints
     = note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)

  error: unknown clippy lint: clippy::no_effect_underscore_binding
     --> src/blockchain/mod.rs:220:1
      |
  220 | #[maybe_async]
      | ^^^^^^^^^^^^^^
      |
      = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unknown_clippy_lints
      = note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
  ```

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: 3fe0d2829415c7276d5339e217cefba1255c14d6d73ec0a5eff2b8072d189ffef56088623ef75f84e400d3d05e546f759b8048082b467a3738885796b3338323
2021-12-16 09:30:49 -08:00
Steve Myers
57a1185aef
Only run clippy for the stable rust version 2021-12-16 09:12:43 -08:00
Steve Myers
64e88f0e00
Merge bitcoindevkit/bdk#492: bump electrsd dep to 0.13
f7f9bd2409d51354698aa1f24bccba8ca429f279 bump electrsd dep to 0.13 (Riccardo Casatta)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  bump electrsd dep to 0.13, close #491

ACKs for top commit:
  rajarshimaitra:
    ACK f7f9bd2409
  notmandatory:
    utACK f7f9bd24

Tree-SHA512: 89a8094387896c9296e2f0120d7a2c7419e979049a12fc9a6ae7fe1810b75af43338db235887dd9054a6b52e400491b77f8e006f61451da54aca9635098ab342
2021-12-01 09:34:15 -08:00
Riccardo Casatta
f7f9bd2409
bump electrsd dep to 0.13 2021-12-01 08:45:32 +01:00
Steve Myers
68a3d2b1cc
Merge bitcoindevkit/bdk#487: Use "Description" instead of "Descriptive Title" in SoB Issue Template
084ec036a53c94b4a3f7a7e9d6abd7842d99a939 Use "Description" instead of "Descriptive Title" (rajarshimaitra)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  The `Descriptive Title` part is already in the issue title, and we can use `Description` in the issue body.

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

ACKs for top commit:
  thunderbiscuit:
    ACK 084ec03.
  notmandatory:
    ACK 084ec036a53c94b4a3f7a7e9d6abd7842d99a939

Tree-SHA512: 2fc365066849033cce056a46bc9e8ab2d931aa45fd2799ebebe3e07bb789c458491ebf2c05e5868bdff63f60dec0657043f3374135dcfbc79a1f89a2562b1883
2021-11-30 16:21:09 -08:00
Steve Myers
aa13186fb0
Merge bitcoindevkit/bdk#478: Fix typos in comments
7f8103dd762572f8b0f01514d0c32723d27c61e9 Fix typos in comments (thunderbiscuit)

Pull request description:

  ### Description

  This PR fixes a bunch of small typos in comments. I'm getting acquainted with the codebase and found a few typos just by chance, and ended up going through it with an IDE searching for typos in all files.

  ### Notes to the reviewers

  To be clear, this PR _only addresses typos that are within comments_.

  ### Checklists

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK 7f8103dd762572f8b0f01514d0c32723d27c61e9

Tree-SHA512: eb3f8f21cbd05de06292affd9ef69c21b52022dfdf25c562c8f4d9c9c011f18175dff0c650cb7efcfb2b665f2af80d9a153be3d12327c47796b0d00bfd5d9803
2021-11-30 16:19:53 -08:00
Steve Myers
02980881ac
Merge bitcoindevkit/bdk#473: release/0.14.0
fed4a597284d20cbd69e9c5be5e4586623f70d59 Bump version to 0.14.1-dev (Steve Myers)
c175dd2aae10b0a48430b58e40f0b66fde4bdc48 Bump version to 0.14.0 (Steve Myers)
6b1cbcc4b71c3ec4aa2abb3ab6836f86dbf80c34 Bump version to 0.14.0-rc.1 (Steve Myers)

Pull request description:

  ### Description

  Merge the 0.14.0 bdk release into the master branch.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

Top commit has no ACKs.

Tree-SHA512: 0a897988c47f56e24b7e831cb45ff348b5637ca1a172555e9456539f5b75f263007421d63820b20737bcddb6f4c8077271471ea830e500ca6f88b902502f8186
2021-11-30 16:16:37 -08:00
Steve Myers
69b184a0a4
Merge branch 'master' into release/0.14.0 2021-11-30 15:41:41 -08:00
rajarshimaitra
084ec036a5
Use "Description" instead of "Descriptive Title" 2021-11-30 12:26:36 +05:30
Steve Myers
c1af456e58
Merge bitcoindevkit/bdk#475: Fix typo in check_miniscript method declaration and use
b9fc06195beab8eab4c4c6224dc069ebd5106729 Fix typo in check_miniscript method declaration and use (thunderbiscuit)

Pull request description:

  ### Description

  This PR renames the `check_minsicript()` method on the `CheckMiniscript` trait  and its uses throughout the codebase to `check_miniscript()`.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    ACK b9fc06195beab8eab4c4c6224dc069ebd5106729

Tree-SHA512: cc4406c653cb86f9b15e60c6f87b95c300784d6b2992abc98b3f2db4b02ce252304cc0ab2c638f080b0caf3889e832885eca19e2d6582a3557c8709311b69644
2021-11-29 14:13:26 -08:00
Steve Myers
d20b649eb8
Merge bitcoindevkit/bdk#477: Update issue templates
8534cd39433211733c325a73ca15fe7d569e8401 Update issue templates (Steve Myers)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  Add bug reporting issue template and template for proposing a "Summer of Bitcoin" project.

  ### Notes to the reviewers

  The SoB template is basically a copy of what Adi created but lightly formatted to work as github issue templates.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)

Top commit has no ACKs.

Tree-SHA512: 956f7833b7cc1daf4880f74be3886fb17508719af37a247065c463d3f95b1f058bad785590714c609b0e069fe00784bc71cfb0812a79a70c18a2b5bdb22aca6b
2021-11-29 10:27:46 -08:00
Steve Myers
fed4a59728
Bump version to 0.14.1-dev 2021-11-27 22:13:29 -08:00
Steve Myers
c175dd2aae
Bump version to 0.14.0 2021-11-27 21:07:12 -08:00
Steve Myers
8534cd3943
Update issue templates 2021-11-24 21:55:46 -08:00
Steve Myers
3a07614fdb
Merge bitcoindevkit/bdk#471: moving the function wallet_name_from_descriptor from blockchain/rpc.rs to wallet/mod.rs as it can be useful not only for rpc
2fc81141806ace8f12e5a019c0866f16fa8a02dc moving the function wallet_name_from_descriptor from blockchain/rpc.rs to wallet/mod.rs as it can be useful not only for rpc (Richard Ulrich)

Pull request description:

  ### Description

  Moving the function wallet_name_from_descriptor from rpc.rs to mod.rs
  Since the local cache for compact filters should be separate per wallet, this function can be useful not only for rpc.

  ### Notes to the reviewers

  I thought about renaming it, but waited for opinions on that.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    re-ACK  2fc8114

Tree-SHA512: d5732e74f7a54f54dde39fff77f94f12c611a419bed9683025ecf7be95cde330209f676dfc9346ebcd29194325589710eafdd1d533e8073d0662cb397577119f
2021-11-24 20:44:58 -08:00
Steve Myers
b2ac4a0dfd
Merge bitcoindevkit/bdk#461: Restructure electrum/esplora sync logic
9c5770831de58760066dbbb26c0785632dde4991 Make stop_gap a parameter to EsploraBlockchainConfig::new (LLFourn)
0f0a01a742448fa9db67752722fed7d1c028117b s/vin/vout/ (LLFourn)
1a64fd9c9595566366cfe96cc20d8ba2f4da1bd3 Delete src/blockchain/utils.rs (LLFourn)
d3779fac73321f41b82897e6ab69708c957212b2 Fix comments (LLFourn)
d39401162fb72a9a02999908ac0347685d8861a5 Less intermediary data states in sync (LLFourn)
dfb63d389b2804cb55da60de0d8fcad985d50e5c s/observed_txs/finished_txs/g (LLFourn)
188d9a4a8b502b3f681f4c83fd9933b9a952e42c Make variable names consistent (LLFourn)
5eadf5ccf9722aa331008304221e981d01bca1c1 Add some logging to script_sync (LLFourn)
aaad560a91872318890208c4b3d5cb73a63029a8 Always get up to chunk_size heights to request headers for (LLFourn)
e7c13575c88be4fce1f407eae3710cb06c5db039 Don't request conftime during tx request (LLFourn)
808d7d8463c56cbcda0bd55a5eba422cf5080ce7 Update changelog (LLFourn)
732166fcb689ad666eab02a4bb28c33018f7b819 Fix feerate calculation for esplora (LLFourn)
3f5cb6997f8bf0c889747badb9498a402ecf96a4 Invert dependencies in electrum sync (LLFourn)

Pull request description:

  ## Description

  This PR does dependency inversion on the previous sync logic for electrum and esplora captured in the trait `ElectrumLikeSync`. This means that the sync logic does not reference the blockchain at all. Instead the blockchain asks the sync logic (in `script_sync.rs`) what it needs to continue the sync and tries to retrieve it.

  The initial purpose of doing this is to remove invocations of `maybe_await` in the abstract sync logic in preparation for completely removing `maybe_await` in the future. The other major benefit is it gives a lot more freedom for the esplora logic to use the rich data from the responses to complete the sync with less HTTP requests than it did previously.

  ## List of changes

  - sync logic moved to `script_sync.rs` and `ElectrumLikeSync` is gone.
  - esplora makes one http request per sync address. This means it makes half the number of http requests for a fully synced wallet and N*M less requests for a wallet which has N new transactions with M unique input transactions.
  - electrum and esplora save less raw transactions in the database. Electrum still requests input transactions for each of its transactions to calculate the fee but it does not save them to the database anymore.
  - The ureq and reqwest blockchain configuration is now unified into the same struct. This is the only API change. `read_timeout` and `write_timeout` have been removed in favor of a single `timeout` option which is set in both ureq and reqwest.
  - ureq now does concurrent (parallel) requests using threads.
  - An previously unnoticed bug has been fixed where by sending a lot of double spending transactions to the same address you could trick a bdk Esplora wallet into thinking it had a lot of unconfirmed coins. This is because esplora doesn't delete double spent transactions from its indexes immediately (not sure if this is a bug or a feature). A blockchain test is added for this.
  - BONUS: The second commit in this PR fixes the feerate calculation for esplora and adds a test (the previous algorithm didn't work at all). I could have made a separate PR but since I was touching this file a lot I decided to fix it here.

  ## Notes to the reviewers

  - The most important thing to review is the the logic in `script_sync.rs` is sound.
  - Look at the two commits separately.
  - I think CI is failing because of MSRV problems again!
  - It would be cool to measure how much sync time is improved for your existing wallets/projects. For `gun` the speed improvements for modest but it is at least hammering the esplora server much less.
  - I noticed the performance of reqwest in blocking is much worse in this patch than previously. This is because somehow reqwest is not re-using the connection for each request in this new code. I have no idea why. The plan is to get rid of the blocking reqwest implementation in a follow up PR.

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits

ACKs for top commit:
  rajarshimaitra:
    Retested ACK a630685a0a

Tree-SHA512: de74981e9d1f80758a9f20a3314ed7381c6b7c635f7ede80b177651fe2f9e9468064fae26bf80d4254098accfacfe50326ae0968e915186e13313f05bf77990b
2021-11-24 19:51:09 -08:00
thunderbiscuit
7f8103dd76
Fix typos in comments 2021-11-23 14:09:54 -05:00
thunderbiscuit
b9fc06195b
Fix typo in check_miniscript method declaration and use 2021-11-23 13:25:24 -05:00
LLFourn
a630685a0a
Merge branch 'master' into sync_pipeline 2021-11-23 12:53:40 +11:00
Richard Ulrich
2fc8114180
moving the function wallet_name_from_descriptor from blockchain/rpc.rs to wallet/mod.rs as it can be useful not only for rpc 2021-11-22 08:15:47 +01:00
Steve Myers
6b1cbcc4b7
Bump version to 0.14.0-rc.1 2021-11-17 11:54:09 -08:00
Steve Myers
afa1ab4ff8
Fix blockchain_tests::test_send_to_bech32m_addr
Now works with latest released versions of rust-bitcoincore-rpc and
bitcoind. Once these crates are updated to support creating descriptor
wallets and add importdescriptors and bech32m support this test will
need to be updated.
2021-11-11 13:59:11 -08:00
Sandipan Dey
632422a3ab
Added wallet blockchain test to send to Bech32m address 2021-11-11 08:20:40 -08:00
Sandipan Dey
54f61d17f2
Added a wallet unit test to send to a Bech32m address 2021-11-11 08:20:38 -08:00
Alekos Filini
5830226216
[database] Wrap BlockTime in another struct to allow adding more
fields in the future
2021-11-10 12:30:42 +01:00
Alekos Filini
2c77329333
Rename ConfirmationTime to BlockTime 2021-11-10 12:30:38 +01:00
Alekos Filini
3e5bb077ac
Update CHANGELOG.md 2021-11-10 12:30:33 +01:00
Alekos Filini
7c06f52a07
[wallet] Store the block height and timestamp after syncing
Closes #455
2021-11-10 12:30:02 +01:00
Alekos Filini
12e51b3c06
[wallet] Expose an immutable reference to a wallet's database 2021-11-10 12:29:58 +01:00
Alekos Filini
2892edf94b
[db] Add the last_sync_time database entry
This will be used to store the height and timestamp after every sync.
2021-11-10 12:29:47 +01:00
LLFourn
9c5770831d
Make stop_gap a parameter to EsploraBlockchainConfig::new 2021-11-10 09:07:36 +11:00
LLFourn
0f0a01a742
s/vin/vout/ 2021-11-10 09:07:36 +11:00
LLFourn
1a64fd9c95
Delete src/blockchain/utils.rs 2021-11-10 09:07:36 +11:00
LLFourn
d3779fac73
Fix comments 2021-11-10 09:07:36 +11:00
LLFourn
d39401162f
Less intermediary data states in sync
Use BTrees to store ordered sets rather than HashSets -> VecDequeue
2021-11-10 09:07:36 +11:00
LLFourn
dfb63d389b
s/observed_txs/finished_txs/g 2021-11-10 09:07:36 +11:00
LLFourn
188d9a4a8b
Make variable names consistent 2021-11-10 09:07:36 +11:00
LLFourn
5eadf5ccf9
Add some logging to script_sync 2021-11-10 09:07:36 +11:00
LLFourn
aaad560a91
Always get up to chunk_size heights to request headers for 2021-11-10 09:07:36 +11:00
LLFourn
e7c13575c8
Don't request conftime during tx request 2021-11-10 09:07:36 +11:00
LLFourn
808d7d8463
Update changelog 2021-11-10 09:07:34 +11:00
LLFourn
732166fcb6
Fix feerate calculation for esplora 2021-11-10 09:06:49 +11:00
LLFourn
3f5cb6997f
Invert dependencies in electrum sync
Blockchain calls sync logic rather than the other way around.
Sync logic is captured in script_sync.rs.
2021-11-10 09:06:49 +11:00
Riccardo Casatta
aa075f0b2f
fix after merge changing borrow of tx in broadcast 2021-11-09 15:37:18 +01:00
Riccardo Casatta
8010d692e9
Update CHANGELOG 2021-11-09 15:37:13 +01:00
Riccardo Casatta
b2d7412d6d
add test for add_data 2021-11-09 15:36:42 +01:00
Riccardo Casatta
fd51029197
add method add_data as a shortcut to create an OP_RETURN output, fix the dust check to consider only spendable output 2021-11-09 15:36:39 +01:00
Alekos Filini
711510006b
Merge commit 'refs/pull/464/head' of github.com:bitcoindevkit/bdk 2021-11-08 10:41:12 +01:00
Alekos Filini
d21b6e47ab
Merge commit 'refs/pull/458/head' of github.com:bitcoindevkit/bdk 2021-11-08 10:39:50 +01:00
rajarshimaitra
5922c216a1
Update WordsCount -> WordCount 2021-11-06 20:14:03 +05:30
rajarshimaitra
9e29e2d2b1
Update changelog 2021-11-06 20:13:45 +05:30
Alekos Filini
16e832533c
Merge commit 'refs/pull/462/head' of github.com:bitcoindevkit/bdk 2021-11-04 15:26:15 +00:00
Steve Myers
7f91bcdf1a
Merge commit 'refs/pull/453/head' of github.com:bitcoindevkit/bdk 2021-11-03 13:51:59 -07:00
rajarshimaitra
35695d8795
remove redundant backtrace dependency 2021-11-03 11:14:14 +05:30
rajarshimaitra
756858e882
update module doc 2021-11-03 11:14:13 +05:30
rajarshimaitra
d2ce2714f2
Replace tiny-bip39 with rust-bip39
Use rust-bip39 for mnemonic derivation everywhere.

This requires our own WordCount enum as rust-bip39 doesn't have
explicit mnemonic type definition.
2021-11-03 11:14:05 +05:30
rajarshimaitra
3b2b559910
Update codecov@v2 2021-11-02 15:21:37 +05:30
rajarshimaitra
3c8416bf31
update dependency
dependency updated from tiny-bip39 to rust-bip39
2021-10-31 20:29:11 +05:30
Steve Myers
f6f736609f
Bump version to 0.13.1-dev 2021-10-28 13:38:39 -07:00
Steve Myers
5cb0726780
Bump version to 0.13.0 2021-10-28 10:44:56 -07:00
Steve Myers
8781599740
Switch back to rust-bitcoin/rust-bitcoincore-rpc 2021-10-27 13:53:58 -07:00
Steve Myers
ee8b992f8b
Update dev-dependencies electrsd to 0.12 2021-10-27 13:42:01 -07:00
Mariusz Klochowicz
3d8efbf8bf
Borrow instead of moving transaction when broadcasting
There's no need to take ownership of the transaction for a broadcast.
2021-10-27 21:51:55 +10:30
Alekos Filini
a2e26f1b57
Pin version of ureq to maintain our MSRV
(cherry picked from commit d75d221540a0d47b7538b456211f92cdb4d4da8c)
2021-10-26 16:15:13 -07:00
Alekos Filini
5f5744e897
Pin version of backtrace to maintain our MSRV
(cherry picked from commit 548e43d928d1492784dc465a28fa99b9ca263b9f)
2021-10-26 16:15:11 -07:00
Alekos Filini
e106136227
[ci] Update the stable version to 1.56
(cherry picked from commit a348dbdcfe2fa9abc92eab7286dde1177fef65bd)
2021-10-26 16:15:09 -07:00
Alekos Filini
d75d221540
Pin version of ureq to maintain our MSRV 2021-10-22 15:57:40 +02:00
Alekos Filini
548e43d928
Pin version of backtrace to maintain our MSRV 2021-10-22 15:57:36 +02:00
Alekos Filini
a348dbdcfe
[ci] Update the stable version to 1.56 2021-10-22 15:57:27 +02:00
Steve Myers
b638039655
Fix CHANGELOG for Unreleased, v0.13.0 2021-10-20 20:14:10 -07:00
Steve Myers
7e085a86dd
Bump version to 0.13.0-rc.1 2021-10-20 20:09:31 -07:00
Sudarsan Balaji
59f795f176
Make MemoryDatabase Send + Sync 2021-10-15 21:36:36 +05:30
Steve Myers
2da10382e7
Pin ahash version to 0.7.4 for sqlite feature
The `ahash` crate is used by the `sqlite` feature but the latest update (0.7.5)
breaks compatibility with our current MSRV 1.46.0. See also:
https://github.com/tkaitchuck/aHash/issues/99
2021-10-14 08:24:32 -07:00
Steve Myers
6d18502733
Merge commit 'refs/pull/443/head' of github.com:bitcoindevkit/bdk 2021-10-07 22:52:55 -07:00
Steve Myers
81b263f235
Merge commit 'refs/pull/445/head' of github.com:bitcoindevkit/bdk 2021-10-07 22:48:47 -07:00
rajarshimaitra
2f38d3e526
Update ChangeLog 2021-10-07 20:49:13 +05:30
rajarshimaitra
2ee125655b
Expose get_tx() method from DB to Wallet 2021-10-07 20:49:07 +05:30
Steve Myers
22c39b7b78
Fix cargo doc warning and missing sqlite feature 2021-09-30 16:11:42 -07:00
Steve Myers
18f1107c41
Update DEVELOPMENT_CYCLE release instructions 2021-09-30 13:39:40 -07:00
Steve Myers
763bcc22ab
Bump version to 0.12.1-dev 2021-09-30 13:39:39 -07:00
Steve Myers
9e4ca516a8
Bump version to 0.12.0 2021-09-30 11:42:21 -07:00
Steve Myers
b60465f31e
Bump bdk-macros version to 0.6.0 2021-09-30 11:24:01 -07:00
Steve Myers
1469a3487a
Downgrade tiny-bip39 to version < 0.8
This is required until BDK MSRV is changed to 1.51 or we replace
tiny-bip39 dependency.
2021-09-27 12:47:58 -07:00
Steve Myers
8c21bcf40a
Downgrade tiny-bip39 to version < 0.8
This is required until BDK MSRV is changed to 1.51 or we replace
tiny-bip39 dependency.
2021-09-26 20:01:58 -07:00
Steve Myers
c9ed8bdf6c
Bump version to 0.12.0-rc.1 2021-09-24 10:25:12 -07:00
Steve Myers
919522a456
Fix clippy warning 2021-09-23 18:57:55 -07:00
Steve Myers
678607e673
Move new CHANGELOG entries to Unreleased 2021-09-23 18:28:27 -07:00
John Cantrell
c06d9f1d33
implement sqlite database 2021-09-23 20:54:08 -04:00
Steve Myers
5a6a2cefdd
Merge commit 'refs/pull/442/head' of github.com:bitcoindevkit/bdk 2021-09-23 15:28:57 -07:00
Alekos Filini
3fe2380d6c
[esplora] Support proxies in EsploraBlockchain 2021-09-23 21:38:19 +02:00
Lucas Soriano del Pino
eea8b135a4
Activate miniscript/use-serde feature 2021-09-23 19:49:06 +10:00
Steve Myers
a685b22aa6
[ci] Change check-wasm job to use ubuntu-20.04 runner 2021-09-22 10:08:10 -07:00
LLFourn
c601ae3271
[fix-build] Fix version of zeroize_derive to 1.1.0 2021-09-22 11:01:37 +10:00
Riccardo Casatta
c23692824d
[rpc] rescan in chunks of 10_000 blocks 2021-09-17 15:19:52 +02:00
Steve Myers
46f7b440f5
Merge commit 'refs/pull/438/head' of github.com:bitcoindevkit/bdk 2021-09-16 11:03:52 -07:00
Steve Myers
562fde7953
Merge commit 'refs/pull/434/head' of github.com:bitcoindevkit/bdk 2021-09-16 08:45:53 -07:00
rajarshimaitra
9e508748a3
Update CI blockchain tests
(cherry picked from commit 10b53a56d71ca4a923464f9cd12b5738f280d84a)
2021-09-15 13:44:11 -07:00
rajarshimaitra
84b8579df5
Test refactor
- Fix esplora module level feature flag
- Move esplora blockchain tests to module, to cover for both variants

(cherry picked from commit 8d1d92e71e61f7c8094b3f3c8ed26b849cc8250b)
2021-09-15 13:44:09 -07:00
rajarshimaitra
7cb0116c44
Fix reqwest blockchain test
- add back await_or_block! to bdk-macros
- use await_or_block! in reqwest tests

(cherry picked from commit a41a0030dc212bc3685848c7aa5e9ce12c23720f)
2021-09-15 13:44:06 -07:00
rajarshimaitra
6e12468b12
Update Cargo.toml
- Changed to local bdk-macro
- Added back tokio
- Update esplora-reqwest and test-esplora feature guards

(cherry picked from commit 2459740f7218603447307b20bd3776dc14898a6e)
2021-09-15 13:44:04 -07:00
Alekos Filini
326b64de3a
[descriptor] Add a test for extract_policy() on pk_h() operands 2021-09-15 10:38:36 +02:00
Alekos Filini
5edf663f3d
[descriptor] Add an alias for and_or()
The descriptor syntax encodes it with `andor()`, without the underscore
2021-09-15 10:37:35 +02:00
Alekos Filini
e3dd755396
[descriptor] Fix pk_h() in the descriptor!() macro
Instead of accepting just a `DescriptorPublicKey` it now accepts
anything that implements `IntoDescriptorKey` like `pk_k()` does.
2021-09-15 10:37:33 +02:00
Alekos Filini
b500cfe4e5
[descriptor] Fix extract_policy() for descriptors with pk_h() 2021-09-15 10:37:30 +02:00
rajarshimaitra
10b53a56d7
Update CI blockchain tests 2021-09-14 11:29:29 +05:30
rajarshimaitra
8d1d92e71e
Test refactor
- Fix esplora module level feature flag
- Move esplora blockchain tests to module, to cover for both variants
2021-09-14 11:29:28 +05:30
rajarshimaitra
a41a0030dc
Fix reqwest blockchain test
- add back await_or_block! to bdk-macros
- use await_or_block! in reqwest tests
2021-09-14 11:29:28 +05:30
rajarshimaitra
2459740f72
Update Cargo.toml
- Changed to local bdk-macro
- Added back tokio
- Update esplora-reqwest and test-esplora feature guards
2021-09-14 11:29:28 +05:30
Steve Myers
5694b98304
Bump version to 0.11.1-dev 2021-09-04 11:43:24 -07:00
Steve Myers
aa786fbb21
Bump version to 0.11.0 2021-09-04 10:46:03 -07:00
Steve Myers
8c570ae7eb
Update version in src/lib.rs 2021-09-04 10:45:18 -07:00
Steve Myers
56a7bc9874
Update changelog 2021-09-04 10:44:44 -07:00
Steve Myers
dd4bd96f79
Merge commit 'refs/pull/428/head' of github.com:bitcoindevkit/bdk 2021-08-31 08:33:07 -07:00
rajarshimaitra
2caa590438
Use ureq with default features 2021-08-31 14:37:50 +05:30
Steve Myers
2a53cfc23f
Merge commit 'refs/pull/426/head' of github.com:bitcoindevkit/bdk 2021-08-30 12:41:25 -07:00
Steve Myers
cf1815a1c0
Bump version to 0.11.0-rc.1 2021-08-30 10:27:24 -07:00
Lucas Soriano del Pino
acf157a99a
Fix use statements in populate_test_db macro
- Use re-exported `bitcoin` so that users of the macro don't need to
depend on `bitcoin` directly.
- Add missing `use std::str::FromStr`.
2021-08-30 14:08:17 +10:00
Lucas Soriano del Pino
fb813427eb
Use re-exported bitcoin and miniscript in testutils macro
Otherwise users of the macro must depend on `bitcoin` and `miniscript`
directly, which defeats the point of re-exporting these crates in the
first place.
2021-08-30 13:48:34 +10:00
Steve Myers
721748e98f
Fix CHANGELOG after merging release/0.10.0 branch 2021-08-25 22:20:20 +02:00
Steve Myers
976e641ba6
Merge commit 'refs/pull/411/head' of github.com:bitcoindevkit/bdk 2021-08-25 21:55:43 +02:00
Thomas Eizinger
7117557dea
Add deprecation policy to CONTRIBUTING.md 2021-08-25 17:43:06 +02:00
Richard Ulrich
fa013aeb83
moving get_funded_wallet out of the test section to make it available for bdk-reserves 2021-08-25 11:18:50 +02:00
Roman Zeyde
470d02c81c
Fix a small typo in log_progress() description 2021-08-24 23:56:57 +03:00
Steve Myers
38d1d0b0e2
Merge branch 'release/0.10.0' 2021-08-19 19:55:24 +02:00
Steve Myers
582d2f3814
Remove unneeded cache paths for test-blockchains CI job 2021-08-19 18:17:20 +02:00
Steve Myers
5e0011e1a8
Change dependencies bitcoincore-rpc to core-rpc, update bitcoin to ^0.27 and miniscript to ^6.0 2021-08-19 18:16:40 +02:00
Steve Myers
39d2bd0d21
Update dev-dependencies electrsd to 0.10 2021-08-19 18:13:50 +02:00
Steve Myers
0e10952b80
Merge commit 'refs/pull/409/head' of github.com:bitcoindevkit/bdk 2021-08-19 14:08:05 +02:00
Steve Myers
19d74955e2
Update Database BatchOperations flush() documentation 2021-08-19 13:56:38 +02:00
Steve Myers
73a7faf144
Remove unneeded cache paths for test-blockchains CI job 2021-08-18 09:10:47 +02:00
Steve Myers
ea56a87b4b
Change dependencies bitcoincore-rpc to core-rpc, update bitcoin to ^0.27 and miniscript to ^6.0 2021-08-17 22:52:17 +02:00
Steve Myers
67f5f45e07
Update dev-dependencies electrsd to 0.10 2021-08-17 22:51:40 +02:00
Alekos Filini
b8680b299d
Bump version to 0.10.1-dev 2021-08-09 17:00:05 +02:00
Alekos Filini
a5d3a4d31a
Bump version to 0.10.0 2021-08-09 14:58:32 +02:00
Alekos Filini
d03d3c0dbd
Update bdk-macros 2021-08-09 14:57:58 +02:00
Alekos Filini
9aba3196ff
Bump version of bdk-macros to v0.5.0 2021-08-09 14:57:06 +02:00
Alekos Filini
c8593ecf70
Update version in src/lib.rs 2021-08-09 14:56:22 +02:00
Alekos Filini
cbec0b0bcf
Update changelog 2021-08-09 14:55:17 +02:00
Tobin Harding
e80be49d1e
Disable default features for rocksdb
In an effort to reduce the build times of `rocksdb` we can set
`default-features` to false.

Please note, the build speed up is minimil

With default features:
```
cargo check --features compact_filters  890.91s user 47.62s system 352% cpu 4:26.55 total
```

Without default features:
```
cargo check --features compact_filters  827.07s user 47.63s system 352% cpu 4:08.39 total
```

Enable `snappy` since it seems like this is the current default compression
algorithm, therefore this patch (hopefully) makes no changes to the usage of the
`rocksdb` library in `bdk`. From the `rocksdb` code:

```
    /// Sets the compression algorithm that will be used for compressing blocks.
    ///
    /// Default: `DBCompressionType::Snappy` (`DBCompressionType::None` if
    /// snappy feature is not enabled).
    ///
    /// # Examples
    ///
    /// ```
    /// use rocksdb::{Options, DBCompressionType};
    ///
    /// let mut opts = Options::default();
    /// opts.set_compression_type(DBCompressionType::Snappy);
    /// ```
    pub fn set_compression_type(&mut self, t: DBCompressionType) {
        ....
```
2021-08-04 10:22:08 +10:00
Riccardo Casatta
fe30716fa2
update CHANGELOG citing new flush method 2021-08-03 12:34:26 +02:00
Riccardo Casatta
e52550cfec
Add flush method to Database trait 2021-08-03 12:33:31 +02:00
Riccardo Casatta
f57c0ca98e
in tests enable daemons logging if log level is Debug 2021-08-03 12:15:16 +02:00
Alekos Filini
c54e1e9652
Bump version to 0.10.0-rc.1 2021-07-30 17:47:45 +02:00
Tobin Harding
5cdc5fb58a
Move estimate -> fee rate logic to esplora module
Currently we have duplicate code for converting the fee estimate we get
back from esplora into a fee rate. This logic can be moved to a separate
function and live in the `esplora` module.
2021-07-29 10:12:19 +10:00
Tobin Harding
27cd9bbcd6
Improve feature combinations for ureq/reqwest
Our features are a bit convoluted, most annoyingly we cannot build with
`--all-features`. However we can make life for users a little easier.

Explicitly we want users to be able to:

- Use async-interface/WASM without using esplora (to implement their own blockchain)
- Use esplora in an ergonomic manner

Currently using esplora requires either reqwest or ureq. Instead of
making the user add all the features manually we can add features that
add the required feature sets, this makes it easier for users to
understand what is required and also makes usage easier.

With this patch applied we can do

- `cargo check --no-default-features --features=use-esplora-reqwest`
- `cargo check --no-default-features --features=use-esplora-ureq`
- `cargo check --features=use-esplora-ureq`
- `cargo check --no-default-features --features=async-trait`
2021-07-29 10:12:17 +10:00
Tobin Harding
f37e735b43
Add a ureq version of esplora module
The `Blockchain` implementation for connecting to an Esplora instance is
currently based on `reqwest`. Some users may not wish to use reqwest.

`ureq` is a simple HTTP client (no async) that is useful when `reqwest`
is not suitable.

- Move `esplora.rs` -> `esplora/reqwest.rs`
- Add an implementation based on the `reqwest` esplora code but using `ureq`
- Add feature flags and conditional includes to re-export everything to
  the `esplora` module so we don't effect the rest of the code base.
- Remove the forced dependency on `tokio`.
- Make esplora independent of async-interface
- Depend on local version of macros crate
2021-07-29 09:16:44 +10:00
codeShark149
adceafa40c
Fix float substraction error 2021-07-28 11:52:51 +02:00
Alekos Filini
2b0c4f0817
Merge commit 'refs/pull/407/head' of github.com:bitcoindevkit/bdk 2021-07-28 11:34:41 +02:00
Alekos Filini
e9428433a0
Merge commit 'refs/pull/408/head' of github.com:bitcoindevkit/bdk 2021-07-28 11:32:44 +02:00
Alekos Filini
63592f169f
Merge commit 'refs/pull/392/head' of github.com:bitcoindevkit/bdk 2021-07-27 13:23:25 +02:00
Alekos Filini
27600f4a11
Merge commit 'refs/pull/398/head' of github.com:bitcoindevkit/bdk 2021-07-27 13:07:56 +02:00
Riccardo Casatta
77eae76459
add link to upstream PR 2021-07-27 12:17:12 +02:00
Riccardo Casatta
ad69702aa3
Update electrsd dep 2021-07-26 17:09:00 +02:00
Riccardo Casatta
fd254536d3
update CHANGELOG.md 2021-07-26 16:36:35 +02:00
Riccardo Casatta
c4d5dd14fa
Use RPC backend in any 2021-07-26 16:36:32 +02:00
Riccardo Casatta
13bed2667a
Create Auth struct proxy of the same upstream struct but serializable 2021-07-26 15:55:40 +02:00
Tobin Harding
2db24fb8c5
Add unit test required not enough
Add a unit test that passes a required utxo to the coin selection
algorithm that is less than the required spend. This tests that we get
that utxo included as well as tests that the rest of the coin selection
algorithm code also executes (i.e., that we do not short circuit
incorrectly).
2021-07-23 10:27:16 +10:00
Tobin Harding
d2d37fc06d
Return early if required UTXOs already big enough
If the required UTXO set is already bigger (including fees) than the
amount required for the transaction we can return early, no need to go
through the BNB algorithm or random selection.
2021-07-23 09:48:22 +10:00
Tobin Harding
2986fce7c6
Fix vbytes and fee rate code
It was just pointed out that we are calculating the virtual bytes
incorrectly by forgetting to take the ceiling after division by 4 [1]

Add helper functions to encapsulate all weight unit -> virtual byte
calculations including fee to and from fee rate. This makes the code
easier to read, easier to write, and gives us a better chance that bugs
like this will be easier to see.

As an added bonus we can also stop using f32 values for fee amount,
which is by definition an amount in sats so should be a u64. This
removes a bunch of casts and the need for epsilon comparisons and just
deep down feels nice :)

[1] https://github.com/bitcoindevkit/bdk/pull/386#discussion_r670882678
2021-07-23 09:43:12 +10:00
Roman Zeyde
1dc648508c
Fix a small typo in comments 2021-07-21 21:32:35 +03:00
Steve Myers
474620e6a5
[keys] limit version of zeroize to support rust 1.47+ 2021-07-19 14:35:16 -07:00
Steve Myers
a5919f4ab0
Remove stop_gap param from Blockchain trait setup and sync functions 2021-07-16 08:52:41 -07:00
Steve Myers
7e986fd904
Add stop_gap param to electrum and esplora blockchain configs 2021-07-16 08:50:36 -07:00
Alekos Filini
77379e9262
Merge commit 'refs/pull/371/head' of github.com:bitcoindevkit/bdk 2021-07-16 11:24:19 +02:00
Alekos Filini
ea699a6ec1
Merge commit 'refs/pull/393/head' of github.com:bitcoindevkit/bdk 2021-07-16 09:05:51 +02:00
Lloyd Fournier
81c1ccb185
Apply typo fixes from @tcharding
Co-authored-by: Tobin C. Harding <me@tobin.cc>
2021-07-14 16:43:02 +10:00
Steve Myers
4f4802b0f3
Merge commit 'refs/pull/388/head' of github.com:bitcoindevkit/bdk 2021-07-13 16:10:30 -07:00
Steve Myers
bab9d99a00
Merge commit 'refs/pull/375/head' of github.com:bitcoindevkit/bdk 2021-07-13 15:12:53 -07:00
Alekos Filini
22f4db0de1
Merge commit 'refs/pull/389/head' of github.com:bitcoindevkit/bdk 2021-07-12 14:26:05 +02:00
Riccardo Casatta
a6ce75fa2d
[docs] clarify when the fee could be unknown 2021-07-12 10:06:08 +02:00
LLFourn
7597645ed6
Replace set_single_recipient with drain_to
What set_single_recipient does turns out to be useful with multiple
recipients.
Effectively, set_single_recipient was simply creating a change
output that was arbitrarily required to be the only output.
But what if you want to send excess funds to one address but still have
additional recipients who receive a fixed value?
Generalizing this to `drain_to` simplifies the logic and removes several
error cases while also allowing new use cases.

"maintain_single_recipient" is also replaced with "allow_shrinking"
which has more general semantics.
2021-07-12 16:38:42 +10:00
LLFourn
618e0d3700
Replace set_single_recipient with drain_to
What set_single_recipient does turns out to be useful with multiple
recipients.
Effectively, set_single_recipient was simply creating a change
output that was arbitrarily required to be the only output.
But what if you want to send excess funds to one address but still have
additional recipients who receive a fixed value?
Generalizing this to `drain_to` simplifies the logic and removes several
error cases while also allowing new use cases.

"maintain_single_recipient" is also replaced with "allow_shrinking"
which has more general semantics.
2021-07-12 16:21:53 +10:00
Alekos Filini
44d0e8d07c
[rpc] Show in the docs that the RPC APIs are feature-gated 2021-07-09 09:11:02 +02:00
Alekos Filini
7a9b691f68
Bump version to 0.9.1-dev 2021-07-08 15:20:28 +02:00
Alekos Filini
4e813e8869
Bump version to 0.9.0 2021-07-08 13:37:19 +02:00
Alekos Filini
53409ef3ae
Update version in src/lib.rs 2021-07-08 13:37:05 +02:00
Alekos Filini
f8a6e1c3f4
Update CHANGELOG 2021-07-08 13:36:20 +02:00
Tobin Harding
c1077b95cf
Add Vbytes trait
We convert weight units into vbytes in various places. Lets add a trait
to do it, this makes the code slightly cleaner.
2021-07-08 11:33:39 +10:00
Alekos Filini
fa5103b0eb
Merge commit 'refs/pull/383/head' of github.com:bitcoindevkit/bdk into release/0.9.0 2021-07-06 09:58:40 +02:00
Alekos Filini
e5d4994329
Merge commit 'refs/pull/383/head' of github.com:bitcoindevkit/bdk 2021-07-06 09:58:22 +02:00
Alekos Filini
d1658a2eda
Merge commit 'refs/pull/385/head' of github.com:bitcoindevkit/bdk into release/0.9.0 2021-07-06 09:57:22 +02:00
Evgenii P
879e5cf319
rustfmt 2021-07-03 14:08:38 +07:00
Evgenii P
928f9c6112
dsl: add regression test for and_or() descriptor 2021-07-03 13:52:05 +07:00
Evgenii P
814ab4c855
dsl: fix descriptor macro when and_or() used 2021-07-03 13:51:43 +07:00
Alekos Filini
58cf46050f
Build the rpc feature on docs.rs 2021-07-02 10:09:58 +02:00
Alekos Filini
b6beef77e7
[rpc] Mark the RPC backend as experimental 2021-07-02 10:09:55 +02:00
Alekos Filini
7ed0676e44
Build the rpc feature on docs.rs 2021-07-02 10:09:09 +02:00
Alekos Filini
595e1bdbe1
[rpc] Mark the RPC backend as experimental 2021-07-02 10:07:44 +02:00
Alekos Filini
7555d3b430
Bump version to 0.9.0-rc.1 2021-07-02 10:06:31 +02:00
Alekos Filini
fbdee52f2f
[verify] Build the verify feature on docs.rs 2021-07-01 16:37:03 +02:00
Alekos Filini
50597fd73f
[verify] Use impl_error!() whenever possible 2021-07-01 16:37:00 +02:00
Alekos Filini
975905c8ea
[verify] Add documentation 2021-07-01 16:36:56 +02:00
Alekos Filini
a67aca32c0
[verify] Cache txs to avoid multiple db/network lookups 2021-07-01 16:36:52 +02:00
Alekos Filini
7873dd5e40
[wallet] Verify unconfirmed transactions after syncing
Verify the unconfirmed transactions we download against the consensus
rules. This is currently exposed as an extra `verify` feature, since it
depends on a pre-release version of `bitcoinconsensus`.

Closes #352
2021-07-01 16:36:48 +02:00
Alekos Filini
a186d82f9a
[wallet] Verify unconfirmed transactions after syncing
Verify the unconfirmed transactions we download against the consensus
rules. This is currently exposed as an extra `verify` feature, since it
depends on a pre-release version of `bitcoinconsensus`.

Closes #352
2021-07-01 16:36:42 +02:00
Riccardo Casatta
7109f7d9b4
fix readme 2021-06-29 11:35:02 +02:00
Riccardo Casatta
f52fda4b4b
update github ci removing electrs download and fixing cache 2021-06-29 11:35:00 +02:00
Riccardo Casatta
a6be470fe4
use electrsd with feature to download the binary 2021-06-29 11:34:58 +02:00
Riccardo Casatta
8e41c4587d
use bitcoind with feature to download the binary 2021-06-29 11:34:56 +02:00
Riccardo Casatta
2ecae348ea
use cfg! instead of #[cfg] and use semver 2021-06-29 11:34:54 +02:00
Riccardo Casatta
f4ecfa0d49
Remove container and test blockchains downloading backends executables 2021-06-29 11:34:48 +02:00
Riccardo Casatta
696647b893
trigger electrs when polling 2021-06-29 11:32:30 +02:00
Riccardo Casatta
18dcda844f
remove serial_test 2021-06-29 11:32:28 +02:00
Riccardo Casatta
6394c3e209
use bitcoind and electrsd crate to launch daemons 2021-06-29 11:32:26 +02:00
Riccardo Casatta
42adad7dbd
bump bitcoind dep to 0.11.0 2021-06-29 11:32:24 +02:00
Alekos Filini
4498e0f7f8
[testutils] Allow the generated blockchain tests to access test_client 2021-06-29 11:32:20 +02:00
William Casarin
476fa3fd7d
add Copy trait to Progress types 2021-06-23 08:31:55 -07:00
Alekos Filini
2755b09e7b
Bump CI stable version to 1.53
Fixes #374
2021-06-21 12:16:54 +02:00
Alekos Filini
5e6286a493
Fix clippy warnings on 1.53
Fix `clippy::inconsistent_struct_constructor`: the constructor field
order was inconsistent with the struct declaration.
2021-06-21 12:16:45 +02:00
Alekos Filini
67714adc80
Fix CHANGELOG
The `Rpc` backend is not part of the release but it accidentally ended
up there during the merge
2021-06-21 09:07:15 +02:00
Alekos Filini
9ff86ea37c
Merge commit 'refs/pull/370/head' of github.com:bitcoindevkit/bdk 2021-06-18 12:54:11 +02:00
Steve Myers
ceeb3a40cf
[ci] Revert change to run_blockchain_tests.sh back to using container id 2021-06-15 15:57:14 -07:00
Steve Myers
e3316aee4c
[ci] Change blockchain tests to use bitcoind rpc cookie authentication 2021-06-15 15:39:54 -07:00
Steve Myers
c2567b61aa
Merge branch 'release/0.8.0' 2021-06-14 11:47:39 -07:00
Steve Myers
e1a77b87ab
Fix CHANGELOG unreleased link 2021-06-14 11:43:48 -07:00
Steve Myers
5bf758b03a
Add CHANGELOG v0.8.0 link 2021-06-14 11:40:50 -07:00
Riccardo Casatta
0bbfa5f989
make fee in TransactionDetails Option, add confirmation_time field as Option
confirmation_time contains both a block height and block timestamp and is
Some only for confirmed transaction
2021-06-14 15:29:24 +02:00
Alekos Filini
18254110c6
Merge commit 'refs/pull/348/head' of github.com:bitcoindevkit/bdk 2021-06-11 11:41:23 +02:00
Alekos Filini
44217539e5
Bump version to 0.8.1-dev 2021-06-11 11:29:42 +02:00
Alekos Filini
33b45ebe82
Bump version to 0.8.0 2021-06-10 16:00:01 +02:00
Alekos Filini
2faed425ed
Update CHANGELOG 2021-06-10 15:59:24 +02:00
Alekos Filini
2cc05c07a5
Bump version in src/lib.rs 2021-06-10 15:59:08 +02:00
Riccardo Casatta
fe371f9d92
Use bitcoin's base64 feature for Psbts 2021-06-10 15:50:44 +02:00
Tobin Harding
12de13b95c
Remove redundant borrows
Clippy emits:

  warning: this expression borrows a reference

As suggested remove the borrows from the front of vars that are already references.
2021-06-10 13:16:07 +10:00
Alekos Filini
9205295332
Merge commit 'refs/pull/365/head' of github.com:bitcoindevkit/bdk into release/0.8.0 2021-06-09 16:05:16 +02:00
Tobin Harding
3b446c9e14
Use no_run instead of ignore
We have an attribute `no_run` that builds but does not run example code
in Rustdocs, this keeps the examples building as the codebase evolves.

use `no_run` and fix example code so it builds cleanly during test run.

Some examples that require the `electrum` feature to be available have
been feature-gated to make sure they aren't accidentally compiled when
that feature is not enabled.

Co-authored-by: Alekos Filini <alekos.filini@gmail.com>
2021-06-09 11:29:57 +02:00
Alekos Filini
378167efca
Remove explicit feature(external_doc)
It looks like this is now enabled by default as of `cargo 1.54.0-nightly (0cecbd673 2021-06-01)`
2021-06-09 11:27:25 +02:00
Alekos Filini
224be27aa8
Fix example/doctests format 2021-06-04 15:53:15 +02:00
Alekos Filini
4a23070cc8
[ci] Check fmt for examples/doctests 2021-06-04 15:07:02 +02:00
Riccardo Casatta
ba2e3042cc
add details to TODO, format doc example 2021-06-04 15:05:35 +02:00
Alekos Filini
f8117c0f9f
Bump version to 0.8.0-rc.1 2021-06-04 09:42:14 +02:00
Riccardo Casatta
1639984b56
move scan in setup 2021-06-03 15:26:47 +02:00
Riccardo Casatta
ab54a17eb7
update bitcoind dep 2021-06-03 11:07:39 +02:00
Riccardo Casatta
ae5aa06586
use storage address instead of satoshi's 2021-06-03 11:06:24 +02:00
Riccardo Casatta
ab98283159
always ask node for tx no matter capabilities 2021-06-03 10:56:02 +02:00
Riccardo Casatta
81851190f0
correctly initialize UTXO keychain kind 2021-06-03 10:56:02 +02:00
Riccardo Casatta
e1b037a921
change feature to execute sync from rpc to test-rpc 2021-06-03 10:56:01 +02:00
Riccardo Casatta
9b7ed08891
rename struct to CallResult 2021-06-03 10:56:01 +02:00
Riccardo Casatta
dffb753ce3
match also on signet 2021-06-03 10:56:00 +02:00
Riccardo Casatta
0b969657cd
update changelog with rpc feature 2021-06-03 10:55:59 +02:00
Riccardo Casatta
bfef2e3cfe
Implements RPC Backend 2021-06-03 10:55:58 +02:00
Paul Miller
0ec064ef13
Use AddressInfo in private methods 2021-05-27 17:11:16 -04:00
Paul Miller
6b60914ca1
return AddressInfo from get_address 2021-05-27 17:11:16 -04:00
Alekos Filini
881ca8d1e3
[signer] Add an option to explicitly allow using non-ALL sighashes
Instead of blindly using the `sighash_type` set in a psbt input, we
now only sign `SIGHASH_ALL` inputs by default, and require the user to
explicitly opt-in to using other sighashes if they desire to do so.

Fixes #350
2021-05-26 10:38:15 +02:00
Alekos Filini
5633475ce8
Merge commit 'refs/pull/347/head' of github.com:bitcoindevkit/bdk 2021-05-26 08:56:38 +02:00
LLFourn
ea8488b2a7
Initialize env_logger at start of blockchain tests 2021-05-21 13:21:59 +10:00
LLFourn
d2a981efee
run_blockchain_tests.sh improvements 2021-05-21 13:21:41 +10:00
LLFourn
4c92daf517
Uppercase 'Test' so that github can see what's up
It is expecting something named 'Test electrum'
2021-05-20 14:33:02 +10:00
LLFourn
aba2a05d83
Add script for running the blockchain tests locally 2021-05-19 16:45:48 +10:00
LLFourn
5b194c268d
Fix clippy warnings inside testutils macro
Now that it's inside the main repo clippy is having a go at me.
2021-05-19 16:45:48 +10:00
LLFourn
00bdf08f2a
Remove testutils feature so doctests worka again
I wanted to only conditionally compile testutils but it's needed in
doctests which we can't conditionally compile for:

https://github.com/rust-lang/rust/issues/67295
2021-05-19 16:45:48 +10:00
LLFourn
38b0470b14
Move blockchain related stuff to blockchain_tests 2021-05-19 16:45:48 +10:00
LLFourn
d60c5003bf
Merge testutils crate into the main crate
This avoids having to keep the apis in sync between the macros and the
main project.
2021-05-19 16:45:48 +10:00
LLFourn
fcae5adabd
Run blockchain tests on esplora
They were only being run on electrum before.
2021-05-19 15:47:44 +10:00
Steve Myers
9f04a9d82d
Merge commit 'refs/pull/338/head' of github.com:bitcoindevkit/bdk 2021-05-18 16:41:45 -07:00
LLFourn
465ef6e674
Roll blockchain tests proc macro into normal macro
This means one less crate in the repo. Had to do a Default on TestClient
to satisfy clippy.
2021-05-18 20:02:33 +10:00
Steve Myers
aaa9943a5f
Merge commit 'refs/pull/346/head' of github.com:bitcoindevkit/bdk 2021-05-14 10:49:30 -07:00
Alekos Filini
3897e29740
Fix changelog 2021-05-12 15:11:20 +02:00
Alekos Filini
8f06e45872
Bump version to 0.7.1-dev 2021-05-12 15:10:28 +02:00
Alekos Filini
766570abfd
Bump version to 0.7.0 2021-05-12 14:20:58 +02:00
Alekos Filini
934ec366d9
Use the released testutils-macros 2021-05-12 14:20:23 +02:00
Alekos Filini
d0733e9496
Bump version in src/lib.rs 2021-05-12 14:19:58 +02:00
Alekos Filini
3c7a1f5918
Bump testutils-macros to v0.6.0 2021-05-12 14:19:00 +02:00
Alekos Filini
85aadaccd2
Update changelog in preparation of v0.7.0 2021-05-12 14:17:46 +02:00
Tobin Harding
fad0fe9f30
Update create transaction example code
The transaction builder changed a while ago, looks like some of the
example code did not get updated.

Update the transaction creation code to use a mutable builder.
2021-05-12 14:13:23 +02:00
Tobin Harding
6546b77c08
Remove stale comments
The two fields this comment references are not `Option` type. This
comment seems to be stale.
2021-05-11 13:29:22 +10:00
Tobin Harding
e1066e955c
Remove unneeded unit expression
Clippy emits:

  warning: unneeded unit expression

As suggested, remove the unneeded unit expression.
2021-05-11 10:52:08 +10:00
Tobin Harding
7f06dc3330
Clear clippy manual_map warning
The lint `manual_map` is new so we cannot explicitly allow it and
maintain backwards comparability. Instead, allow all lints for
`get_utxo_for` with a comment explaining why.
2021-05-11 10:52:07 +10:00
Tobin Harding
de40351710
Use consistent field ordering
Clippy emits:

  warning: struct constructor field order is inconsistent with struct
  definition field order

As suggested, re-order the fields to be consistent with the struct
definition.
2021-05-11 10:51:44 +10:00
Tobin Harding
de811bea30
Use !any() instead of find()...is_none()
Clippy emits:

  warning: called `is_none()` after searching an `Iterator` with `find`

As suggested, use the construct: `!foo.iter().any(...)`
2021-05-11 10:51:44 +10:00
Tobin Harding
74cc80d127
Remove unnecessary clone
Clippy emits:

  warning: using `clone` on type `descriptor::policy::Condition` which
  implements the `Copy` trait

Remove the clone and rely on `Copy`.
2021-05-11 10:51:44 +10:00
Tobin Harding
009f68a06a
Use assert!(foo) instead of assert_eq!(foo, true)
It is redundant to pass true/false to `assert_eq!` since `assert!`
already asserts true/false.

This may, however, be controversial if someone thinks that

```
    assert_eq!(foo, false);
```

is more clear than

```
    assert!(!foo);
```

Use `assert!` directly instead of `assert_eq!` with true/false argument.
2021-05-11 10:51:44 +10:00
Riccardo Casatta
47f26447da
continue signing when finding already finalized inputs 2021-05-07 16:32:24 +02:00
Tobin Harding
12641b9e8f
Use PsbtKey instead of PSBT
We recently converted uses of `PSBT` -> `Psbt` inline with idiomatic
Rust acronym identifiers. Do the same to `PSBTKey`.

Use `PsbtKey` instead of `PSBTKey` when aliasing the import of
`psbt::raw::Key` from `bitcoin` library.
2021-05-07 16:29:53 +02:00
Tobin Harding
aa3707b5b4
Use Psbt instead of PSBT
Idiomatic Rust uses lowercase for acronyms for all characters after the
first e.g. `std::net::TcpStream`. PSBT (Partially Signed Bitcoin
Transaction) should be rendered `Psbt` in Rust code if we want to write
idiomatic Rust.

Use `Psbt` instead of `PSBT` when aliasing the import of
`PartiallySignedTransaction` from `bitcoin` library.
2021-05-07 16:29:50 +02:00
Riccardo Casatta
f6631e35b8
continue signing when finding already finalized inputs 2021-05-07 13:52:20 +02:00
Alekos Filini
3608ff9f14
Merge commit 'refs/pull/341/head' of github.com:bitcoindevkit/bdk into release/0.7.0 2021-05-07 11:00:00 +02:00
Alekos Filini
7fdb98e147
Merge commit 'refs/pull/341/head' of github.com:bitcoindevkit/bdk 2021-05-07 10:59:32 +02:00
Tobin Harding
9aea90bd81
Use default: D mirroring Rust documentation
Currently we use `F: f` for the argument that is the default function
passed to `map_or_else` and pass a closure for the second argument. This
bent my brain while reading the documentation because the docs use
`default: D` for the first and `f: F` for the second. Although this is
totally trivial it makes deciphering the combinator chain easier if we
name the arguments the same way the Rust docs do.

Use `default: D` for the identifier of the default function passed into `map_or_else`.
2021-05-07 09:08:49 +10:00
Riccardo Casatta
898dfe6cf1
get psbt inputs with bounds check 2021-05-06 16:10:11 +02:00
Riccardo Casatta
7961ae7f8e
Check index out of bound also for tx inputs not only for psbt inputs 2021-05-06 15:13:25 +02:00
Alekos Filini
8bf77c8f07
Bump version to 0.7.0-rc.1 2021-05-06 13:56:38 +02:00
Alekos Filini
3c7bae9ce9
Rewrite the non_witness_utxo check 2021-05-06 11:39:01 +02:00
Alekos Filini
17bcd8ed7d
[signer] Replace force_non_witness_utxo with only_witness_utxo
Instead of providing an opt-in option to force the addition of the
`non_witness_utxo`, we will now add them by default and provide the
option to disable them when they aren't considered necessary.
2021-05-06 08:58:39 +02:00
Alekos Filini
b5e9589803
[signer] Adjust signing behavior with SignOptions 2021-05-06 08:58:38 +02:00
Alekos Filini
1d628d84b5
[signer] Fix error variant 2021-05-05 16:59:59 +02:00
Alekos Filini
b84fd6ea5c
Fix import for FromStr 2021-05-05 16:59:57 +02:00
Alekos Filini
8fe4222c33
Merge commit 'refs/pull/336/head' of github.com:bitcoindevkit/bdk 2021-05-05 14:51:36 +02:00
codeShark149
e626f2e255
Added grcov based code coverage reporting in github action 2021-04-30 17:20:20 +05:30
LLFourn
5a0c150ff9
Make wallet methods take &mut psbt
Rather than consuming it because that is unergonomic.
2021-04-28 15:34:25 +10:00
Alekos Filini
00f07818f9
Merge commit 'refs/pull/321/head' of github.com:bitcoindevkit/bdk 2021-04-16 14:08:26 +02:00
Riccardo Casatta
136a4bddb2
Verify PSBT input satisfaction 2021-04-16 12:22:49 +02:00
Riccardo Casatta
ff7b74ec27
destructure tuple to improve clarity 2021-04-16 12:22:47 +02:00
Steve Myers
8c00326990
[ci] Revert fixed nightly-2021-03-23, use actual nightly 2021-04-15 10:15:13 -07:00
Riccardo Casatta
afcd26032d
comment out println in tests, fix doc 2021-04-15 16:48:42 +02:00
Riccardo Casatta
8f422a1bf9
Add timelocks to policy satisfaction results
Also for signature the logic has been refactored to handle appropriately nested cases.
2021-04-15 15:57:35 +02:00
Alekos Filini
45983d2166
Merge commit 'refs/pull/322/head' of github.com:bitcoindevkit/bdk 2021-04-15 11:40:34 +02:00
Steve Myers
89cb4de7f6
[ci] Update 'test-readme-examples' job to use nightly-2021-03-23 2021-04-14 20:34:32 -07:00
Steve Myers
7ca0e0e2bd
[ci] Update 'Tarpaulin to codecov.io' job to use nightly-2021-03-23 2021-04-14 20:33:42 -07:00
Alekos Filini
2bddd9baed
Update CHANGELOG for v0.6.0 2021-04-14 18:49:52 +02:00
Alekos Filini
0135ba29c5
Bump version to 0.6.1-dev 2021-04-14 18:47:31 +02:00
Alekos Filini
549cd24812
Bump version to 0.6.0 2021-04-14 17:27:28 +02:00
Alekos Filini
a841b5d635
Use published bdk-testutils-macros 2021-04-14 17:26:40 +02:00
Alekos Filini
16ceb6cb30
Bump version of bdk-testutils-macros 2021-04-14 17:25:11 +02:00
Alekos Filini
edfd7d454c
Merge commit 'refs/pull/325/head' of github.com:bitcoindevkit/bdk into release/0.6.0 2021-04-13 09:25:47 +02:00
Alekos Filini
1d874e50c2
Merge commit 'refs/pull/326/head' of github.com:bitcoindevkit/bdk into release/0.6.0 2021-04-13 09:25:27 +02:00
Richard Ulrich
98127cc5da
Allow setting RBF when bumping the fee of a transaction. This enables to further bump the fee. 2021-04-13 09:18:46 +02:00
Richard Ulrich
e243107bb6
Adding tests to demonstrate that we can't keep RBF when bumping the fee of a transaction. 2021-04-13 09:18:43 +02:00
Steve Myers
237a8d4e69
[ci] Update 'Build docs' job to use nightly-2021-03-23 2021-04-12 10:33:54 -07:00
Steve Myers
7f4042ba1b
Bump version to 0.6.0-rc.1 2021-04-09 15:30:34 -07:00
Steve Myers
3ed44ce8cf
Remove unneeded script 2021-04-09 09:19:19 -07:00
Steve Myers
8e7d8312a9
[ci] Update 'build-test' job to clippy check all-targets 2021-04-08 14:44:35 -07:00
Steve Myers
4da7488dc4
Update 'cargo-check.sh' to not check +nightly 2021-04-08 14:36:07 -07:00
Steve Myers
e37680af96
Use .flatten() instead of .filter_map(|x| x), clippy warning
https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_identity
2021-04-08 14:18:07 -07:00
Steve Myers
5f873ae500
Use .any() instead of .find().is_some(), clippy warning
https://rust-lang.github.io/rust-clippy/master/index.html#search_is_some
2021-04-08 14:18:07 -07:00
Steve Myers
2380634496
Use .get(0) instead of .iter().next(), clippy warning
https://rust-lang.github.io/rust-clippy/master/index.html#iter_next_slice
2021-04-08 14:18:07 -07:00
Steve Myers
af98b8da06
Compare float equality using error margin EPSILON, clippy warning
https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp
2021-04-08 14:17:59 -07:00
Steve Myers
b68ec050e2
Remove redundant clone, clippy warning
https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone
2021-04-08 11:41:58 -07:00
Steve Myers
ac7df09200
Remove needlessly taken reference of both operands, clippy warning
https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
2021-04-08 11:39:38 -07:00
Riccardo Casatta
192965413c
Convert upper-case acronyms as suggested by CamelCase convention
see https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms
2021-04-07 22:14:54 +02:00
Riccardo Casatta
745be7bea8
remove format! from assert! (will be an error in rust edition 2021) 2021-04-07 22:09:08 +02:00
Riccardo Casatta
b6007e05c1
upgrade CI rust version to 1.51.0 2021-04-07 22:08:56 +02:00
Steve Myers
f53654d9f4
Merge commit 'refs/pull/314/head' of github.com:bitcoindevkit/bdk 2021-04-06 10:21:07 -07:00
Daniel Karzel
e5ecc7f541
Avoid over-/underflow error in coin_select
Adds fix for edge-cases involving small UTXOs (where value < fee) where the coin_select calculation would panic with overflow/underflow errors.
Bitcoin is limited to 21*(10^6), so any Bitcoin amount fits into i64.
2021-04-06 10:21:55 +10:00
LLFourn
882a9c27cc
Use tagged serialization for blockchain config
also make the config types Clone and PartialEq
2021-04-03 15:30:49 +11:00
Steve Myers
1e6b8e12b2
Merge commit 'refs/pull/310/head' of github.com:bitcoindevkit/bdk 2021-03-31 16:06:53 -07:00
Steve Myers
b226658977
[ci] update MSRV to 1.46.0 2021-03-29 11:17:50 -07:00
Alekos Filini
6d6776eb58
Merge branch 'release/0.5.1' 2021-03-29 19:48:00 +02:00
Alekos Filini
f1f844a5b6
Bump version to 0.5.2-dev 2021-03-29 19:10:47 +02:00
Alekos Filini
a3e45358de
Bump version to 0.5.1 2021-03-29 18:28:06 +02:00
Alekos Filini
07e79f6e8a
Update CHANGELOG.md 2021-03-29 18:28:04 +02:00
Steve Myers
d94b8f87a3
Pin hyper version to =0.14.4 2021-03-29 10:12:56 +02:00
Steve Myers
fdb895d26c
Update DEVELOPMENT_CYCLE for unreleased dev-dependencies 2021-03-22 10:48:39 -07:00
Steve Myers
7041e96737
Fix new test to use new get_address() fn 2021-03-22 10:26:56 -07:00
Steve Myers
199f716ebb
Fix bdk-testutils-macros version 2021-03-22 10:24:21 -07:00
Steve Myers
b12e358c1d
Fix 0.5.1-dev CHANGELOG.md 2021-03-20 11:42:00 -07:00
Alekos Filini
f786f0e624
Merge branch 'release/0.5.0' of github.com:bitcoindevkit/bdk 2021-03-17 22:27:44 +01:00
Alekos Filini
71e0472dc9
Bump version to 0.5.1-dev 2021-03-17 20:58:23 +01:00
Alekos Filini
f7944e871b
Bump version to 0.5.0 2021-03-17 15:21:37 +01:00
Alekos Filini
2fea1761c1
Bump deps version 2021-03-17 15:21:07 +01:00
Alekos Filini
fa27ae210f
Update version in lib.rs 2021-03-17 15:14:35 +01:00
Alekos Filini
46fa41470e
Update CHANGELOG with the new release tag 2021-03-17 15:13:46 +01:00
Alekos Filini
c456a252f8
Merge commit 'refs/pull/296/head' of github.com:bitcoindevkit/bdk 2021-03-17 11:30:31 +01:00
Riccardo Casatta
d837a762fc
update changelog and fix docs 2021-03-17 11:24:48 +01:00
davemo88
e82dfa971e
brevity 2021-03-16 10:20:07 -04:00
davemo88
cc17ac8859
update changelog 2021-03-15 21:58:03 -04:00
davemo88
3798b4d115
add get_psbt_input 2021-03-15 21:50:51 -04:00
Steve Myers
2d0f6c4ec5
[wallet] Add get_address(AddressIndex::Reset(u32)), update CHANGELOG 2021-03-15 09:13:23 -07:00
Steve Myers
f3b475ff0e
[wallet] Refactor get_*_address() into get_address(AddressIndex), update CHANGELOG 2021-03-15 08:58:11 -07:00
Steve Myers
41ae202d02
[wallet] Add get_unused_address() function, update CHANGELOG 2021-03-15 08:58:09 -07:00
Steve Myers
fef6176275
[wallet] Add fetch_index() helper function 2021-03-15 08:58:07 -07:00
Alekos Filini
8ebe7f0ea5
Merge commit 'refs/pull/308/head' of github.com:bitcoindevkit/bdk into release/0.5.0 2021-03-15 10:53:49 +01:00
Alekos Filini
eb85390846
Merge commit 'refs/pull/309/head' of github.com:bitcoindevkit/bdk into release/0.5.0 2021-03-15 10:53:29 +01:00
davemo88
dc83db273a
better derivation path building 2021-03-11 21:54:00 -05:00
davemo88
201bd6ee02
better derivation path building 2021-03-11 21:35:16 -05:00
davemo88
396ffb42f9
handle descriptor xkey origin 2021-03-11 17:39:02 -05:00
Steve Myers
9cf62ce874
[ci] Manually install libclang-common-10-dev to 'check-wasm' job 2021-03-11 11:10:10 -08:00
Alekos Filini
9c6b98d98b
Bump version to 0.5.0-rc.1 2021-03-11 10:07:26 +01:00
Riccardo Casatta
14ae64e09d
[policy] Populate satisfaction with singatures already present in a PSBT 2021-03-08 16:58:56 +01:00
Riccardo Casatta
48215675b0
[policy] uncomment and update 4 tests: 2 ignored and 2 restored 2021-03-08 16:51:43 +01:00
Riccardo Casatta
37fa35b24a
[policy] pass existing context instead of new one 2021-03-08 16:51:42 +01:00
Riccardo Casatta
23ec9c3ba0
[policy] pass secp context to setup_keys 2021-03-08 16:51:40 +01:00
Steve Myers
e33a6a12c1
Update README license badge 2021-03-05 16:48:57 -08:00
Steve Myers
12ae1c3479
Update license to Apache 2.0 or MIT, copyright to Bitcoin Dev Kit Developers 2021-03-03 13:23:25 -08:00
Thomas Eizinger
fdde0e691e
Make constructor functions on FeeRate const
This allows `FeeRate`s to be stored inside `const`s.

For example:

const MY_FEE_RATE: FeeRate = FeeRate::from_sat_per_vb(10.0);

Unfortunately, floating point maths inside const expressions is
still unstable, hence we cannot make `from_btc_per_kvb` const.
2021-03-01 11:04:39 +11:00
Alekos Filini
1cbd47b988
Merge commit 'refs/pull/285/head' of github.com:bitcoindevkit/bdk 2021-02-26 10:14:01 +01:00
Alekos Filini
e0183ed5c7
Merge commit 'refs/pull/279/head' of github.com:bitcoindevkit/bdk 2021-02-26 10:09:24 +01:00
Alekos Filini
dae900cc59
Merge commit 'refs/pull/297/head' of github.com:bitcoindevkit/bdk 2021-02-26 10:00:01 +01:00
Alekos Filini
4c2042ab01
[descriptor] Ensure that there are no duplicated keys 2021-02-26 09:46:38 +01:00
Thomas Eizinger
2f0ca206f3
Update electrum-client to 0.7 2021-02-26 14:09:46 +11:00
LLFourn
ac7c1bd97b
Clean up add_foreign_utxo tests a bit
Noticed some suboptimal things while reviewing myself.
2021-02-26 13:33:52 +11:00
LLFourn
d9a102afa9
Improve docs of satisfaction_weight 2021-02-26 13:33:52 +11:00
Lloyd Fournier
7c1dcd8a72
Apply typo fixes from @tcharding
Co-authored-by: Tobin C. Harding <me@tobin.cc>
2021-02-26 13:33:52 +11:00
LLFourn
1fbfeabd77
Added add_foreign_utxo
To allow adding UTXOs external to the current wallet.
The caller must provide the psbt::Input so we can create a coherent PSBT
at the end and so this is compatible with existing PSBT workflows.

Main changes:

- There are now two types of UTXOs, local and foreign reflected in a
`Utxo` enum.
- `WeightedUtxo` now captures floating `(Utxo, usize)` tuples
- `CoinSelectionResult` now has methods on it for distinguishing between
local amount included vs total.
2021-02-26 13:33:52 +11:00
LLFourn
9a918f285d
Make TxBuilder actually Clone
it derived Clone but in practice it was never clone because some of the
parameters were not Clone.
2021-02-26 13:33:52 +11:00
LLFourn
a7183f34ef
s/UTXO/LocalUtxo/g
Since this struct has a "keychain" it is not a general "UTXO" but a
local wallet UTXO.
2021-02-26 13:33:52 +11:00
Tobin Harding
bda416df0a
Use mixed order insertions
Currently we have a unit test to test that signers are sorted by
ordering. We call `add_external` to add them but currently we add them
in the same order we expect them to be in. This means if the
implementation happens to insert them simply in the order they are
added (i.e. insert to end of list) then this test will still pass.

Insert in a mixed order, including one lower followed by one higher -
this ensures we are not inserting at the front or at the back but are
actually sorting based on the `SignerOrdering`.
2021-02-24 13:39:36 +11:00
Tobin Harding
a838c2bacc
Use id() for DummySigner comparison
If we give the `DummySigner` a valid identifier then we can use this to
do comparison.

Half the time we do comparison we only have a `dyn Signer` so we cannot
use `PartialEq`, add a helper function to check equality (this is in
test code so its not toooo ugly).

Thanks @afilini for the suggestion.
2021-02-24 13:37:41 +11:00
Tobin Harding
d2a094aa4c
Align multi-line string
Recently we shortened the first line of a multi-line string and failed
to re-align the rest of the lines.

Thanks @afilini
2021-02-24 13:30:49 +11:00
Tobin Harding
bdb2a53597
Add cargo check script
We build against various targets on CI, in order to not abuse CI its
nice to see if code is good before pushing.

Add a script that runs `cargo check` with various combinations of
features and targets in order to enable thorough checking of the project
source code during development.
2021-02-24 13:30:49 +11:00
Tobin Harding
97ad0f1b4f
Remove unused macro_use
Found by Clippy, we don't need this `macro_use` statement.
2021-02-24 13:30:48 +11:00
Tobin Harding
2b5e177ab2
Use lazy_static
`lazy_static` is not imported, this error is hidden behind the
`compact_filters` feature flag.
2021-02-24 13:30:48 +11:00
Tobin Harding
bfe29c4ef6
Use map instead of and_then
As suggested by Clippy us `map` instead of `and_then` with an inner
option.
2021-02-24 13:30:48 +11:00
Tobin Harding
e35601bb19
Use vec! instead of mut and push
As suggested by Clippy, use the `vec!` macro directly instead of
declaring a mutable vector and pushing elements onto it.
2021-02-24 13:30:48 +11:00
Tobin Harding
24df438607
Remove useless question mark operator
Clippy emits:

  warning: Question mark operator is useless here

No need to use the `?` operator inside an `Ok()` statement when
returning, just return directly.
2021-02-24 13:30:48 +11:00
Tobin Harding
cb3b8cf21b
Do not compare vtable
Clippy emits error:

 comparing trait object pointers compares a non-unique vtable address

The vtable is an implementation detail, it may change in future. we
should not be comparing vtable addresses for equality. Instead we can
get a pointer to the data field of a fat pointer and compare on that.
2021-02-24 13:30:48 +11:00
Tobin Harding
0e6add0cfb
Refactor db/batch matching
Remove the TODO; refactor matching to correctly handle conditionally
built `Sled` variants. Use `unreachable` instead of `unimplemented` with
a comment hinting that this is a bug, this makes it explicit, both at
runtime and when reading the code, that this match arm should not be hit.
2021-02-24 13:30:47 +11:00
Tobin Harding
343e97da0e
Conditionally compile constructor
The `ChunksIterator` constructor is only used when either `electrum` or
`esplora` features are enabled. Conditionally build it so that we do not
get a clippy warning when building without these features.
2021-02-24 13:30:47 +11:00
Tobin Harding
ba8ce7233d
Allow mutex_atomic
Clippy complains about use of a mutex, suggesting we use an
 `AtomicUsize`. While the same functionality _could_ be achieved using an
 `AtomicUsize` and a CAS loop it makes the code harder to reason about
 for little gain. Lets just quieten clippy with an allow attribute and
 document why we did so.
2021-02-24 13:30:47 +11:00
Tobin Harding
35184e6908
Use default pattern
Clippy emits warning:

  warning: field assignment outside of initializer for an instance
  created with Default::default()

Do as suggested by clippy and use the default init pattern.

```
    let foo = Foo {
    	bar: ...,
        Default::default()
    }
```
2021-02-24 13:30:47 +11:00
Tobin Harding
824b00c9e0
Use next instead of nth(0)
As suggested by clippy we can use `.next()` on an iterator instead of
`nth(0)`. Although arguably no clearer, and certainly no worse, it keeps
clippy quiet and a clean lint is a good thing.
2021-02-24 13:30:47 +11:00
Tobin Harding
79cab93d49
Use count instead of collect and len
Clippy emits warning:

	warning: avoid using `collect()` when not needed

As suggested by clippy just use `count` directly on the iterator instead
of `collect` followed by `len`.
2021-02-24 13:30:47 +11:00
Tobin Harding
2afc9faa08
Remove needles explicit reference
Clippy emits warning:

	warning: needlessly taken reference of both operands

Remove the explicit reference's as suggested.
2021-02-24 13:30:46 +11:00
Tobin Harding
0e99d02fbe
Remove redundant calls to clone
No need to clone copy types, found by clippy.
2021-02-24 13:30:46 +11:00
Tobin Harding
3a0a1e6d4a
Remove static lifetime
const str types do not need an explicit lifetime, remove it. Found by
clippy.
2021-02-24 13:30:46 +11:00
Tobin Harding
2057c35468
Use ! is_empty instead of len > 0
As directed by clippy use `!a.is_empty()` instead of `a.len() > 0`.
2021-02-24 13:30:46 +11:00
Tobin Harding
5eaa3b0916
Use unwrap_or_else
As directed by clippy use `unwrap_or_else` in order to take advantage of
lazy evaluation.
2021-02-24 13:30:46 +11:00
Steve Myers
4ad0f54c30
[ci] Rename MAGICAL_ env vars to BDK_, for tests use wallet name in RPC calls 2021-02-21 19:47:06 -08:00
Steve Myers
eeff3b5049
[ci] Update start-core.sh to create default wallet for bitcoind 0.21.0 2021-02-21 19:04:52 -08:00
Steve Myers
5e352489a0
Merge branch 'release/0.4.0' 2021-02-17 18:33:11 -08:00
Steve Myers
7ee262ef4b
Fix CHANGELOG 'Unreleased' link 2021-02-17 18:30:18 -08:00
Steve Myers
2759231f7b
Bump version to 0.4.1-dev 2021-02-17 16:32:23 -08:00
Steve Myers
e3f893dbd1
Bump version to 0.4.0 2021-02-17 12:08:43 -08:00
Steve Myers
3f5513a2d6
Update 'bdk-macros', 'bdk-testutils', 'bdk-testutils-macros' dep versions 2021-02-17 12:08:41 -08:00
Steve Myers
fcf5e971a6
Bump 'bdk-macros' version to 0.3.0 2021-02-17 12:08:39 -08:00
Steve Myers
cdf7b33104
Bump 'bdk-testutils' version to 0.3.0 2021-02-17 12:08:37 -08:00
Steve Myers
7bbff79d4b
Bump 'bdk-testutils-macros' version to 0.3.0 2021-02-17 12:08:35 -08:00
Steve Myers
3a2b8bdb85
Small CHANGELOG cleanup 2021-02-17 12:08:33 -08:00
Alekos Filini
7843732e17
[descriptor] Perform additional checks before using a descriptor
Fixes #287
2021-02-17 12:08:31 -08:00
Alekos Filini
fa5a5c8c05
Merge commit 'refs/pull/290/head' of github.com:bitcoindevkit/bdk 2021-02-16 11:54:52 -05:00
Lloyd Fournier
6092c6e789
Don't fix tokio minor version
This is also what they give as an example in their docs: https://docs.rs/tokio/1.2.0/tokio/
2021-02-16 09:57:54 -05:00
Lloyd Fournier
7fe5a30424
Don't fix tokio minor version
This is also what they give as an example in their docs: https://docs.rs/tokio/1.2.0/tokio/
2021-02-16 16:31:55 +11:00
Steve Myers
a82b2155e9
[ci] Manually set rust stable version in CI pipeline 2021-02-15 14:33:10 -08:00
Alekos Filini
b61427c07b
[policy] Allow specifying a policy path for Multisig
While technically it's not required since there are no timelocks inside,
it's still less confusing for the end user if we allow this instead of
failing like we do currently.
2021-02-13 11:17:07 -05:00
Alekos Filini
fa2610538f
[policy] Remove the TooManyItemsSelected error
The `TooManyItemsSelected` error has been removed, since it's not technically an
error but potentailly more of an "over-constraint" over a tx: for instance,
given a `thresh(3,pk(a),pk(b),older(10),older(20))` descriptor one could create
a spending tx with the `[0,1,2]` items that would only be spendable after `10`
blocks, or a tx with the `[0,2,3]` items that would be spendable after `20`.

In this case specifying more items than the threshold would create a tx with
the maximum constraint possible, in this case the `20` blocks. This is not
necessarily an error, so we should allow it without failing.
2021-02-13 11:10:31 -05:00
Alekos Filini
d0ffcdd009
Merge branch 'master' into release/0.4.0
Merging in fixes for the CI after Rust 1.50.0
2021-02-13 11:08:03 -05:00
Steve Myers
1c6864aee8
Rename ToDescriptorKey to IntoDescriptorKey 2021-02-12 23:23:20 -08:00
Steve Myers
d638da2f10
Rename ToWalletDescriptor to IntoWalletDescriptor 2021-02-12 23:23:20 -08:00
Steve Myers
2f7513753c
Update CHANGELOG for rust 1.50.0 clippy changes 2021-02-12 23:23:09 -08:00
Steve Myers
c90a1f70a6
Fix clippy warn on compact_filters peer::_recv() 2021-02-12 22:23:48 -08:00
Steve Myers
04348d0090
Fix clippy warning 'wrong_self_convention' 2021-02-12 22:23:48 -08:00
Steve Myers
eda23491c0
Fix clippy warning 'unnecessary_wraps' 2021-02-12 22:23:29 -08:00
Alekos Filini
dccf09861c
Update version in the examples 2021-02-11 09:29:44 -05:00
Alekos Filini
02b9eda6fa
Update CHANGELOG for release v0.4.0 2021-02-11 09:29:27 -05:00
Alekos Filini
6611ef0e5f
Bump version to 0.4.0-rc.1 2021-02-11 09:27:34 -05:00
Riccardo Casatta
db5e663f05
compact filters balance example 2021-02-10 12:38:07 +01:00
Alekos Filini
c4f21799a6
Merge commit 'refs/pull/278/head' of github.com:bitcoindevkit/bdk 2021-02-05 17:22:52 -05:00
Alekos Filini
fedd92c022
Properly handle the Signet network
Closes #62
2021-02-05 16:51:48 -05:00
Alekos Filini
19eca4e2d1
[compact_filters] Use the new rust-bitcoin API 2021-02-05 16:51:46 -05:00
Alekos Filini
023dabd9b2
Update changelog 2021-02-05 16:51:44 -05:00
Alekos Filini
b44d1f7a92
Update bitcoin, miniscript, electrum-client 2021-02-05 16:51:41 -05:00
Alekos Filini
3d9d6fee07
Update bitcoin, miniscript, electrum-client 2021-02-05 09:11:27 -05:00
Alekos Filini
4c36020e95
Merge commit 'refs/pull/274/head' of github.com:bitcoindevkit/bdk 2021-02-03 10:14:16 -05:00
Alekos Filini
6d01c51c63
Un-pin the version of cc
Fixes #183
2021-02-03 09:57:12 -05:00
Lucas Soriano del Pino
693fb24e02
Emit specific compile error if incompatible features are enabled
This is motivated by the feature `electrum` being part of the
`default` features of this crate. It is easy to naively enable
`esplora` and `async-interface` and forget that `electrum` is enabled
by default, running into not so obvious compile errors.
2021-02-03 18:16:13 +11:00
LLFourn
6689384c8a
Merge branch 'master' into make_txbuilder_take_ref_to_wallet 2021-01-30 13:12:13 +11:00
LLFourn
35a61f5759
Fix whitespace and curse emacs 2021-01-30 13:05:23 +11:00
LLFourn
d0ffd5606a
Fix CHANGELOG to mention s/utxos/add_utxos/ 2021-01-30 12:58:05 +11:00
Alekos Filini
c2b1268675
Merge commit 'refs/pull/270/head' of github.com:bitcoindevkit/bdk 2021-01-29 15:24:39 -05:00
Alekos Filini
ccbbad3e9e
[keys] Improve the API of DerivableKey
A new `ExtendedKey` type has been added, which is basically an enum of
`bip32::ExtendedPubKey` and `bip32::ExtendedPrivKey`, with some extra metadata
regarding the `ScriptContext`.

This type has some methods that make it very easy to extract its content as
either an `xprv` or `xpub`.

The `DerivableKey` trait has been updated so that the user now only has to
implement a method (`DerivableKey::into_extended_key()`) to perform the
conversion into an `ExtendedKey`.

The method that was previously called `add_metadata()` has now been renamed
to `into_descriptor_key()`, and it has
a blanket implementation.
2021-01-29 15:21:36 -05:00
LLFourn
dbf8cf7674
Make maintain_single_recipient return a Result
preferable to panicking.
2021-01-29 12:33:07 +11:00
Steve Myers
eb96ac374b
[ci] Update rust toolchains 2021-01-27 14:53:48 -08:00
Alekos Filini
c431a60171
[signer] Add Signer::id()
Closes #261
2021-01-27 11:43:28 -05:00
Alekos Filini
2e0ca4fe05
Fix the crate version in src/lib.rs 2021-01-26 09:34:14 -05:00
Alekos Filini
df32c849bb
Add a function to return the version of BDK at runtime 2021-01-25 15:14:54 -05:00
Lloyd Fournier
33426d4c3a
Merge branch 'master' into make_txbuilder_take_ref_to_wallet 2021-01-23 17:36:01 +11:00
Alekos Filini
03e6e8126d
Merge commit 'refs/pull/174/head' of github.com:bitcoindevkit/bdk 2021-01-22 10:38:17 -05:00
LLFourn
ff10aa5ceb
Add "add_utxos" method on TxBuilder
To replace the previously existing ".utxos"
2021-01-22 15:08:31 +11:00
LLFourn
21d382315a
Remove not very useful comment
Thanks @tcharding.
2021-01-22 15:08:30 +11:00
LLFourn
6fe3be0243
Derive Clone + Debug for TxBuilder
And make Wallet Debug while I'm at it.
2021-01-22 15:08:30 +11:00
LLFourn
10fcba9439
Revert back to Vec to hold utxos in builder
Due to brain malfunction I made utxos into a BTree. This made a test
pass but is incorrect. The test itself was incorrect as per comment in

https://github.com/bitcoindevkit/bdk/pull/258#issuecomment-758370380

So I (1) reverted utxos back to a Vec, (2) fixed the test and expanded
the comment in the test.
2021-01-22 15:08:30 +11:00
LLFourn
890d6191a1
Remove Option trickery from TxBuilder API
see: https://github.com/bitcoindevkit/bdk/pull/258#issuecomment-754685962
2021-01-22 15:08:30 +11:00
LLFourn
735db02850
Assert that .finish() hasn't been called already in coin_selection 2021-01-22 14:33:37 +11:00
LLFourn
7bf46c7d71
Add comment explaining why params and coin_selection are Options 2021-01-22 14:33:37 +11:00
LLFourn
8319b32466
Fix wrong doc links 2021-01-22 14:33:37 +11:00
LLFourn
0faca43744
Make testutils dependency path relative 2021-01-22 14:33:37 +11:00
LLFourn
6f66de3d16
Update Changelog for Tx creation overhaul 2021-01-22 14:33:37 +11:00
LLFourn
5fb7fdffe1
[wallet] Use doctest_wallet!() to remove some no_runs from doctests
...and improve the fee bumping example while trying to make it
no_run (but failed).
2021-01-22 14:33:37 +11:00
LLFourn
7553b905c4
[wallet] Overhaul TxBuilder internals and externals
Fixes #251

TxBuilders are now not created directly but are created through the
wallet with `build_tx` and `build_fee_bump`.
The advantages of this realised in this commit are:

1. Normal tx creation and fee bumping use the code internally. The only
difference between normal tx and fee bump is how the builder is created.
2. The TxBuilder now has a refernce to the wallet and can therefore
lookup things as methods are called on it. `add_utxo` now uses this to
look up UTXO deta when it is called (rather than having to do it and
possibly error later on).

To support these changes `get_utxo` and `get_descriptor_for_keychain`
public methods have been added to Wallet. I could have kept them
pub(crate) but they seem like fine APIs to have publicly.
2021-01-22 14:33:37 +11:00
LLFourn
f74f17e227
Change "received_tx" into "populate_test_db" macro
A `[cfg(test)]` function is not as helpful as a macro since it can't be
called in the context of a doctest.

Also adds doctest_wallet macro which can be used to create a wallet in a
doctest.
2021-01-22 14:23:36 +11:00
Alekos Filini
7566904926
Merge branch 'release/0.3.0' 2021-01-20 10:59:09 -05:00
Alekos Filini
1420cf8d0f
Bump version to 0.3.1-dev 2021-01-20 10:58:04 -05:00
Alekos Filini
bddd418c8e
Bump version to 0.3.0 2021-01-20 10:39:24 -05:00
Alekos Filini
49db898acb
Update CHANGELOG.md in preparation of tag v0.3.0 2021-01-20 10:27:28 -05:00
Tobin Harding
01585227c5
Use contains combinator
As suggested by clippy, use the `contains` combinator instead of doing
manual range check on floats.
2021-01-18 11:39:37 -08:00
Tobin Harding
03b7c1b46b
Use contains combinator
As suggested by clippy, use the `contains` combinator instead of doing
manual range check on floats.
2021-01-18 10:46:12 -08:00
Tobin Harding
4686ebb420
Add full stops to list items
Super anal patch to make list items uniform, add full stop to the items
where it is missing.
2021-01-18 10:46:10 -08:00
Tobin Harding
082db351c0
Remove unexplainable newlines
It seems the documentation of this project uses arbitrarily long
lines (i.e. no set column width) along with the occasional newline
before some sentences (within a paragraph). When to split a sentence
onto a newline does not seem to follow any discernible pattern.

There are a few instances of newline characters appearing randomly in
the middle of a sentence and since, as observed above, there is no
fixed column width is use these new lines are out of place.

Remove them so the documentation is slightly more uniform and nice to
read in an editor.

This patch is whitespace only, no other textual changes.
2021-01-18 10:46:08 -08:00
Tobin Harding
84db6ce453
Do minor grammar fix 2021-01-18 10:46:06 -08:00
Justin Moon
52b45c5b89
[wallet] Add "needed" and "available" metadata to Error::InsufficientFunds 2021-01-18 11:15:10 +01:00
Justin Moon
5c82789e57
Update CHANGELOG 2021-01-13 23:04:23 -06:00
Justin Moon
7bc8c3c380
[wallet] Add "needed" and "available" metadata to Error::InsufficientFunds 2021-01-13 23:00:37 -06:00
Justin Moon
813c1ddcd0
[blockchain] Upgrade tokio
- Also upgrade reqwest
- Switch to `tokio::runtime::Builder::new_single_thread()` because
`tokio::runtime::Runtime::new()` changed it's behavior to create a
multithreaded runtime.
- `enable_all` enables time and io resource drivers as explained
[here](https://docs.rs/tokio/0.2.24/tokio/runtime/index.html#resource-drivers)
2021-01-13 22:58:02 -06:00
Alekos Filini
733355a6ae
Bump version to 0.3.0-rc.1 2021-01-12 21:41:30 +01:00
Alekos Filini
6955a7776d
Merge commit 'refs/pull/264/head' of github.com:bitcoindevkit/bdk 2021-01-12 14:02:41 +01:00
Alekos Filini
bf04a2cf69
descriptor: Use DescriptorError instead of Error when reasonable
Change the return type of the `descriptor!()` macro and `ToWalletDescriptor` to
avoid having to map errors.

Also introduce more checks to validate descriptors built using the macro.
2021-01-12 12:21:22 +01:00
Riccardo Casatta
2b669afd3e
Permit to not set timeout in ElectrumBlockchainConfig
Allowing to use socks5 which requires None timeout
2021-01-11 14:06:56 +01:00
Steve Myers
8510b2b86e
Fix crates.io license info 2021-01-09 10:41:48 -08:00
Alekos Filini
a95a9f754c
Merge commit 'refs/pull/260/head' of github.com:bitcoindevkit/bdk 2021-01-05 16:06:32 +01:00
Alekos Filini
3980b90bff
Merge commit 'refs/pull/248/head' of github.com:bitcoindevkit/bdk 2021-01-05 16:04:53 +01:00
Alekos Filini
b2bd1b5831
Merge commit 'refs/pull/257/head' of github.com:bitcoindevkit/bdk 2021-01-05 16:01:15 +01:00
Steve Myers
aa31c96821
[ci] Fail 'Build docs' job if warnings 2021-01-04 16:39:11 -08:00
Steve Myers
f74bfdd493
Remove 'cli.rs' module, 'cli-utils' feature and 'repl.rs' example 2020-12-31 09:44:30 -08:00
Steve Myers
5034ca2267
Fix clippy warnings for compact_filters feature 2020-12-30 19:23:35 -08:00
Steve Myers
8094263028
[ci] Fix clippy step to check matrix features 2020-12-30 19:23:00 -08:00
LLFourn
0c9c0716a4
[wallet] Fix details.fees being wrong when change is dust 2020-12-29 16:36:35 +11:00
Alekos Filini
c2b2da7601
Merge commit 'refs/pull/252/head' of github.com:bitcoindevkit/bdk 2020-12-23 18:39:05 +01:00
Alekos Filini
407f14add9
Merge commit 'refs/pull/250/head' of github.com:bitcoindevkit/bdk 2020-12-23 17:48:59 +01:00
LLFourn
656c9c9da8
Use () to indicate a missing blockchain
So that:
1. There are no runtime errors
2. There less type annotations needed
3. Less traits and stuff to document
2020-12-23 14:52:29 +11:00
LLFourn
a578d20282
Fix incredibly annoying cargo-fmt problem
I must have a newer version of cargo-fmt which stops me from making
commits every time because of this.
2020-12-22 14:37:53 +11:00
Steve Myers
2e222c7ad9
[docs] Add badges for crates.io, mit license. Fix docs.rs badge and link 2020-12-21 20:14:25 +01:00
Alekos Filini
7d6cd6d4f5
Fix the changelog after release v0.2.0 2020-12-21 20:14:23 +01:00
Alekos Filini
e31bd812ed
Bump version to 0.2.1-dev 2020-12-21 14:51:49 +01:00
Alekos Filini
76b5273040
Bump version to 0.2.0 2020-12-21 14:16:14 +01:00
Alekos Filini
c910668ce3
Add metadata to Cargo.toml, remove local deps 2020-12-21 14:03:32 +01:00
Alekos Filini
2c7a28337d
Add metadata for bdk-testutils and bdk-testutils-macros, bump their version 2020-12-21 13:16:41 +01:00
Alekos Filini
7be193faa5
[testutils-macros] Fix deps features 2020-12-21 13:16:39 +01:00
Alekos Filini
a5f914b56d
Add metadata for bdk-macros, bump its version 2020-12-21 12:15:10 +01:00
Alekos Filini
c68716481b
Document the development cycle 2020-12-21 12:06:17 +01:00
Alekos Filini
a217494bb1
Bump version to 0.2.0-rc.1 2020-12-18 10:52:10 +01:00
Alekos Filini
63aabe203f
Merge commit 'refs/pull/235/head' of github.com:bitcoindevkit/bdk 2020-12-18 10:41:37 +01:00
Steve Myers
b8c6732c74
[ci] Remove unneeded skip step conditionals in CI 2020-12-17 09:52:48 -08:00
Steve Myers
baa919c96a
Fix empty checkboxes in PR template 2020-12-17 09:52:47 -08:00
Steve Myers
2325a1fcc2
[docs] Format code in docs with '--config format_code_in_doc_comments=true' 2020-12-16 15:12:51 -08:00
Steve Myers
fb5c70fc64
[docs] Replace all 'allow(missing_docs)' with basic docs 2020-12-16 15:12:49 -08:00
Steve Myers
8cfbf1f0a2
[docs] Add more docs to 'types.rs' 2020-12-16 15:12:47 -08:00
Alekos Filini
713411ea5d
[keys] impl ToDescriptorKey for &str 2020-12-16 19:06:02 +01:00
Alekos Filini
7e90657ee1
[descriptor] Make the syntax of descriptor!() more consistent
The syntax now is pretty much the same as the normal descriptor syntax,
with the only difference that modifiers cannot be grouped together (i.e.
`sdv:older(144)` must be turned into `s:d:v:older(144)`.
2020-12-16 19:00:55 +01:00
Riccardo Casatta
635d98c069
[docs] use only sled instead of crate::sled 2020-12-16 12:11:49 +01:00
Riccardo Casatta
680aa2aaf4
[docs] fix NetworkMessage::Ping docs link 2020-12-16 12:11:26 +01:00
Alekos Filini
5f373180ff
Merge commit 'refs/pull/223/head' of github.com:bitcoindevkit/bdk 2020-12-16 11:11:38 +01:00
Alekos Filini
931a110e4e
Merge commit 'refs/pull/229/head' of github.com:bitcoindevkit/bdk 2020-12-16 10:48:10 +01:00
Riccardo Casatta
d2aac4848c
always build docs and create artifacts, publish only on master 2020-12-16 10:16:45 +01:00
Steve Myers
148e8c6088
[docs] Add docs to the 'wallet' module 2020-12-15 15:12:32 -08:00
Steve Myers
1d1d539154
[ci] Fix publishing coverage to codecov.io 2020-12-15 13:36:36 -08:00
Evgenii P
09730c0898
Take ID into account in SignersContainerKey's PartialEq impl 2020-12-15 22:40:07 +07:00
Alekos Filini
6d9472793c
Merge commit 'refs/pull/228/head' of github.com:bitcoindevkit/bdk 2020-12-15 14:33:59 +01:00
Alekos Filini
eadf50042c
[wallet] Add tests for check_nsequence_rbf and check_nlocktime 2020-12-15 12:01:44 +01:00
Alekos Filini
322122afc8
[wallet] Set the correct nSequence when RBF and OP_CSV are used
This commit also fixes the timelock comparing logic in the policy module, since
the rules are different for absolute (OP_CLTV) and relative (OP_CSV) timelocks.

Fixes #215
2020-12-15 12:01:41 +01:00
Evgenii P
5315c3ef25
rustfmt 2020-12-15 11:36:26 +07:00
Evgenii P
c58236fcd7
Fix SignersContainer::find to filter out incorrect IDs 2020-12-15 11:36:26 +07:00
Evgenii P
2658a9b05a
Fix SignersContainerKey PartialOrd to respect the ID 2020-12-15 11:36:26 +07:00
Evgenii P
c075183a7b
Revert replacing BTreeMap to HashMap in SingersContainer 2020-12-15 11:35:34 +07:00
LLFourn
9b31ae9153
Fix doc comment fallout from s/script type/keychain 2020-12-15 08:39:19 +11:00
Alekos Filini
1713d621d4
Rename ScriptType to KeychainKind
This avoids confusion with the "type of script".
2020-12-14 17:14:24 +01:00
Alekos Filini
7adaaf227c
[ci] Ignore empty nightly docs commits instead of failing 2020-12-14 15:16:38 +01:00
Alekos Filini
4ede4a4ad0
Merge commit 'refs/pull/222/head' of github.com:bitcoindevkit/bdk 2020-12-14 11:44:06 +01:00
Alekos Filini
c83cec3777
Merge commit 'refs/pull/221/head' of github.com:bitcoindevkit/bdk 2020-12-14 11:27:51 +01:00
Alekos Filini
0ef0b45745
Merge commit 'refs/pull/224/head' of github.com:bitcoindevkit/bdk 2020-12-14 11:18:51 +01:00
Evgenii P
351b656a82
Use unstable sort by key for performance 2020-12-14 16:27:54 +07:00
Alekos Filini
6c768e5388
Add the pull request template 2020-12-14 10:21:22 +01:00
Steve Myers
f8d3cdca9f
[docs] Add experimental warning to compact_filters and policy modules 2020-12-13 21:04:17 -08:00
Steve Myers
0f2dc05c08
[docs] Add docs to the 'descriptor' module 2020-12-13 20:57:28 -08:00
Steve Myers
4e771d6546
[docs] Add docs to the 'template' module 2020-12-13 20:41:32 -08:00
Steve Myers
60e5cf1f8a
[docs] Add docs to the 'policy' module 2020-12-13 20:40:23 -08:00
Evgenii P
641d9554b1
Ignore broken tests. (#225) 2020-12-14 10:17:12 +07:00
Evgenii P
95af38a01d
rustfmt 2020-12-14 01:03:14 +07:00
Evgenii P
3ceaa33de0
Add unit tests for SignersContainer 2020-12-14 01:03:14 +07:00
Evgenii P
5d190aa87d
Remove debug output 2020-12-14 01:02:48 +07:00
Evgenii P
20e0a4d421
Replace BTreeMap with a HashMap 2020-12-13 18:37:27 +07:00
Alekos Filini
010b7eed97
Merge commit 'refs/pull/218/head' of github.com:bitcoindevkit/bdk 2020-12-11 16:31:17 +01:00
Evgenii P
c9a05c0deb
Fix the REPL example to have optional esplora 2020-12-11 22:19:08 +07:00
Evgenii P
7d7b78534a
Remove unused macro imports 2020-12-11 22:19:08 +07:00
Evgenii P
ff7ba04180
Make "esplora" feature optional for REPL binary 2020-12-11 22:19:07 +07:00
Alekos Filini
c0a92bd084
[keys] Replace (Fingerprint, DerivationPath) with KeySource 2020-12-11 11:16:41 +01:00
Alekos Filini
1a90832f3a
[docs] Add the docs to the keys module 2020-12-11 11:16:39 +01:00
Alekos Filini
9bafdfe2d4
[docs] Various fixes to the docs 2020-12-11 11:16:38 +01:00
Alekos Filini
a1db9f633b
[ci] Test the examples in README.md 2020-12-11 11:16:36 +01:00
Steve Myers
8d6f67c764
Add warn and TODOs for missing_docs and add lib.rs docs 2020-12-08 15:57:31 -08:00
Steve Myers
602ae3d63a
Add TODOs for missing_docs 2020-12-07 18:25:16 -08:00
Steve Myers
3491bfbf30
Fix README.md examples 2020-12-07 18:19:54 -08:00
Steve Myers
400b4a85f3
Fix unused import warning and docs link warning 2020-12-07 11:28:25 -08:00
Alekos Filini
aed2414cad
Merge commit 'refs/pull/214/head' of github.com:bitcoindevkit/bdk 2020-12-07 11:57:32 +01:00
Alekos Filini
592c37897e
Merge commit 'refs/pull/213/head' of github.com:bitcoindevkit/bdk 2020-12-07 11:57:03 +01:00
Alekos Filini
eef59e463d
Merge commit 'refs/pull/210/head' of github.com:bitcoindevkit/bdk 2020-12-07 11:21:21 +01:00
Alekos Filini
8d9365099e
Merge commit 'refs/pull/208/head' of github.com:bitcoindevkit/bdk 2020-12-07 11:09:40 +01:00
Riccardo Casatta
46092a200a
[docs] database/any.rs 2020-12-05 13:26:00 +01:00
Riccardo Casatta
95bfe7c983
[docs] types.rs 2020-12-05 13:25:58 +01:00
Riccardo Casatta
8b1a9d2518
[docs] descriptor/error.rs 2020-12-05 13:25:58 +01:00
Riccardo Casatta
9028d2a16a
[docs] compact_filters/mod.rs 2020-12-05 13:25:57 +01:00
Riccardo Casatta
87eebe466f
[docs] error.rs 2020-12-05 13:25:47 +01:00
Alekos Filini
ee854b9d73
Merge commit 'refs/pull/209/head' of github.com:bitcoindevkit/bdk 2020-12-04 11:57:44 +01:00
Riccardo Casatta
81519555cf
generalize impl_error! macro so that used for other errors type 2020-12-04 11:23:01 +01:00
Riccardo Casatta
586b874a19
Remove EsploraHeader json in favor of raw hex block header 2020-12-04 11:04:31 +01:00
Steve Myers
364b47bfcb
Update cli module to use StructOpt and add docs 2020-12-03 16:18:47 -08:00
LLFourn
8dcb75dfa4
Replace UTXO::is_internal with script_type
This means less conversion and logic mapping from bool to ScriptType and
back again.
2020-12-04 10:46:25 +11:00
Alekos Filini
4aac833073
[ci] Build and publish nightly docs 2020-12-03 19:05:06 +01:00
Steve Myers
2e7f98a371
Fix docs 2020-12-02 16:57:59 -08:00
Riccardo Casatta
a89dd85833
allow missing docs on self-explanatory variants 2020-12-02 14:19:46 -08:00
Riccardo Casatta
a766441fe0
missing docs for esplora.rs (also remove useless pubs) 2020-12-02 14:19:41 -08:00
Riccardo Casatta
68db07b2e3
Missing docs for electrum.rs 2020-12-02 14:19:35 -08:00
Alekos Filini
6b5c3bca82
[changelog] Update CHANGELOG.md to document PSBT_GLOBAL_XPUB
Log the changes made in PR #200
2020-12-01 16:43:41 +01:00
Alekos Filini
5d352ecb63
[wallet] Add tests for TxBuilder::add_global_xpubs() 2020-12-01 16:43:40 +01:00
Alekos Filini
ebfe5db0c3
[wallet] Add a flag to fill-in PSBT_GLOBAL_XPUB 2020-12-01 16:43:38 +01:00
Alekos Filini
e1a59336f8
[cli] Add a flag to build PSBTs for offline signers
The `--offline_signer` flag forces the addition of `non_witness_utxo` and the full
witness and redeem script for every output, which makes it easier for the signer
to identify the change output.

Closes #199
2020-12-01 14:53:00 +01:00
Alekos Filini
59482f795b
[blockchain] Fix clippy warnings 2020-12-01 14:41:59 +01:00
LLFourn
67957a93b9
[wallet] Add wallet.network() 2020-12-01 13:29:20 +11:00
Alekos Filini
9073f761d8
Merge commit 'refs/pull/189/head' of github.com:bitcoindevkit/bdk 2020-11-30 15:38:09 +01:00
Alekos Filini
d6ac752b65
Merge commit 'refs/pull/191/head' of github.com:bitcoindevkit/bdk 2020-11-30 15:17:09 +01:00
Riccardo Casatta
6d1d5d5f57
use electurm-client updated 2020-11-30 13:25:23 +01:00
Alekos Filini
7425985850
Merge commit 'refs/pull/188/head' of github.com:bitcoindevkit/bdk 2020-11-24 11:14:47 +01:00
Alekos Filini
93afdc599c
Switch to miniscript from crates.io 2020-11-24 10:07:37 +01:00
Alekos Filini
4f6e3a4f68
Update tiny-bip39 to v0.8
Fixes #185
2020-11-24 10:01:42 +01:00
Steve Myers
6eac2ca4cf
Fix typo in CONTRIBUTING.md 2020-11-23 21:40:40 -08:00
Steve Myers
790fd52abe
Add CHANGELOG.md 2020-11-23 20:57:23 -08:00
LLFourn
dd35903660
Remove trait bounds on Wallet struct
see: https://github.com/rust-lang/api-guidelines/issues/6
2020-11-24 12:40:58 +11:00
LLFourn
acc0ae14ec
[wallet] Eagerly finalize inputs
If we know the final witness/scriptsig for an input we should add it
right away to the PSBT. Before, if we couldn't finalize any of them we
finalized none of them.
2020-11-23 16:07:50 +11:00
LLFourn
d2490d9ce3
Fix to at least bitcoin ^0.25.2
And fix the fallout.
2020-11-23 15:06:13 +11:00
Alekos Filini
196c2f5450
Merge commit 'refs/pull/172/head' of github.com:bitcoindevkit/bdk 2020-11-20 12:06:41 +01:00
Alekos Filini
8eaf377d2f
Merge commit 'refs/pull/184/head' of github.com:bitcoindevkit/bdk 2020-11-20 11:58:31 +01:00
Riccardo Casatta
73326068f8
Use dirs-next instead of dirs since the latter is unmantained 2020-11-19 17:57:59 +01:00
Justin Moon
9e2b2d04ba
More consistent references with 'signers' variables 2020-11-19 10:27:34 -06:00
Justin Moon
b1b2f2abd6
[wallet] Don't wrap SignersContainer arguments in Arc 2020-11-19 10:27:33 -06:00
Alekos Filini
fc3b6ad0b9
Merge commit 'refs/pull/169/head' of github.com:bitcoindevkit/bdk 2020-11-19 15:41:17 +01:00
Riccardo Casatta
dbfa0506db
Add scheduled audit check in CI 2020-11-19 15:18:04 +01:00
Alekos Filini
0edcc83c13
[ci] Generate a different cache key for every job 2020-11-19 13:59:19 +01:00
Riccardo Casatta
25bde82048
pin cc version because last breaks rocksdb build 2020-11-19 13:11:27 +01:00
Justin Moon
f9d3467397
[wallet] Add witness and redeem scripts to PSBT outputs 2020-11-18 11:40:34 -06:00
Riccardo Casatta
c9079a7292
Allow to set concurrency in Esplora config and optionally pass it in repl 2020-11-18 11:55:20 +01:00
Riccardo Casatta
4c59809f8e
Make esplora call in parallel 2020-11-18 11:08:19 +01:00
Alekos Filini
fe7ecd3dd2
Merge commit 'refs/pull/167/head' of github.com:bitcoindevkit/bdk 2020-11-18 10:44:54 +01:00
Alekos Filini
a601337e0c
Merge commit 'refs/pull/166/head' of github.com:bitcoindevkit/bdk 2020-11-18 10:31:51 +01:00
Riccardo Casatta
ae16c8b602
fix typo 2020-11-18 09:27:01 +01:00
Alekos Filini
6f4d2846d3
[descriptor] Add support for sortedmulti in descriptor! 2020-11-17 23:57:33 +01:00
Alekos Filini
7a42c5e095
Switch to "mainline" rust-miniscript 2020-11-17 23:57:28 +01:00
Riccardo Casatta
b79fa27aa4
Remove unused varaint HeaderParseFail 2020-11-17 18:54:34 +01:00
Riccardo Casatta
8dfbbf2763
Require esplora feature for repl example 2020-11-17 16:47:58 +01:00
Riccardo Casatta
42480ea37b
Bring less data around 2020-11-17 16:38:19 +01:00
Riccardo Casatta
02c0ad2fca
eagerly unwrap height option, save one collect 2020-11-17 16:37:10 +01:00
Riccardo Casatta
16fde66c6a
use flatten instead of unwrap_or 2020-11-17 15:24:26 +01:00
Riccardo Casatta
2844ddec63
avoid a max() call by checking minus or equal 2020-11-17 15:20:33 +01:00
Riccardo Casatta
7a58d3dd7a
Use filter_map instead of filter and map 2020-11-17 15:16:18 +01:00
Riccardo Casatta
4d1617f4e0
use proper type for EsploraHeader, make conversion to BlockHeader infallible 2020-11-17 15:08:04 +01:00
Riccardo Casatta
3c8b8e4fca
conditionally remove cli args according to enabled feature 2020-11-17 15:00:18 +01:00
Riccardo Casatta
2f39a19b01
Use our Instant struct to be compatible with wasm 2020-11-17 14:25:27 +01:00
Riccardo Casatta
d9985c4bbb
[examples] support esplora blockchain source in repl 2020-11-17 09:39:44 +01:00
Riccardo Casatta
c5dba115a0
[sync] Improve sync
Make every request in batch, to save round trip times
Fetch timestamp of blockheader to populate timestamp field in transaction
Remove listunspent requests because we can compute it from our history
2020-11-17 09:39:43 +01:00
LLFourn
35579cb216
[wallet] Build output lookup inside complete transaction
To avoid the caller having to do it.
2020-11-17 15:11:47 +11:00
LLFourn
fcc408f346
[wallet] Add test that shwpkh populates witness_utxo 2020-11-17 15:11:47 +11:00
LLFourn
004f81b0a8
[wallet] Make coin_select return UTXOs instead of TxIns
- We want to keep the metadata in the UTXO around for things later
- It is easier to turn a UTXO into a TxIn outside
2020-11-17 15:11:47 +11:00
Steve Myers
13c1170304
[ci] Remove actions-rs, cleanup names 2020-11-16 18:46:16 -08:00
Alekos Filini
a30ad49f63
[wallet] Use the branch-and-bound cs by default
Keep the `LargestFirst` coin selection for the tests, to make them more
predictable.
2020-11-16 14:08:04 +01:00
Riccardo Casatta
755d76bf54
remove unneeded pub modifier 2020-11-16 12:11:37 +01:00
Riccardo Casatta
25da54d5ec
ignore .idea 2020-11-16 12:09:14 +01:00
Riccardo Casatta
4f99c77abe
[sync] check last derivation in cache to avoid recomputation 2020-11-16 12:06:48 +01:00
Alekos Filini
ac18fb119f
[keys] Add a shortcut to generate keys with the default options 2020-11-13 17:43:57 +01:00
Alekos Filini
f2edee0e2e
[keys] impl ToDescriptorKey for GeneratedKey 2020-11-13 17:29:01 +01:00
Alekos Filini
f4affbd039
[keys] impl GeneratableKey for bitcoin::PrivateKey 2020-11-13 17:27:19 +01:00
Alekos Filini
d269c9e0b2
[cli] Split the internal and external policy paths 2020-11-13 15:00:22 +01:00
Alekos Filini
7c80aec454
[wallet] Take both spending policies into account in create_tx
This allows specifying different "policy paths" for the internal and external
descriptors, and adds additional checks to make sure they are compatibile (i.e.
the timelocks are expressed in the same unit).

It's still suboptimal, since the `n_sequence`s are per-input and not per-transaction,
so it should be possibile to spend different inputs with different, otherwise
incompatible, `CSV` timelocks, but that requires a larger refactor that
can be done in a future patch.

This commit also tries to clarify how the "policy path" should be used by adding
a fairly detailed example to the docs.
2020-11-13 12:55:42 +01:00
Daniela Brozzoni
9f31ad1bc8
[wallet] Replace must_use with required in coin selection 2020-11-13 12:42:07 +01:00
Daniela Brozzoni
c43f201e35
[wallet] Add tests for BranchAndBoundCoinSelection::single_random_draw 2020-11-13 12:42:06 +01:00
Daniela Brozzoni
23824321ba
[wallet] Add tests for BranchAndBoundCoinSelection::bnb 2020-11-13 12:42:06 +01:00
Daniela Brozzoni
be91997d84
[wallet] Add tests for BranchAndBoundCoinSelection::coin_select 2020-11-13 12:42:06 +01:00
Daniela Brozzoni
99060c5627
[wallet] Add Branch and Bound coin selection 2020-11-13 12:42:06 +01:00
Daniela Brozzoni
a86706d1a6
[wallet] Use TXIN_DEFAULT_WEIGHT constant in coin selection
Replace all the occurences of `serialize(&txin)`
with TXIN_DEFAULT_WEIGHT.
2020-11-13 12:42:06 +01:00
Alekos Filini
36c5a4dc0c
[wallet] Split send_all into set_single_recipient and drain_wallet
Previously `send_all` was particularly confusing, because when used on a
`create_tx` it implied two things:
- spend everything that's in the wallet (if no utxos are specified)
- don't create a change output

But when used on a `bump_fee` it only meant to not add a change output
and instead reduce the only existing output to increase the fee.

This has now been split into two separate options that should hopefully
make it more clear to use, as described in #142.

Additionally, `TxBuilder` now has a "context", that basically allows to
make some flags available only when they are actually meaningful, either
for `create_tx` or `bump_fee`.

Closes #142.
2020-11-05 12:06:43 +01:00
Alekos Filini
f67bfe7bfc
Merge commit 'refs/pull/156/head' of github.com:bitcoindevkit/bdk 2020-11-05 11:44:29 +01:00
LLFourn
796f9f5a70
Make Signer and AddressValidator Send and Sync 2020-11-03 16:16:32 +11:00
LLFourn
3b3659fc0c
Remove redundant Box around signers 2020-11-03 16:06:43 +11:00
LLFourn
5784a95e48
Remove redundant Box around address validators 2020-11-03 16:06:43 +11:00
Steve Myers
f7499cb65d
[ci] test with all features enabled in single run 2020-11-02 19:06:41 -08:00
Steve Myers
40bf9f8b79
[ci] Add code coverage github actions workflow 2020-11-02 13:18:52 -08:00
Riccardo Casatta
30f1ff5ab5
[repl] add max_addresses param in sync 2020-10-30 15:04:09 +01:00
Alekos Filini
e6c2823a36
Merge commit 'refs/pull/146/head' of github.com:bitcoindevkit/bdk 2020-10-29 11:53:22 +01:00
Steve Myers
4a75f96d35
[ci] Enable clippy for stable and tests by default 2020-10-28 21:48:40 -07:00
Steve Myers
4f7355ec82
[ci] Fix all-keys and cli-utils tests 2020-10-28 21:34:04 -07:00
Steve Myers
7b9df5bbe5
[ci] Enable clippy and test for optional features 2020-10-28 17:51:03 -07:00
Steve Myers
8d04128c74
[ci] Fix or ignore clippy warnings for all optional features except compact_filters 2020-10-28 17:50:12 -07:00
Murch
457e70e70f
Rename get_must_may_use_utxos to preselect_utxos 2020-10-27 23:24:03 -04:00
Murch
84aee3baab
Rename may_use_utxos to optional_uxtos 2020-10-27 23:24:03 -04:00
Alekos Filini
297e92a829
Merge commit 'refs/pull/115/head' of github.com:bitcoindevkit/bdk 2020-10-27 11:04:00 +01:00
Steve Myers
8927d68a69
[descriptor] Comment out incomplete ExtractPolicy trait tests 2020-10-26 12:48:31 -07:00
Steve Myers
3a80e87ccb
[descriptor] Fix compile errors after rebase 2020-10-26 12:48:27 -07:00
Steve Myers
e31f5306d2
[descriptor] Add descriptor macro tests 2020-10-26 12:48:23 -07:00
Steve Myers
9fa9a304b9
[descriptor] Add get_checksum tests, cleanup tests 2020-10-26 12:48:19 -07:00
Steve Myers
bc0e9c9831
[descriptor] Add ExtractPolicy trait tests 2020-10-26 12:48:15 -07:00
Murch
43a51a1ec3
Rename must_use_utxos to required_utxos 2020-10-26 14:40:44 -04:00
Murch
b2ec6e3683
Rename DumbCS to LargestFirstCoinSelection 2020-10-26 14:20:44 -04:00
LLFourn
8d65581825
Incorporate RBF rules into utxo selection function 2020-10-23 13:54:59 +11:00
LLFourn
a6b70af2fb
[wallet] Stop implicitly enforcing manaul selection by .add_utxo
This makes it possible to choose a UTXO manually without having to
choose them *all* manually. I introduced the `manually_selected_only`
option to enforce that only manually selected utxos can be used.

To stop the cli semantics changing I made the `utxos` keep the old
behaviour by calling `manually_selected_only`.
2020-10-23 13:54:59 +11:00
LLFourn
b87c7c5dc7
[wallet] Make 'unspendable' into a HashSet
to avoid awkwardly later on.
2020-10-23 13:54:59 +11:00
LLFourn
c549281ace
[wallet] Replace ChangeSpendPolicy::filter_utxos with a predicate
To make composing it with other filtering conditions easier.
2020-10-23 13:54:59 +11:00
Richard Ulrich
365a91f805
Merging two match expressions for fee calculation 2020-10-22 13:41:26 +02:00
Richard Ulrich
49894ffa6d
Implementing review suggestions from afilini 2020-10-22 09:11:58 +02:00
Richard Ulrich
759f6eac43
complying with clippy from the github CI 2020-10-20 18:22:37 +02:00
Richard Ulrich
27890cfcff
allow to definie static fees for transactions Fixes #137 2020-10-20 18:10:59 +02:00
Alekos Filini
872d55cb4c
[wallet] Default to SIGHASH_ALL if not specified
Closes #133
2020-10-16 15:40:30 +02:00
Alekos Filini
12635e603f
[wallet] Refactor Wallet::bump_fee() 2020-10-16 14:49:05 +02:00
Alekos Filini
a5713a8348
[wallet] Improve CoinSelectionAlgorithm
Implement the improvements described in issue #121.

Closes #121, closes #131.
2020-10-16 14:30:44 +02:00
LLFourn
17f7294c8e
[wallet] Make coin_select take may/must use utxo lists
so that in the future you can add a UTXO that you *must* spend and let
the coin selection fill in the rest.

This partially addresses #121
2020-10-16 14:28:22 +02:00
LLFourn
64b4cfe308 Use collect to avoid iter unwrapping Options 2020-10-15 13:41:36 +11:00
Alekos Filini
0caad5f3d9
[blockchain] Fix receiving a coinbase using Electrum/Esplora
Closes #107
2020-10-13 11:56:59 +02:00
Alekos Filini
848b52c50e
[keys]: Re-export tiny-bip39
Closes #104
2020-10-13 10:57:40 +02:00
Alekos Filini
100f0aaa0a
Bump rust-bitcoin to 0.25, fix Cargo dependencies
Closes #112, closes #113, closes #124
2020-10-13 10:39:48 +02:00
Steve Myers
69ef56cfed
[ci] Remove travis.yml 2020-10-12 09:30:20 -07:00
Steve Myers
070d481849
[ci] Fix clippy warnings for 1.47.0 2020-10-10 10:31:08 -07:00
Steve Myers
98803b2573
[ci] Use bitcoindevkit/electrs base image for electrum tests 2020-10-10 10:31:08 -07:00
Steve Myers
aea9abff8a
[ci] Fix clippy warnings, enable clippy checks 2020-10-10 10:31:07 -07:00
Steve Myers
6402fd07c2
[ci] Consolidate build, test, clippy jobs 2020-10-10 10:31:07 -07:00
Alekos Filini
8e7b195e93
Add a Discord badge to the README 2020-10-07 10:00:06 +02:00
Steve Myers
56bcbc4aff
[ci] add CI github actions 2020-10-05 09:35:54 -07:00
Alekos Filini
1faf0ed0a0
Fix the recovery of a descriptor given a PSBT
This commit upgrades `rust-miniscript` with a fix to only return the prefix that
matches a `hd_keypath` instead of the full derivation path, and then adapts the
signer code accordingly.

This commit closes #108 and #109.
2020-10-02 17:52:11 +02:00
LLFourn
490c88934e [keys] Less convoluted entropy generation
Since const generics aren't in rust yet you have to find some awkward
workarounds. This improves the workaround for specifying entropy length.
2020-09-30 20:05:17 +10:00
Steve Myers
eae15563d8
[descriptor] add ToWalletDescriptor trait tests 2020-09-25 22:21:11 -07:00
Alekos Filini
82251a8de4
[keys] Fix entropy generation 2020-09-24 15:59:46 +02:00
Alekos Filini
b294b11c54
[keys] Add a trait for keys that can be generated 2020-09-24 09:53:56 +02:00
Alekos Filini
c93cd1414a
[descriptor] Add descriptor templates, add DerivableKey 2020-09-24 09:53:54 +02:00
Alekos Filini
c51ba4a99f
[keys] Add a way to restrict the networks in which keys are valid
Thanks to the `ToWalletDescriptor` trait we can also very easily validate the checksum
for descriptors that are loaded from strings, if they contain one. Fixes #20.
2020-09-24 09:53:51 +02:00
Alekos Filini
bc8acaf088
[keys] Take ScriptContext into account when converting keys 2020-09-24 09:53:48 +02:00
Alekos Filini
ab9d964868
[keys] Add BIP39 support 2020-09-24 09:53:46 +02:00
Alekos Filini
751a553925
[descriptor] Improve the descriptor macro, add traits for key and descriptor types 2020-09-24 09:53:42 +02:00
Alekos Filini
9832ecb660
[descriptor] Add a macro to write descriptors from code 2020-09-24 09:53:41 +02:00
willcl-ark
4970d1e522
Add CONTRIBUTING.md
Add a CONTRIBUTING.md file based on a template taken from the
rust-lightning project.
2020-09-23 10:19:53 +01:00
willcl-ark
844820dcfa
Prettify README examples on github 2020-09-21 15:32:38 +01:00
Alekos Filini
33a5ba6cd2
[signer] Fix signing for ShWpkh inputs 2020-09-16 17:50:54 +02:00
Alekos Filini
cf2a8bccac
[cargo] Add the required rand features for wasm32 2020-09-16 17:30:11 +02:00
Alekos Filini
57ea653f1c
[database] Add AnyDatabase and ConfigurableDatabase
This is related to #43
2020-09-15 15:39:15 +02:00
Alekos Filini
5b0fd3bba0
[blockchain] Document AnyBlockchain and ConfigurableBlockchain 2020-09-15 15:38:59 +02:00
Alekos Filini
e5cc8d9529
[blockchain] Add an AnyBlockchain enum to allow switching at runtime
This is related to #43
2020-09-15 12:03:07 +02:00
Alekos Filini
5eee18bed2
[blockchain] Add a trait to create Blockchains from a configuration
This is the first set of changes for #42
2020-09-15 12:03:04 +02:00
Alekos Filini
6094656a54 Update the README 2020-09-14 15:13:43 -07:00
Alekos Filini
10ab293e18 [cargo] Remove the magic alias for repl 2020-09-14 15:13:43 -07:00
Alekos Filini
d7ee38cc52 Rename the library to bdk 2020-09-14 15:13:43 -07:00
Alekos Filini
efdd11762c
[blockchain] Simplify the architecture of blockchain traits
Instead of having two traits, `Blockchain` and `OnlineBlockchain` that need
to be implemented by the user, only the relevant one (`OnlineBlockchain`, here
renamed to `Blockchain`) will need to be implemented, since we provide a
blanket implementation for the "marker" trait (previously `Blockchain`, here
renamed to `BlockchainMarker`).

Users of the library will probably never need to implement `BlockchainMarker`
by itself, since we expose the `OfflineBlockchain` type that already does
that and should be good for any "offline" wallet. Still, it's exposed since
they might need to import it to define types with generics.
2020-09-10 10:45:07 +02:00
Alekos Filini
24fcb38565
[repl] Revert back the repl example to use Electrum 2020-09-09 17:06:35 +02:00
Alekos Filini
5d977bc617
Bump version to 0.1.0-beta.1 2020-09-08 15:26:44 +02:00
Alekos Filini
cc07c61b47
Change docs link while we can't publish the crate 2020-09-08 15:24:44 +02:00
Alekos Filini
c4f4f20d8b
Improve the README, add examples 2020-09-07 16:33:08 +02:00
LLFourn
6a2d0db674 Remove assumed "/api" prefix from esplora
It is not necessary that esplora is hosted with a /api prefix
2020-09-05 14:00:50 +10:00
Alekos Filini
7b58a4ad6f
Fix the last_derivation_index calculation
It should be set to `0` if not transactions are found during sync.

Closes #44
2020-09-04 21:53:31 +02:00
Alekos Filini
43cb0331bf
Rename the crate to just "magical" 2020-09-04 17:01:33 +02:00
Alekos Filini
ac06e35c49
Add docs for Wallet 2020-09-04 16:29:25 +02:00
Alekos Filini
eee75219e0
Write more docs, make TxBuilder::with_recipients take Scripts 2020-09-04 16:07:41 +02:00
Alekos Filini
7065c1fed6
Write more docs 2020-09-04 11:44:49 +02:00
Alekos Filini
6b9c363937
Write the docs for blockchain::* 2020-09-03 11:36:07 +02:00
Alekos Filini
c0867a6adc
General cleanup for the docs 2020-08-31 15:04:27 +02:00
Alekos Filini
d61e974dbe
Add the license to every file 2020-08-31 11:48:25 +02:00
Alekos Filini
7a127d0275
[wallet] Add tests for Wallet::sign() 2020-08-30 20:38:24 +02:00
Alekos Filini
ff50087de5
[wallet] Support signing the whole tx instead of individual inputs 2020-08-30 20:38:22 +02:00
Alekos Filini
991db28170
[wallet] Add explicit ordering for the signers 2020-08-30 20:38:20 +02:00
Alekos Filini
f54243fd18
[error] implement std::error::Error 2020-08-30 20:38:17 +02:00
Alekos Filini
895c6b0808
[blockchain] impl OnlineBlockchain for types wrapped in Arc 2020-08-30 20:38:14 +02:00
Alekos Filini
557f7ef8c9
[wallet] Add AddressValidators 2020-08-30 20:36:25 +02:00
Alekos Filini
37a7547e9c
[descriptor] Tests for DescriptorMeta::derive_from_psbt_input() 2020-08-30 20:36:23 +02:00
Alekos Filini
21318eb940
[cli] Make the REPL return JSON 2020-08-30 20:36:21 +02:00
Alekos Filini
5777431135
Use miniscript::DescriptorPublicKey
This allows us to remove all our custom "ExtendedDescriptor" implementation since that is
now built directly in miniscript.
2020-08-30 20:36:19 +02:00
Alekos Filini
ddc2bded99
[compact_filters] Add support for Tor 2020-08-30 17:24:04 +02:00
Alekos Filini
77c95b93ac
Compact Filters blockchain implementation 2020-08-30 17:23:33 +02:00
Alekos Filini
c12aa3d327
Implement RBF and add a few tests 2020-08-14 12:48:07 +02:00
Alekos Filini
8f8c393f6f
[tests] Run Bitcoin Core and Electrs on Travis 2020-08-11 11:31:19 +02:00
Alekos Filini
53b5f23fb2
[tests] Add tests for Wallet::create_tx() 2020-08-11 11:31:11 +02:00
Alekos Filini
9e5023670e
[tests] Add a proc macro to generate tests for OnlineBlockchain types 2020-08-10 17:18:17 +02:00
Alekos Filini
c90c752f21
[wallet] Add force_non_witness_utxo() to TxBuilder 2020-08-10 17:18:15 +02:00
Alekos Filini
8d9ccf8d0b
[wallet] Allow limiting the use of internal utxos in TxBuilder 2020-08-10 17:18:13 +02:00
Alekos Filini
85090a28eb
[wallet] Add RBF and custom versions in TxBuilder 2020-08-10 17:18:11 +02:00
Alekos Filini
0665c9e854
[wallet] TxOrdering, shuffle/bip69 support 2020-08-10 17:18:09 +02:00
Alekos Filini
7005a26fc5
[wallet] Nicer interface for WalletExport 2020-08-10 13:20:48 +02:00
Alekos Filini
f7f99172fe
Add a feature to enable the async interface on non-wasm32 platforms
Follow-up to: #28
2020-08-10 11:41:19 +02:00
Alekos Filini
f0a1e670df
[examples] Use MemoryDatabase in the compiler example 2020-08-08 09:37:25 +02:00
Alekos Filini
a5188209b2
Update .travis.ci to test the miniscriptc example 2020-08-08 09:27:52 +02:00
Dominik Spicher
462d413b02 [examples] Fix Miniscript variants issue in compiler example
miniscript has extended the `Miniscript` struct to be generic
over a `ScriptContext`. This context is different for the `Sh`
variant (`Legacy`) than for the `Wsh` and `ShWsh` variants
(`Segwitv0`). Therefore, Rust is not happy with the single
`compiled` variable if it is used as an argument for all three
variants.
2020-08-07 16:08:23 +02:00
Dominik Spicher
a581457ba8 [examples] Add missing dependency for compiler example 2020-08-07 16:02:32 +02:00
Dominik Spicher
796a3a5c91 [examples] Fix renamed thresh_m descriptor
In miniscript 1.0, `thresh_m` has been renamed to `multi`
2020-08-07 15:17:59 +02:00
Alekos Filini
08792b2fcd
[wallet] Add a type convert fee units, add Wallet::estimate_fee() 2020-08-07 11:23:46 +02:00
Alekos Filini
5f80950971
[export] Implement the wallet import/export format from FullyNoded
This commit closes #31
2020-08-07 10:19:06 +02:00
Alekos Filini
82c7e11bd5
Improve .travis.ci 2020-08-06 19:30:17 +02:00
Alekos Filini
b67bbeb202
[wallet] Refill the address pool whenever necessary 2020-08-06 18:11:07 +02:00
Alekos Filini
7a23b2b558
[wallet] Abstract coin selection in a separate trait 2020-08-06 16:56:41 +02:00
Alekos Filini
499e579824
[wallet] Add a TxBuilder struct to simplify create_tx()'s interface 2020-08-06 14:28:22 +02:00
Alekos Filini
927c2f37b9
[wallet] Abstract, multi-platform datetime utils 2020-08-06 14:28:20 +02:00
Alekos Filini
0954049df0
[wallet] Cleanup, remove unnecessary mutable references 2020-08-06 14:28:12 +02:00
Alekos Filini
5683a83288
[repl] Expose list_transactions() in the REPL 2020-07-21 18:37:15 +02:00
Alekos Filini
4fcf7ac89e
Make the blockchain interface async again on wasm32-unknown-unknown
The procedural macro `#[maybe_async]` makes a method or every method of a trait
"async" whenever the target_arch is `wasm32`, and leaves them untouched on
every other platform.

The macro `maybe_await!($e:expr)` can be used to call `maybe_async` methods on
multi-platform code: it expands to `$e` on non-wasm32 platforms and to
`$e.await` on wasm32.

The macro `await_or_block!($e:expr)` can be used to contain async code as much
as possible: it expands to `tokio::runtime::Runtime::new().unwrap().block_on($e)`
on non-wasm32 platforms, and to `$e.await` on wasm32.
2020-07-20 20:02:24 +02:00
Alekos Filini
4a51d50e1f
Update miniscript to version 1.0 2020-07-19 19:31:40 +02:00
Alekos Filini
123984e99d
Remove async, upgrade electrum-client 2020-07-17 09:44:01 +02:00
Alekos Filini
c3923b66f8
Remove unused file 2020-06-30 17:21:56 +02:00
Alekos Filini
ea62337f0d
[database] Replace DerivationPaths with single u32s 2020-06-30 15:21:14 +02:00
Alekos Filini
2fb104824a
[wallet] Add hd_keypaths to outputs 2020-06-30 14:01:38 +02:00
168 changed files with 42299 additions and 6463 deletions

26
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@ -0,0 +1,26 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'bug'
assignees: ''
---
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
**To Reproduce**
<!-- Steps or code to reproduce the behavior. -->
**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
**Build environment**
- BDK tag/commit: <!-- e.g. v0.13.0, 3a07614 -->
- OS+version: <!-- e.g. ubuntu 20.04.01, macOS 12.0.1, windows -->
- Rust/Cargo version: <!-- e.g. 1.56.0 -->
- Rust/Cargo target: <!-- e.g. x86_64-apple-darwin, x86_64-unknown-linux-gnu, etc. -->
**Additional context**
<!-- Add any other context about the problem here. -->

View File

@ -0,0 +1,17 @@
---
name: Enhancement request
about: Request a new feature or change to an existing feature
title: ''
labels: 'enhancement'
assignees: ''
---
**Describe the enhancement**
<!-- A clear and concise description of what you would like added or changed. -->
**Use case**
<!-- Tell us how you or others will use this new feature or change to an existing feature. -->
**Additional context**
<!-- Add any other context about the enhancement here. -->

99
.github/ISSUE_TEMPLATE/minor_release.md vendored Normal file
View File

@ -0,0 +1,99 @@
---
name: Minor Release
about: Create a new minor release [for release managers only]
title: 'Release MAJOR.MINOR+1.0'
labels: 'release'
assignees: ''
---
## Create a new minor release
### Summary
<--release summary to be used in announcements-->
### Commit
<--latest commit ID to include in this release-->
### Changelog
<--add notices from PRs merged since the prior release, see ["keep a changelog"]-->
### Checklist
Release numbering must follow [Semantic Versioning]. These steps assume the current `master`
branch **development** version is *MAJOR.MINOR.0*.
#### On the day of the feature freeze
Change the `master` branch to the next MINOR+1 version:
- [ ] Switch to the `master` branch.
- [ ] Create a new PR branch called `bump_dev_MAJOR_MINOR+1`, eg. `bump_dev_0_22`.
- [ ] Bump the `bump_dev_MAJOR_MINOR+1` branch to the next development MINOR+1 version.
- Change the `Cargo.toml` version value to `MAJOR.MINOR+1.0`.
- Update the `CHANGELOG.md` file.
- The commit message should be "Bump version to MAJOR.MINOR+1.0".
- [ ] Create PR and merge the `bump_dev_MAJOR_MINOR+1` branch to `master`.
- Title PR "Bump version to MAJOR.MINOR+1.0".
Create a new release branch and release candidate tag:
- [ ] Double check that your local `master` is up-to-date with the upstream repo.
- [ ] Create a new branch called `release/MAJOR.MINOR+1` from `master`.
- [ ] Bump the `release/MAJOR.MINOR+1` branch to `MAJOR.MINOR+1.0-rc.1` version.
- Change the `Cargo.toml` version value to `MAJOR.MINOR+1.0-rc.1`.
- The commit message should be "Bump version to MAJOR.MINOR+1.0-rc.1".
- [ ] Add a tag to the `HEAD` commit in the `release/MAJOR.MINOR+1` branch.
- The tag name should be `vMAJOR.MINOR+1.0-rc.1`
- Use message "Release MAJOR.MINOR+1.0 rc.1".
- Make sure the tag is signed, for extra safety use the explicit `--sign` flag.
- [ ] Push the `release/MAJOR.MINOR` branch and new tag to the `bitcoindevkit/bdk` repo.
- Use `git push --tags` option to push the new `vMAJOR.MINOR+1.0-rc.1` tag.
If any issues need to be fixed before the *MAJOR.MINOR+1.0* version is released:
- [ ] Merge fix PRs to the `master` branch.
- [ ] Git cherry-pick fix commits to the `release/MAJOR.MINOR+1` branch.
- [ ] Verify fixes in `release/MAJOR.MINOR+1` branch.
- [ ] Bump the `release/MAJOR.MINOR+1` branch to `MAJOR.MINOR+1.0-rc.x+1` version.
- Change the `Cargo.toml` version value to `MAJOR.MINOR+1.0-rc.x+1`.
- The commit message should be "Bump version to MAJOR.MINOR+1.0-rc.x+1".
- [ ] Add a tag to the `HEAD` commit in the `release/MAJOR.MINOR+1` branch.
- The tag name should be `vMAJOR.MINOR+1.0-rc.x+1`, where x is the current release candidate number.
- Use tag message "Release MAJOR.MINOR+1.0 rc.x+1".
- Make sure the tag is signed, for extra safety use the explicit `--sign` flag.
- [ ] Push the new tag to the `bitcoindevkit/bdk` repo.
- Use `git push --tags` option to push the new `vMAJOR.MINOR+1.0-rc.x+1` tag.
#### On the day of the release
Tag and publish new release:
- [ ] Bump the `release/MAJOR.MINOR+1` branch to `MAJOR.MINOR+1.0` version.
- Change the `Cargo.toml` version value to `MAJOR.MINOR+1.0`.
- The commit message should be "Bump version to MAJOR.MINOR+1.0".
- [ ] Add a tag to the `HEAD` commit in the `release/MAJOR.MINOR+1` branch.
- The tag name should be `vMAJOR.MINOR+1.0`
- The first line of the tag message should be "Release MAJOR.MINOR+1.0".
- In the body of the tag message put a copy of the **Summary** and **Changelog** for the release.
- Make sure the tag is signed, for extra safety use the explicit `--sign` flag.
- [ ] Wait for the CI to finish one last time.
- [ ] Push the new tag to the `bitcoindevkit/bdk` repo.
- [ ] Publish **all** the updated crates to crates.io.
- [ ] Create the release on GitHub.
- Go to "tags", click on the dots on the right and select "Create Release".
- Set the title to `Release MAJOR.MINOR+1.0`.
- In the release notes body put the **Summary** and **Changelog**.
- Use the "+ Auto-generate release notes" button to add details from included PRs.
- Until we reach a `1.0.0` release check the "Pre-release" box.
- [ ] Make sure the new release shows up on [crates.io] and that the docs are built correctly on [docs.rs].
- [ ] Announce the release, using the **Summary**, on Discord, Twitter and Mastodon.
- [ ] Celebrate 🎉
[Semantic Versioning]: https://semver.org/
[crates.io]: https://crates.io/crates/bdk
[docs.rs]: https://docs.rs/bdk/latest/bdk
["keep a changelog"]: https://keepachangelog.com/en/1.0.0/

71
.github/ISSUE_TEMPLATE/patch_release.md vendored Normal file
View File

@ -0,0 +1,71 @@
---
name: Patch Release
about: Create a new patch release [for release managers only]
title: 'Release MAJOR.MINOR.PATCH+1'
labels: 'release'
assignees: ''
---
## Create a new patch release
### Summary
<--release summary to be used in announcements-->
### Commit
<--latest commit ID to include in this release-->
### Changelog
<--add notices from PRs merged since the prior release, see ["keep a changelog"]-->
### Checklist
Release numbering must follow [Semantic Versioning]. These steps assume the current `master`
branch **development** version is *MAJOR.MINOR.PATCH*.
### On the day of the patch release
Change the `master` branch to the new PATCH+1 version:
- [ ] Switch to the `master` branch.
- [ ] Create a new PR branch called `bump_dev_MAJOR_MINOR_PATCH+1`, eg. `bump_dev_0_22_1`.
- [ ] Bump the `bump_dev_MAJOR_MINOR` branch to the next development PATCH+1 version.
- Change the `Cargo.toml` version value to `MAJOR.MINOR.PATCH+1`.
- Update the `CHANGELOG.md` file.
- The commit message should be "Bump version to MAJOR.MINOR.PATCH+1".
- [ ] Create PR and merge the `bump_dev_MAJOR_MINOR_PATCH+1` branch to `master`.
- Title PR "Bump version to MAJOR.MINOR.PATCH+1".
Cherry-pick, tag and publish new PATCH+1 release:
- [ ] Merge fix PRs to the `master` branch.
- [ ] Git cherry-pick fix commits to the `release/MAJOR.MINOR` branch to be patched.
- [ ] Verify fixes in `release/MAJOR.MINOR` branch.
- [ ] Bump the `release/MAJOR.MINOR.PATCH+1` branch to `MAJOR.MINOR.PATCH+1` version.
- Change the `Cargo.toml` version value to `MAJOR.MINOR.MINOR.PATCH+1`.
- The commit message should be "Bump version to MAJOR.MINOR.PATCH+1".
- [ ] Add a tag to the `HEAD` commit in the `release/MAJOR.MINOR` branch.
- The tag name should be `vMAJOR.MINOR.PATCH+1`
- The first line of the tag message should be "Release MAJOR.MINOR.PATCH+1".
- In the body of the tag message put a copy of the **Summary** and **Changelog** for the release.
- Make sure the tag is signed, for extra safety use the explicit `--sign` flag.
- [ ] Wait for the CI to finish one last time.
- [ ] Push the new tag to the `bitcoindevkit/bdk` repo.
- [ ] Publish **all** the updated crates to crates.io.
- [ ] Create the release on GitHub.
- Go to "tags", click on the dots on the right and select "Create Release".
- Set the title to `Release MAJOR.MINOR.PATCH+1`.
- In the release notes body put the **Summary** and **Changelog**.
- Use the "+ Auto-generate release notes" button to add details from included PRs.
- Until we reach a `1.0.0` release check the "Pre-release" box.
- [ ] Make sure the new release shows up on [crates.io] and that the docs are built correctly on [docs.rs].
- [ ] Announce the release, using the **Summary**, on Discord, Twitter and Mastodon.
- [ ] Celebrate 🎉
[Semantic Versioning]: https://semver.org/
[crates.io]: https://crates.io/crates/bdk
[docs.rs]: https://docs.rs/bdk/latest/bdk
["keep a changelog"]: https://keepachangelog.com/en/1.0.0/

View File

@ -0,0 +1,77 @@
---
name: Summer of Bitcoin Project
about: Template to suggest a new https://www.summerofbitcoin.org/ project.
title: ''
labels: 'summer-of-bitcoin'
assignees: ''
---
<!--
## Overview
Project ideas are scoped for a university-level student with a basic background in CS and bitcoin
fundamentals - achievable over 12-weeks. Below are just a few types of ideas:
- Low-hanging fruit: Relatively short projects with clear goals; requires basic technical knowledge
and minimal familiarity with the codebase.
- Core development: These projects derive from the ongoing work from the core of your development
team. The list of features and bugs is never-ending, and help is always welcome.
- Risky/Exploratory: These projects push the scope boundaries of your development effort. They
might require expertise in an area not covered by your current development team. They might take
advantage of a new technology. There is a reasonable chance that the project might be less
successful, but the potential rewards make it worth the attempt.
- Infrastructure/Automation: These projects are the code that your organization uses to get its
development work done; for example, projects that improve the automation of releases, regression
tests and automated builds. This is a category where a Summer of Bitcoin student can be really
helpful, doing work that the development team has been putting off while they focus on core
development.
- Quality Assurance/Testing: Projects that work on and test your project's software development
process. Additionally, projects that involve a thorough test and review of individual PRs.
- Fun/Peripheral: These projects might not be related to the current core development focus, but
create new innovations and new perspectives for your project.
-->
**Description**
<!-- Description: 3-7 sentences describing the project background and tasks to be done. -->
**Expected Outcomes**
<!-- Short bullet list describing what is to be accomplished -->
**Resources**
<!-- 2-3 reading materials for candidate to learn about the repo, project, scope etc -->
<!-- Recommended reading such as a developer/contributor guide -->
<!-- [Another example a paper citation](https://arxiv.org/pdf/1802.08091.pdf) -->
<!-- [Another example an existing issue](https://github.com/opencv/opencv/issues/11013) -->
<!-- [An existing related module](https://github.com/opencv/opencv_contrib/tree/master/modules/optflow) -->
**Skills Required**
<!-- 3-4 technical skills that the candidate should know -->
<!-- hands on experience with git -->
<!-- mastery plus experience coding in C++ -->
<!-- basic knowledge in matrix and tensor computations, college course work in cryptography -->
<!-- strong mathematical background -->
<!-- Bonus - has experience with React Native. Best if you have also worked with OSSFuzz -->
**Mentor(s)**
<!-- names of mentor(s) for this project go here -->
**Difficulty**
<!-- Easy, Medium, Hard -->
**Competency Test (optional)**
<!-- 2-3 technical tasks related to the project idea or repository youd like a candidate to
perform in order to demonstrate competency, good first bugs, warm-up exercises -->
<!-- ex. Read the instructions here to get Bitcoin core running on your machine -->
<!-- ex. pick an issue labeled as “newcomer” in the repository, and send a merge request to the
repository. You can also suggest some other improvement that we did not think of yet, or
something that you find interesting or useful -->
<!-- ex. fixes for coding style are usually easy to do, and are good issues for first time
contributions for those learning how to interact with the project. After you are done with the
coding style issue, try making a different contribution. -->
<!-- ex. setup a full Debian packaging development environment and learn the basics of Debian
packaging. Then identify and package the missing dependencies to package Specter Desktop -->
<!-- ex. write a pull parser for CSV files. You'll be judged by the decisions to store the parser
state and how flexible it is to wrap this parser in other scenarios. -->
<!-- ex. Stretch Goal: Implement some basic metaprogram/app to prove you're very familiar with BDK.
Be prepared to make adjustments as we judge your solution. -->

8
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,8 @@
# Set update schedule for GitHub Actions
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
# Check for updates to GitHub Actions every week
interval: "weekly"

34
.github/pull_request_template.md vendored Normal file
View File

@ -0,0 +1,34 @@
<!-- You can erase any parts of this template not applicable to your Pull Request. -->
### Description
<!-- Describe the purpose of this PR, what's being adding and/or fixed -->
### Notes to the reviewers
<!-- In this section you can include notes directed to the reviewers, like explaining why some parts
of the PR were done in a specific way -->
### Changelog notice
<!-- Notice the release manager should include in the release tag message changelog -->
<!-- See https://keepachangelog.com/en/1.0.0/ for examples -->
### Checklists
#### All Submissions:
* [ ] I've signed all my commits
* [ ] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
* [ ] I ran `cargo fmt` and `cargo clippy` before committing
#### New Features:
* [ ] I've added tests for the new feature
* [ ] I've added docs for the new feature
#### Bugfixes:
* [ ] This pull request breaks the existing API
* [ ] I've added tests to reproduce the issue which are now passing
* [ ] I'm linking the issue being fixed by this PR

19
.github/workflows/audit.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: Audit
on:
push:
paths:
- '**/Cargo.toml'
- '**/Cargo.lock'
schedule:
- cron: '0 0 * * 0' # Once per week
jobs:
security_audit:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions-rs/audit-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}

57
.github/workflows/code_coverage.yml vendored Normal file
View File

@ -0,0 +1,57 @@
on: [push, pull_request]
name: Code Coverage
jobs:
Codecov:
name: Code Coverage
runs-on: ubuntu-latest
env:
RUSTFLAGS: "-Cinstrument-coverage"
RUSTDOCFLAGS: "-Cinstrument-coverage"
LLVM_PROFILE_FILE: "./target/coverage/%p-%m.profraw"
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install lcov tools
run: sudo apt-get install lcov -y
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
profile: minimal
components: llvm-tools-preview
- name: Rust Cache
uses: Swatinem/rust-cache@v2.2.1
- name: Install grcov
run: if [[ ! -e ~/.cargo/bin/grcov ]]; then cargo install grcov; fi
# TODO: re-enable the hwi tests
- name: Build simulator image
run: docker build -t hwi/ledger_emulator ./ci -f ci/Dockerfile.ledger
- name: Run simulator image
run: docker run --name simulator --network=host hwi/ledger_emulator &
- name: Install Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install python dependencies
run: pip install hwi==2.1.1 protobuf==3.20.1
- name: Test
run: cargo test --all-features
- name: Make coverage directory
run: mkdir coverage
- name: Run grcov
run: grcov . --binary-path ./target/debug/ -s . -t lcov --branch --ignore-not-existing --keep-only '**/crates/**' --ignore '**/tests/**' --ignore '**/examples/**' -o ./coverage/lcov.info
- name: Generate HTML coverage report
run: genhtml -o coverage-report.html --ignore-errors source ./coverage/lcov.info
- name: Coveralls upload
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload artifact
uses: actions/upload-artifact@v2
with:
name: coverage-report
path: coverage-report.html

132
.github/workflows/cont_integration.yml vendored Normal file
View File

@ -0,0 +1,132 @@
on: [push, pull_request]
name: CI
jobs:
build-test:
name: Build and test
runs-on: ubuntu-latest
strategy:
matrix:
rust:
- version: stable
clippy: true
- version: 1.63.0 # MSRV
features:
- --no-default-features
- --all-features
steps:
- name: checkout
uses: actions/checkout@v2
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.rust.version }}
override: true
profile: minimal
- name: Rust Cache
uses: Swatinem/rust-cache@v2.2.1
- name: Pin dependencies for MSRV
if: matrix.rust.version == '1.63.0'
run: |
cargo update -p zstd-sys --precise "2.0.8+zstd.1.5.5"
cargo update -p time --precise "0.3.20"
cargo update -p home --precise "0.5.5"
cargo update -p proptest --precise "1.2.0"
cargo update -p url --precise "2.5.0"
cargo update -p cc --precise "1.0.105"
cargo update -p tokio --precise "1.38.1"
- name: Build
run: cargo build ${{ matrix.features }}
- name: Test
run: cargo test ${{ matrix.features }}
check-no-std:
name: Check no_std
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
profile: minimal
# target: "thumbv6m-none-eabi"
- name: Rust Cache
uses: Swatinem/rust-cache@v2.2.1
- name: Check bdk_chain
working-directory: ./crates/chain
# TODO "--target thumbv6m-none-eabi" should work but currently does not
run: cargo check --no-default-features --features miniscript/no-std,hashbrown
- name: Check bdk wallet
working-directory: ./crates/wallet
# TODO "--target thumbv6m-none-eabi" should work but currently does not
run: cargo check --no-default-features --features miniscript/no-std,bdk_chain/hashbrown
- name: Check esplora
working-directory: ./crates/esplora
# TODO "--target thumbv6m-none-eabi" should work but currently does not
run: cargo check --no-default-features --features miniscript/no-std,bdk_chain/hashbrown
check-wasm:
name: Check WASM
runs-on: ubuntu-20.04
env:
CC: clang-10
CFLAGS: -I/usr/include
steps:
- name: Checkout
uses: actions/checkout@v2
# Install a recent version of clang that supports wasm32
- run: wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - || exit 1
- run: sudo apt-get update || exit 1
- run: sudo apt-get install -y libclang-common-10-dev clang-10 libc6-dev-i386 || exit 1
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
profile: minimal
target: "wasm32-unknown-unknown"
- name: Rust Cache
uses: Swatinem/rust-cache@v2.2.1
- name: Check bdk wallet
working-directory: ./crates/wallet
run: cargo check --target wasm32-unknown-unknown --no-default-features --features miniscript/no-std,bdk_chain/hashbrown
- name: Check esplora
working-directory: ./crates/esplora
run: cargo check --target wasm32-unknown-unknown --no-default-features --features miniscript/no-std,bdk_chain/hashbrown,async
fmt:
name: Rust fmt
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
profile: minimal
components: rustfmt
- name: Check fmt
run: cargo fmt --all -- --config format_code_in_doc_comments=true --check
clippy_check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions-rs/toolchain@v1
with:
toolchain: 1.78.0
components: clippy
override: true
- name: Rust Cache
uses: Swatinem/rust-cache@v2.2.1
- uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-features --all-targets -- -D warnings

57
.github/workflows/nightly_docs.yml vendored Normal file
View File

@ -0,0 +1,57 @@
name: Publish Nightly Docs
on: [push, pull_request]
jobs:
build_docs:
name: Build docs
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Set default toolchain
run: rustup default nightly-2024-05-12
- name: Set profile
run: rustup set profile minimal
- name: Update toolchain
run: rustup update
- name: Rust Cache
uses: Swatinem/rust-cache@v2.2.1
- name: Build docs
run: cargo doc --no-deps
env:
RUSTDOCFLAGS: '--cfg docsrs -Dwarnings'
- name: Upload artifact
uses: actions/upload-artifact@v2
with:
name: built-docs
path: ./target/doc/*
publish_docs:
name: 'Publish docs'
if: github.ref == 'refs/heads/master'
needs: [build_docs]
runs-on: ubuntu-latest
steps:
- name: Checkout `bitcoindevkit.org`
uses: actions/checkout@v2
with:
ssh-key: ${{ secrets.DOCS_PUSH_SSH_KEY }}
repository: bitcoindevkit/bitcoindevkit.org
ref: master
- name: Create directories
run: mkdir -p ./docs/.vuepress/public/docs-rs/bdk/nightly
- name: Remove old latest
run: rm -rf ./docs/.vuepress/public/docs-rs/bdk/nightly/latest
- name: Download built docs
uses: actions/download-artifact@v1
with:
name: built-docs
path: ./docs/.vuepress/public/docs-rs/bdk/nightly/latest
- name: Configure git
run: git config user.email "github-actions@github.com" && git config user.name "github-actions"
- name: Commit
continue-on-error: true # If there's nothing to commit this step fails, but it's fine
run: git add ./docs/.vuepress/public/docs-rs && git commit -m "Publish autogenerated nightly docs"
- name: Push
run: git push origin master

6
.gitignore vendored
View File

@ -1,4 +1,10 @@
/target
Cargo.lock
/.vscode
*.swp
.idea
# Example persisted files.
*.db
*.sqlite*

View File

@ -1,22 +0,0 @@
language: rust
rust:
- stable
# - 1.31.0
# - 1.22.0
before_script:
- rustup component add rustfmt
script:
- cargo fmt -- --check --verbose
- cargo test --verbose --all
- cargo build --verbose --all
- cargo build --verbose --no-default-features --features=minimal
- cargo build --verbose --no-default-features --features=minimal,esplora
- cargo build --verbose --no-default-features --features=key-value-db
- cargo build --verbose --no-default-features --features=electrum
notifications:
email: false
before_cache:
- rm -rf "$TRAVIS_HOME/.cargo/registry/src"
cache: cargo

645
CHANGELOG.md Normal file
View File

@ -0,0 +1,645 @@
# Changelog
All notable changes to this project can be found here and in each release's git tag and can be viewed with `git tag -ln100 "v*"`. See also [DEVELOPMENT_CYCLE.md](DEVELOPMENT_CYCLE.md) for more details.
Contributors do not need to change this file but do need to add changelog details in their PR descriptions. The person making the next release will collect changelog details from included PRs and edit this file prior to each release.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [v0.27.1]
### Summary
Fixes [RUSTSEC-2022-0090], this issue is only applicable if you are using the optional sqlite database feature.
[RUSTSEC-2022-0090]: https://rustsec.org/advisories/RUSTSEC-2022-0090
### Changed
- Update optional sqlite dependency from 0.27.0 to 0.28.0. #867
## [v0.27.0]
### Summary
A maintenance release with a bump in project MSRV to 1.57.0, updated dependence and a few developer oriented improvements. Improvements include better error formatting, don't default to async/await for wasm32 and adding derived PartialEq and Eq on SyncTime.
### Changed
- Improve display error formatting #814
- Don't default to use async/await on wasm32 #831
- Project MSRV changed from 1.56.1 to 1.57.0 #842
- Update rust-miniscript dependency to latest bug fix release 9.0 #844
### Added
- Derive PartialEq, Eq on SyncTime #837
## [v0.26.0]
### Summary
This release improves Fulcrum electrum server compatibility and fixes public descriptor template key origin paths. We also snuck in small enhancements to configure the electrum client to validate the domain using SSL and sort TransactionDetails by block height and timestamp.
### Fixed
- Make electrum blockchain client `save_tx` function order independent to work with Fulcrum servers. #808
- Fix wrong testnet key origin path in public descriptor templates. #818
- Make README.md code examples compile without errors. #820
### Changed
- Bump `hwi` dependency to `0.4.0`. #825
- Bump `esplora-client` dependency to `0.3` #830
### Added
- For electrum blockchain client, allow user to configure whether to validate the domain using SSL. #805
- Implement ordering for `TransactionDetails`. #812
## [v0.25.0]
### Summary
This release fixes slow sync time and big script_pubkeys table with SQLite, the wallet rescan height for the FullyNodedExport and setting the network for keys in the KeyMap when using descriptor templates. Also added are new blockchain and mnemonic examples.
### Fixed
- Slow sync time and big script_pubkeys table with SQLite.
- Wallet rescan height for the FullyNodedExport.
- Setting the network for keys in the KeyMap when using descriptor templates.
### Added
- Examples for connecting to Esplora, Electrum Server, Neutrino and Bitcoin Core.
- Example for using a mnemonic in a descriptors.
## [v0.24.0]
### Summary
This release contains important dependency updates for `rust-bitcoin` to `0.29` and `rust-miniscript` to `8.0`, plus related crates that also depend on the latest version of `rust-bitcoin`. The release also includes a breaking change to the BDK signer which now produces low-R signatures by default, saving one byte. A bug was found in the `get_checksum` and `get_checksum_bytes` functions, which are now deprecated in favor of fixed versions called `calc_checksum` and `calc_checksum_bytes`. And finally a new `hardware-signer` features was added that re-exports the `hwi` crate, along with a new `hardware_signers.rs` example file.
### Changed
- Updated dependency versions for `rust-bitcoin` to `0.29` and `rust-miniscript` to `8.0`, plus all related crates. @afilini #770
- BDK Signer now produces low-R signatures by default, saving one byte. If you want to preserve the original behavior, set allow_grinding in the SignOptions to false. @vladimirfomene #779
- Deprecated `get_checksum`and `get_checksum_bytes` due to bug where they calculates the checksum of a descriptor that already has a checksum. Use `calc_checksum` and `calc_checksum_bytes` instead. @evanlinjin #765
- Remove deprecated "address validators". @afilini #770
### Added
- New `calc_checksum` and `calc_checksum_bytes`, replace deprecated `get_checksum` and `get_checksum_bytes`. @evanlinjin #765
- Re-export the hwi crate when the feature hardware-signer is on. @danielabrozzoni #758
- New examples/hardware_signer.rs. @danielabrozzoni #758
- Make psbt module public to expose PsbtUtils trait to downstream projects. @notmandatory #782
## [v0.23.0]
### Summary
This release brings new utilities functions on PSBTs like `fee_amount()` and `fee_rate()` and migrates BDK to use our new external esplora client library.
As always many bug fixes, docs and tests improvement are also included.
### Changed
- Update electrum-client to 0.11.0 by @afilini in https://github.com/bitcoindevkit/bdk/pull/737
- Change configs for source-base code coverage by @wszdexdrf in https://github.com/bitcoindevkit/bdk/pull/708
- Improve docs regarding PSBT finalization by @tnull in https://github.com/bitcoindevkit/bdk/pull/753
- Update compiler example to a Policy example by @rajarshimaitra in https://github.com/bitcoindevkit/bdk/pull/730
- Fix the release process by @afilini in https://github.com/bitcoindevkit/bdk/pull/754
- Remove redundant duplicated keys check by @afilini in https://github.com/bitcoindevkit/bdk/pull/761
- Remove genesis_block lazy initialization by @shobitb in https://github.com/bitcoindevkit/bdk/pull/756
- Fix `Wallet::descriptor_checksum` to actually return the checksum by @evanlinjin in https://github.com/bitcoindevkit/bdk/pull/763
- Use the esplora client crate by @afilini in https://github.com/bitcoindevkit/bdk/pull/764
### Added
- Run code coverage on every PR by @danielabrozzoni in https://github.com/bitcoindevkit/bdk/pull/747
- Add psbt_signer.rs example by @notmandatory in https://github.com/bitcoindevkit/bdk/pull/744
- Add fee_amount() and fee_rate() functions to PsbtUtils trait by @notmandatory in https://github.com/bitcoindevkit/bdk/pull/728
- Add tests to improve coverage by @vladimirfomene in https://github.com/bitcoindevkit/bdk/pull/745
- Enable signing taproot transactions with only `non_witness_utxos` by @afilini in https://github.com/bitcoindevkit/bdk/pull/757
- Add datatype for is_spent sqlite column by @vladimirfomene in https://github.com/bitcoindevkit/bdk/pull/713
- Add vscode filter to gitignore by @evanlinjin in https://github.com/bitcoindevkit/bdk/pull/762
## [v0.22.0]
### Summary
This release brings support for hardware signers on desktop through the HWI library.
It also includes fixes and improvements which are part of our ongoing effort of integrating
BDK and LDK together.
### Changed
- FeeRate function name as_sat_vb to as_sat_per_vb. #678
- Verify signatures after signing. #718
- Dependency electrum-client to 0.11.0. #737
### Added
- Functions to create FeeRate from sats/kvbytes and sats/kwu. #678
- Custom hardware wallet signer HwiSigner in wallet::hardwaresigner module. #682
- Function allow_dust on TxBuilder. #689
- Implementation of Deref<Target=UrlClient> for EsploraBlockchain. #722
- Implementation of Deref<Target=Client> for ElectrumBlockchain #705
- Implementation of Deref<Target=Client> for RpcBlockchain. #731
## [v0.21.0]
- Add `descriptor::checksum::get_checksum_bytes` method.
- Add `Excess` enum to handle remaining amount after coin selection.
- Move change creation from `Wallet::create_tx` to `CoinSelectionAlgorithm::coin_select`.
- Change the interface of `SqliteDatabase::new` to accept any type that implement AsRef<Path>
- Add the ability to specify which leaves to sign in a taproot transaction through `TapLeavesOptions` in `SignOptions`
- Add the ability to specify whether a taproot transaction should be signed using the internal key or not, using `sign_with_tap_internal_key` in `SignOptions`
- Consolidate params `fee_amount` and `amount_needed` in `target_amount` in `CoinSelectionAlgorithm::coin_select` signature.
- Change the meaning of the `fee_amount` field inside `CoinSelectionResult`: from now on the `fee_amount` will represent only the fees associated with the utxos in the `selected` field of `CoinSelectionResult`.
- New `RpcBlockchain` implementation with various fixes.
- Return balance in separate categories, namely `confirmed`, `trusted_pending`, `untrusted_pending` & `immature`.
## [v0.20.0]
- New MSRV set to `1.56.1`
- Fee sniping discouraging through nLockTime - if the user specifies a `current_height`, we use that as a nlocktime, otherwise we use the last sync height (or 0 if we never synced)
- Fix hang when `ElectrumBlockchainConfig::stop_gap` is zero.
- Set coin type in BIP44, BIP49, and BIP84 templates
- Get block hash given a block height - A `get_block_hash` method is now defined on the `GetBlockHash` trait and implemented on every blockchain backend. This method expects a block height and returns the corresponding block hash.
- Add `remove_partial_sigs` and `try_finalize` to `SignOptions`
- Deprecate `AddressValidator`
- Fix Electrum wallet sync potentially causing address index decrement - compare proposed index and current index before applying batch operations during sync.
## [v0.19.0]
- added `OldestFirstCoinSelection` impl to `CoinSelectionAlgorithm`
- New MSRV set to `1.56`
- Unpinned tokio to `1`
- Add traits to reuse `Blockchain`s across multiple wallets (`BlockchainFactory` and `StatelessBlockchain`).
- Upgrade to rust-bitcoin `0.28`
- If using the `sqlite-db` feature all cached wallet data is deleted due to a possible UTXO inconsistency, a wallet.sync will recreate it
- Update `PkOrF` in the policy module to become an enum
- Add experimental support for Taproot, including:
- Support for `tr()` descriptors with complex tapscript trees
- Creation of Taproot PSBTs (BIP-371)
- Signing Taproot PSBTs (key spend and script spend)
- Support for `tr()` descriptors in the `descriptor!()` macro
- Add support for Bitcoin Core 23.0 when using the `rpc` blockchain
## [v0.18.0]
- Add `sqlite-bundled` feature for deployments that need a bundled version of sqlite, i.e. for mobile platforms.
- Added `Wallet::get_signers()`, `Wallet::descriptor_checksum()` and `Wallet::get_address_validators()`, exposed the `AsDerived` trait.
- Deprecate `database::Database::flush()`, the function is only needed for the sled database on mobile, instead for mobile use the sqlite database.
- Add `keychain: KeychainKind` to `wallet::AddressInfo`.
- Improve key generation traits
- Rename `WalletExport` to `FullyNodedExport`, deprecate the former.
- Bump `miniscript` dependency version to `^6.1`.
## [v0.17.0]
- Removed default verification from `wallet::sync`. sync-time verification is added in `script_sync` and is activated by `verify` feature flag.
- `verify` flag removed from `TransactionDetails`.
- Add `get_internal_address` to allow you to get internal addresses just as you get external addresses.
- added `ensure_addresses_cached` to `Wallet` to let offline wallets load and cache addresses in their database
- Add `is_spent` field to `LocalUtxo`; when we notice that a utxo has been spent we set `is_spent` field to true instead of deleting it from the db.
### Sync API change
To decouple the `Wallet` from the `Blockchain` we've made major changes:
- Removed `Blockchain` from Wallet.
- Removed `Wallet::broadcast` (just use `Blockchain::broadcast`)
- Deprecated `Wallet::new_offline` (all wallets are offline now)
- Changed `Wallet::sync` to take a `Blockchain`.
- Stop making a request for the block height when calling `Wallet:new`.
- Added `SyncOptions` to capture extra (future) arguments to `Wallet::sync`.
- Removed `max_addresses` sync parameter which determined how many addresses to cache before syncing since this can just be done with `ensure_addresses_cached`.
- remove `flush` method from the `Database` trait.
## [v0.16.1]
- Pin tokio dependency version to ~1.14 to prevent errors due to their new MSRV 1.49.0
## [v0.16.0]
- Disable `reqwest` default features.
- Added `reqwest-default-tls` feature: Use this to restore the TLS defaults of reqwest if you don't want to add a dependency to it in your own manifest.
- Use dust_value from rust-bitcoin
- Fixed generating WIF in the correct network format.
## [v0.15.0]
- Overhauled sync logic for electrum and esplora.
- Unify ureq and reqwest esplora backends to have the same configuration parameters. This means reqwest now has a timeout parameter and ureq has a concurrency parameter.
- Fixed esplora fee estimation.
## [v0.14.0]
- BIP39 implementation dependency, in `keys::bip39` changed from tiny-bip39 to rust-bip39.
- Add new method on the `TxBuilder` to embed data in the transaction via `OP_RETURN`. To allow that a fix to check the dust only on spendable output has been introduced.
- Update the `Database` trait to store the last sync timestamp and block height
- Rename `ConfirmationTime` to `BlockTime`
## [v0.13.0]
- Exposed `get_tx()` method from `Database` to `Wallet`.
## [v0.12.0]
- Activate `miniscript/use-serde` feature to allow consumers of the library to access it via the re-exported `miniscript` crate.
- Add support for proxies in `EsploraBlockchain`
- Added `SqliteDatabase` that implements `Database` backed by a sqlite database using `rusqlite` crate.
## [v0.11.0]
- Added `flush` method to the `Database` trait to explicitly flush to disk latest changes on the db.
## [v0.10.0]
- Added `RpcBlockchain` in the `AnyBlockchain` struct to allow using Rpc backend where `AnyBlockchain` is used (eg `bdk-cli`)
- Removed hard dependency on `tokio`.
### Wallet
- Removed and replaced `set_single_recipient` with more general `drain_to` and replaced `maintain_single_recipient` with `allow_shrinking`.
### Blockchain
- Removed `stop_gap` from `Blockchain` trait and added it to only `ElectrumBlockchain` and `EsploraBlockchain` structs.
- Added a `ureq` backend for use when not using feature `async-interface` or target WASM. `ureq` is a blocking HTTP client.
## [v0.9.0]
### Wallet
- Added Bitcoin core RPC added as blockchain backend
- Added a `verify` feature that can be enable to verify the unconfirmed txs we download against the consensus rules
## [v0.8.0]
### Wallet
- Added an option that must be explicitly enabled to allow signing using non-`SIGHASH_ALL` sighashes (#350)
#### Changed
`get_address` now returns an `AddressInfo` struct that includes the index and derefs to `Address`.
## [v0.7.0]
### Policy
#### Changed
Removed `fill_satisfaction` method in favor of enum parameter in `extract_policy` method
#### Added
Timelocks are considered (optionally) in building the `satisfaction` field
### Wallet
- Changed `Wallet::{sign, finalize_psbt}` now take a `&mut psbt` rather than consuming it.
- Require and validate `non_witness_utxo` for SegWit signatures by default, can be adjusted with `SignOptions`
- Replace the opt-in builder option `force_non_witness_utxo` with the opposite `only_witness_utxo`. From now on we will provide the `non_witness_utxo`, unless explicitly asked not to.
## [v0.6.0]
### Misc
#### Changed
- New minimum supported rust version is 1.46.0
- Changed `AnyBlockchainConfig` to use serde tagged representation.
### Descriptor
#### Added
- Added ability to analyze a `PSBT` to check which and how many signatures are already available
### Wallet
#### Changed
- `get_new_address()` refactored to `get_address(AddressIndex::New)` to support different `get_address()` index selection strategies
#### Added
- Added `get_address(AddressIndex::LastUnused)` which returns the last derived address if it has not been used or if used in a received transaction returns a new address
- Added `get_address(AddressIndex::Peek(u32))` which returns a derived address for a specified descriptor index but does not change the current index
- Added `get_address(AddressIndex::Reset(u32))` which returns a derived address for a specified descriptor index and resets current index to the given value
- Added `get_psbt_input` to create the corresponding psbt input for a local utxo.
#### Fixed
- Fixed `coin_select` calculation for UTXOs where `value < fee` that caused over-/underflow errors.
## [v0.5.1]
### Misc
#### Changed
- Pin `hyper` to `=0.14.4` to make it compile on Rust 1.45
## [v0.5.0]
### Misc
#### Changed
- Updated `electrum-client` to version `0.7`
### Wallet
#### Changed
- `FeeRate` constructors `from_sat_per_vb` and `default_min_relay_fee` are now `const` functions
## [v0.4.0]
### Keys
#### Changed
- Renamed `DerivableKey::add_metadata()` to `DerivableKey::into_descriptor_key()`
- Renamed `ToDescriptorKey::to_descriptor_key()` to `IntoDescriptorKey::into_descriptor_key()`
#### Added
- Added an `ExtendedKey` type that is an enum of `bip32::ExtendedPubKey` and `bip32::ExtendedPrivKey`
- Added `DerivableKey::into_extended_key()` as the only method that needs to be implemented
### Misc
#### Removed
- Removed the `parse_descriptor` example, since it wasn't demonstrating any bdk-specific API anymore.
#### Changed
- Updated `bitcoin` to `0.26`, `miniscript` to `5.1` and `electrum-client` to `0.6`
#### Added
- Added support for the `signet` network (issue #62)
- Added a function to get the version of BDK at runtime
### Wallet
#### Changed
- Removed the explicit `id` argument from `Wallet::add_signer()` since that's now part of `Signer` itself
- Renamed `ToWalletDescriptor::to_wallet_descriptor()` to `IntoWalletDescriptor::into_wallet_descriptor()`
### Policy
#### Changed
- Removed unneeded `Result<(), PolicyError>` return type for `Satisfaction::finalize()`
- Removed the `TooManyItemsSelected` policy error (see commit message for more details)
## [v0.3.0]
### Descriptor
#### Changed
- Added an alias `DescriptorError` for `descriptor::error::Error`
- Changed the error returned by `descriptor!()` and `fragment!()` to `DescriptorError`
- Changed the error type in `ToWalletDescriptor` to `DescriptorError`
- Improved checks on descriptors built using the macros
### Blockchain
#### Changed
- Remove `BlockchainMarker`, `OfflineClient` and `OfflineWallet` in favor of just using the unit
type to mark for a missing client.
- Upgrade `tokio` to `1.0`.
### Transaction Creation Overhaul
The `TxBuilder` is now created from the `build_tx` or `build_fee_bump` functions on wallet and the
final transaction is created by calling `finish` on the builder.
- Removed `TxBuilder::utxos` in favor of `TxBuilder::add_utxos`
- Added `Wallet::build_tx` to replace `Wallet::create_tx`
- Added `Wallet::build_fee_bump` to replace `Wallet::bump_fee`
- Added `Wallet::get_utxo`
- Added `Wallet::get_descriptor_for_keychain`
### `add_foreign_utxo`
- Renamed `UTXO` to `LocalUtxo`
- Added `WeightedUtxo` to replace floating `(UTXO, usize)`.
- Added `Utxo` enum to incorporate both local utxos and foreign utxos
- Added `TxBuilder::add_foreign_utxo` which allows adding a utxo external to the wallet.
### CLI
#### Changed
- Remove `cli.rs` module, `cli-utils` feature and `repl.rs` example; moved to new [`bdk-cli`](https://github.com/bitcoindevkit/bdk-cli) repository
## [v0.2.0]
### Project
#### Added
- Add CONTRIBUTING.md
- Add a Discord badge to the README
- Add code coverage github actions workflow
- Add scheduled audit check in CI
- Add CHANGELOG.md
#### Changed
- Rename the library to `bdk`
- Rename `ScriptType` to `KeychainKind`
- Prettify README examples on github
- Change CI to github actions
- Bump rust-bitcoin to 0.25, fix Cargo dependencies
- Enable clippy for stable and tests by default
- Switch to "mainline" rust-miniscript
- Generate a different cache key for every CI job
- Fix to at least bitcoin ^0.25.2
#### Fixed
- Fix or ignore clippy warnings for all optional features except compact_filters
- Pin cc version because last breaks rocksdb build
### Blockchain
#### Added
- Add a trait to create `Blockchain`s from a configuration
- Add an `AnyBlockchain` enum to allow switching at runtime
- Document `AnyBlockchain` and `ConfigurableBlockchain`
- Use our Instant struct to be compatible with wasm
- Make esplora call in parallel
- Allow to set concurrency in Esplora config and optionally pass it in repl
#### Fixed
- Fix receiving a coinbase using Electrum/Esplora
- Use proper type for EsploraHeader, make conversion to BlockHeader infallible
- Eagerly unwrap height option, save one collect
#### Changed
- Simplify the architecture of blockchain traits
- Improve sync
- Remove unused variant `HeaderParseFail`
### CLI
#### Added
- Conditionally remove cli args according to enabled feature
#### Changed
- Add max_addresses param in sync
- Split the internal and external policy paths
### Database
#### Added
- Add `AnyDatabase` and `ConfigurableDatabase` traits
### Descriptor
#### Added
- Add a macro to write descriptors from code
- Add descriptor templates, add `DerivableKey`
- Add ToWalletDescriptor trait tests
- Add support for `sortedmulti` in `descriptor!`
- Add ExtractPolicy trait tests
- Add get_checksum tests, cleanup tests
- Add descriptor macro tests
#### Changes
- Improve the descriptor macro, add traits for key and descriptor types
#### Fixes
- Fix the recovery of a descriptor given a PSBT
### Keys
#### Added
- Add BIP39 support
- Take `ScriptContext` into account when converting keys
- Add a way to restrict the networks in which keys are valid
- Add a trait for keys that can be generated
- Fix entropy generation
- Less convoluted entropy generation
- Re-export tiny-bip39
- Implement `GeneratableKey` trait for `bitcoin::PrivateKey`
- Implement `ToDescriptorKey` trait for `GeneratedKey`
- Add a shortcut to generate keys with the default options
#### Fixed
- Fix all-keys and cli-utils tests
### Wallet
#### Added
- Allow to define static fees for transactions Fixes #137
- Merging two match expressions for fee calculation
- Incorporate RBF rules into utxo selection function
- Add Branch and Bound coin selection
- Add tests for BranchAndBoundCoinSelection::coin_select
- Add tests for BranchAndBoundCoinSelection::bnb
- Add tests for BranchAndBoundCoinSelection::single_random_draw
- Add test that shwpkh populates witness_utxo
- Add witness and redeem scripts to PSBT outputs
- Add an option to include `PSBT_GLOBAL_XPUB`s in PSBTs
- Eagerly finalize inputs
#### Changed
- Use collect to avoid iter unwrapping Options
- Make coin_select take may/must use utxo lists
- Improve `CoinSelectionAlgorithm`
- Refactor `Wallet::bump_fee()`
- Default to SIGHASH_ALL if not specified
- Replace ChangeSpendPolicy::filter_utxos with a predicate
- Make 'unspendable' into a HashSet
- Stop implicitly enforcing manual selection by .add_utxo
- Rename DumbCS to LargestFirstCoinSelection
- Rename must_use_utxos to required_utxos
- Rename may_use_utxos to optional_uxtos
- Rename get_must_may_use_utxos to preselect_utxos
- Remove redundant Box around address validators
- Remove redundant Box around signers
- Make Signer and AddressValidator Send and Sync
- Split `send_all` into `set_single_recipient` and `drain_wallet`
- Use TXIN_DEFAULT_WEIGHT constant in coin selection
- Replace `must_use` with `required` in coin selection
- Take both spending policies into account in create_tx
- Check last derivation in cache to avoid recomputing
- Use the branch-and-bound cs by default
- Make coin_select return UTXOs instead of TxIns
- Build output lookup inside complete transaction
- Don't wrap SignersContainer arguments in Arc
- More consistent references with 'signers' variables
#### Fixed
- Fix signing for `ShWpkh` inputs
- Fix the recovery of a descriptor given a PSBT
### Examples
#### Added
- Support esplora blockchain source in repl
#### Changed
- Revert back the REPL example to use Electrum
- Remove the `magic` alias for `repl`
- Require esplora feature for repl example
#### Security
- Use dirs-next instead of dirs since the latter is unmaintained
## [0.1.0-beta.1] - 2020-09-08
### Blockchain
#### Added
- Lightweight Electrum client with SSL/SOCKS5 support
- Add a generalized "Blockchain" interface
- Add Error::OfflineClient
- Add the Esplora backend
- Use async I/O in the various blockchain impls
- Compact Filters blockchain implementation
- Add support for Tor
- Impl OnlineBlockchain for types wrapped in Arc
### Database
#### Added
- Add a generalized database trait and a Sled-based implementation
- Add an in-memory database
### Descriptor
#### Added
- Wrap Miniscript descriptors to support xpubs
- Policy and contribution
- Transform a descriptor into its "public" version
- Use `miniscript::DescriptorPublicKey`
### Macros
#### Added
- Add a feature to enable the async interface on non-wasm32 platforms
### Wallet
#### Added
- Wallet logic
- Add `assume_height_reached` in PSBTSatisfier
- Add an option to change the assumed current height
- Specify the policy branch with a map
- Add a few commands to handle psbts
- Add hd_keypaths to outputs
- Add a `TxBuilder` struct to simplify `create_tx()`'s interface
- Abstract coin selection in a separate trait
- Refill the address pool whenever necessary
- Implement the wallet import/export format from FullyNoded
- Add a type convert fee units, add `Wallet::estimate_fee()`
- TxOrdering, shuffle/bip69 support
- Add RBF and custom versions in TxBuilder
- Allow limiting the use of internal utxos in TxBuilder
- Add `force_non_witness_utxo()` to TxBuilder
- RBF and add a few tests
- Add AddressValidators
- Add explicit ordering for the signers
- Support signing the whole tx instead of individual inputs
- Create a PSBT signer from an ExtendedDescriptor
### Examples
#### Added
- Add REPL broadcast command
- Add a miniscript compiler CLI
- Expose list_transactions() in the REPL
- Use `MemoryDatabase` in the compiler example
- Make the REPL return JSON
[0.1.0-beta.1]: https://github.com/bitcoindevkit/bdk/compare/96c87ea5...0.1.0-beta.1
[v0.2.0]: https://github.com/bitcoindevkit/bdk/compare/0.1.0-beta.1...v0.2.0
[v0.3.0]: https://github.com/bitcoindevkit/bdk/compare/v0.2.0...v0.3.0
[v0.4.0]: https://github.com/bitcoindevkit/bdk/compare/v0.3.0...v0.4.0
[v0.5.0]: https://github.com/bitcoindevkit/bdk/compare/v0.4.0...v0.5.0
[v0.5.1]: https://github.com/bitcoindevkit/bdk/compare/v0.5.0...v0.5.1
[v0.6.0]: https://github.com/bitcoindevkit/bdk/compare/v0.5.1...v0.6.0
[v0.7.0]: https://github.com/bitcoindevkit/bdk/compare/v0.6.0...v0.7.0
[v0.8.0]: https://github.com/bitcoindevkit/bdk/compare/v0.7.0...v0.8.0
[v0.9.0]: https://github.com/bitcoindevkit/bdk/compare/v0.8.0...v0.9.0
[v0.10.0]: https://github.com/bitcoindevkit/bdk/compare/v0.9.0...v0.10.0
[v0.11.0]: https://github.com/bitcoindevkit/bdk/compare/v0.10.0...v0.11.0
[v0.12.0]: https://github.com/bitcoindevkit/bdk/compare/v0.11.0...v0.12.0
[v0.13.0]: https://github.com/bitcoindevkit/bdk/compare/v0.12.0...v0.13.0
[v0.14.0]: https://github.com/bitcoindevkit/bdk/compare/v0.13.0...v0.14.0
[v0.15.0]: https://github.com/bitcoindevkit/bdk/compare/v0.14.0...v0.15.0
[v0.16.0]: https://github.com/bitcoindevkit/bdk/compare/v0.15.0...v0.16.0
[v0.16.1]: https://github.com/bitcoindevkit/bdk/compare/v0.16.0...v0.16.1
[v0.17.0]: https://github.com/bitcoindevkit/bdk/compare/v0.16.1...v0.17.0
[v0.18.0]: https://github.com/bitcoindevkit/bdk/compare/v0.17.0...v0.18.0
[v0.19.0]: https://github.com/bitcoindevkit/bdk/compare/v0.18.0...v0.19.0
[v0.20.0]: https://github.com/bitcoindevkit/bdk/compare/v0.19.0...v0.20.0
[v0.21.0]: https://github.com/bitcoindevkit/bdk/compare/v0.20.0...v0.21.0
[v0.22.0]: https://github.com/bitcoindevkit/bdk/compare/v0.21.0...v0.22.0
[v0.23.0]: https://github.com/bitcoindevkit/bdk/compare/v0.22.0...v0.23.0
[v0.24.0]: https://github.com/bitcoindevkit/bdk/compare/v0.23.0...v0.24.0
[v0.25.0]: https://github.com/bitcoindevkit/bdk/compare/v0.24.0...v0.25.0
[v0.26.0]: https://github.com/bitcoindevkit/bdk/compare/v0.25.0...v0.26.0
[v0.27.0]: https://github.com/bitcoindevkit/bdk/compare/v0.26.0...v0.27.0
[v0.27.1]: https://github.com/bitcoindevkit/bdk/compare/v0.27.0...v0.27.1
[Unreleased]: https://github.com/bitcoindevkit/bdk/compare/v0.27.1...HEAD

118
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,118 @@
Contributing to BDK
==============================
The BDK project operates an open contributor model where anyone is welcome to
contribute towards development in the form of peer review, documentation,
testing and patches.
Anyone is invited to contribute without regard to technical experience,
"expertise", OSS experience, age, or other concern. However, the development of
cryptocurrencies demands a high-level of rigor, adversarial thinking, thorough
testing and risk-minimization.
Any bug may cost users real money. That being said, we deeply welcome people
contributing for the first time to an open source project or picking up Rust while
contributing. Don't be shy, you'll learn.
Communications Channels
-----------------------
Communication about BDK happens primarily on the [BDK Discord](https://discord.gg/dstn4dQ).
Discussion about code base improvements happens in GitHub [issues](https://github.com/bitcoindevkit/bdk/issues) and
on [pull requests](https://github.com/bitcoindevkit/bdk/pulls).
Contribution Workflow
---------------------
The codebase is maintained using the "contributor workflow" where everyone
without exception contributes patch proposals using "pull requests". This
facilitates social contribution, easy testing and peer review.
To contribute a patch, the workflow is as follows:
1. Fork Repository
2. Create topic branch
3. Commit patches
In general commits should be atomic and diffs should be easy to read.
For this reason do not mix any formatting fixes or code moves with actual code
changes. Further, each commit, individually, should compile and pass tests, in
order to ensure git bisect and other automated tools function properly.
When adding a new feature, thought must be given to the long term technical
debt.
Every new feature should be covered by functional tests where possible.
When refactoring, structure your PR to make it easy to review and don't
hesitate to split it into multiple small, focused PRs.
The Minimal Supported Rust Version is **1.57.0** (enforced by our CI).
Commits should cover both the issue fixed and the solution's rationale.
These [guidelines](https://chris.beams.io/posts/git-commit/) should be kept in mind. Commit messages should follow the ["Conventional Commits 1.0.0"](https://www.conventionalcommits.org/en/v1.0.0/) to make commit histories easier to read by humans and automated tools.
To facilitate communication with other contributors, the project is making use
of GitHub's "assignee" field. First check that no one is assigned and then
comment suggesting that you're working on it. If someone is already assigned,
don't hesitate to ask if the assigned party or previous commenter are still
working on it if it has been awhile.
Deprecation policy
------------------
Where possible, breaking existing APIs should be avoided. Instead, add new APIs and
use [`#[deprecated]`](https://github.com/rust-lang/rfcs/blob/master/text/1270-deprecation.md)
to discourage use of the old one.
Deprecated APIs are typically maintained for one release cycle. In other words, an
API that has been deprecated with the 0.10 release can be expected to be removed in the
0.11 release. This allows for smoother upgrades without incurring too much technical
debt inside this library.
If you deprecated an API as part of a contribution, we encourage you to "own" that API
and send a follow-up to remove it as part of the next release cycle.
Peer review
-----------
Anyone may participate in peer review which is expressed by comments in the
pull request. Typically reviewers will review the code for obvious errors, as
well as test out the patch set and opine on the technical merits of the patch.
PR should be reviewed first on the conceptual level before focusing on code
style or grammar fixes.
Coding Conventions
------------------
This codebase uses spaces, not tabs.
Use `cargo fmt` with the default settings to format code before committing.
This is also enforced by the CI.
Security
--------
Security is a high priority of BDK; disclosure of security vulnerabilities helps
prevent user loss of funds.
Note that BDK is currently considered "pre-production" during this time, there
is no special handling of security issues. Please simply open an issue on
Github.
Testing
-------
Related to the security aspect, BDK developers take testing very seriously.
Due to the modular nature of the project, writing new functional tests is easy
and good test coverage of the codebase is an important goal.
Refactoring the project to enable fine-grained unit testing is also an ongoing
effort.
Going further
-------------
You may be interested by Jon Atacks guide on [How to review Bitcoin Core PRs](https://github.com/jonatack/bitcoin-development/blob/master/how-to-review-bitcoin-core-prs.md)
and [How to make Bitcoin Core PRs](https://github.com/jonatack/bitcoin-development/blob/master/how-to-make-bitcoin-core-prs.md).
While there are differences between the projects in terms of context and
maturity, many of the suggestions offered apply to this project.
Overall, have fun :)

View File

@ -1,58 +1,25 @@
[package]
name = "magical-bitcoin-wallet"
version = "0.1.0"
edition = "2018"
authors = ["Riccardo Casatta <riccardo@casatta.it>", "Alekos Filini <alekos.filini@gmail.com>"]
[dependencies]
log = "^0.4"
bitcoin = { version = "0.23", features = ["use-serde"] }
miniscript = { version = "0.12" }
serde = { version = "^1.0", features = ["derive"] }
serde_json = { version = "^1.0" }
base64 = "^0.11"
async-trait = "0.1"
# Optional dependencies
sled = { version = "0.31.0", optional = true }
electrum-client = { git = "https://github.com/MagicalBitcoin/rust-electrum-client.git", optional = true }
reqwest = { version = "0.10", optional = true, features = ["json"] }
futures = { version = "0.3", optional = true }
clap = { version = "2.33", optional = true }
[features]
minimal = []
compiler = ["miniscript/compiler"]
default = ["key-value-db", "electrum"]
electrum = ["electrum-client"]
esplora = ["reqwest", "futures"]
key-value-db = ["sled"]
cli-utils = ["clap"]
[dev-dependencies]
tokio = { version = "0.2", features = ["macros"] }
lazy_static = "1.4"
rustyline = "6.0"
dirs = "2.0"
env_logger = "0.7"
rand = "0.7"
[[example]]
name = "repl"
required-features = ["cli-utils"]
[[example]]
name = "psbt"
[[example]]
name = "parse_descriptor"
[[example]]
name = "miniscriptc"
path = "examples/compiler.rs"
required-features = ["compiler"]
# Provide a more user-friendly alias for the REPL
[[example]]
name = "magic"
path = "examples/repl.rs"
required-features = ["cli-utils"]
[workspace]
resolver = "2"
members = [
"crates/wallet",
"crates/chain",
"crates/file_store",
"crates/electrum",
"crates/esplora",
"crates/bitcoind_rpc",
"crates/hwi",
"crates/testenv",
"example-crates/example_cli",
"example-crates/example_electrum",
"example-crates/example_esplora",
"example-crates/example_bitcoind_rpc_polling",
"example-crates/wallet_electrum",
"example-crates/wallet_esplora_blocking",
"example-crates/wallet_esplora_async",
"example-crates/wallet_rpc",
"nursery/tmp_plan",
"nursery/coin_select"
]
[workspace.package]
authors = ["Bitcoin Dev Kit Developers"]

16
DEVELOPMENT_CYCLE.md Normal file
View File

@ -0,0 +1,16 @@
# Development Cycle
This project follows a regular releasing schedule similar to the one [used by the Rust language]. In short, this means that a new release is made at a regular cadence, with all the feature/bugfixes that made it to `master` in time. This ensures that we don't keep delaying releases waiting for "just one more little thing".
This project uses [Semantic Versioning], but is currently at MAJOR version zero (0.y.z) meaning it is still in initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable. Until we reach version `1.0.0` we will do our best to document any breaking API changes in the changelog info attached to each release tag.
We decided to maintain a faster release cycle while the library is still in "beta", i.e. before release `1.0.0`: since we are constantly adding new features and, even more importantly, fixing issues, we want developers to have access to those updates as fast as possible. For this reason we will make a release **every 4 weeks**.
Once the project reaches a more mature state (>= `1.0.0`), we will very likely switch to longer release cycles of **6 weeks**.
The "feature freeze" will happen **one week before the release date**. This means a new branch will be created originating from the `master` tip at that time, and in that branch we will stop adding new features and only focus on ensuring the ones we've added are working properly.
To create a new release a release manager will create a new issue using the `Release` template and follow the template instructions.
[used by the Rust language]: https://doc.rust-lang.org/book/appendix-07-nightly-rust.html
[Semantic Versioning]: https://semver.org/

29
LICENSE
View File

@ -1,21 +1,14 @@
MIT License
This software is licensed under [Apache 2.0](LICENSE-APACHE) or
[MIT](LICENSE-MIT), at your option.
Copyright (c) 2020 Magical Bitcoin
Some files retain their own copyright notice, however, for full authorship
information, see version control history.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Except as otherwise noted in individual files, all files in this repository are
licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
http://opensource.org/licenses/MIT>, at your option.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
You may not use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of this software or any files in this repository except in
accordance with one or both of these licenses.

201
LICENSE-APACHE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

16
LICENSE-MIT Normal file
View File

@ -0,0 +1,16 @@
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,7 +1,94 @@
# Magical Bitcoin Wallet
# The Bitcoin Dev Kit
A modern, lightweight, descriptor-based wallet written in Rust!
<div align="center">
<h1>BDK</h1>
## Getting Started
<img src="./static/bdk.png" width="220" />
See the documentation at [magicalbitcoin.org](https://magicalbitcoin.org)
<p>
<strong>A modern, lightweight, descriptor-based wallet library written in Rust!</strong>
</p>
<p>
<a href="https://crates.io/crates/bdk_wallet"><img alt="Crate Info" src="https://img.shields.io/crates/v/bdk_wallet.svg"/></a>
<a href="https://github.com/bitcoindevkit/bdk/blob/master/LICENSE"><img alt="MIT or Apache-2.0 Licensed" src="https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg"/></a>
<a href="https://github.com/bitcoindevkit/bdk/actions?query=workflow%3ACI"><img alt="CI Status" src="https://github.com/bitcoindevkit/bdk/workflows/CI/badge.svg"></a>
<a href="https://coveralls.io/github/bitcoindevkit/bdk?branch=master"><img src="https://coveralls.io/repos/github/bitcoindevkit/bdk/badge.svg?branch=master"/></a>
<a href="https://docs.rs/bdk_wallet"><img alt="Wallet API Docs" src="https://img.shields.io/badge/docs.rs-bdk_wallet-green"/></a>
<a href="https://blog.rust-lang.org/2022/08/11/Rust-1.63.0.html"><img alt="Rustc Version 1.63.0+" src="https://img.shields.io/badge/rustc-1.63.0%2B-lightgrey.svg"/></a>
<a href="https://discord.gg/d7NkDKm"><img alt="Chat on Discord" src="https://img.shields.io/discord/753336465005608961?logo=discord"></a>
</p>
<h4>
<a href="https://bitcoindevkit.org">Project Homepage</a>
<span> | </span>
<a href="https://docs.rs/bdk_wallet">Documentation</a>
</h4>
</div>
## About
The `bdk` libraries aims to provide well engineered and reviewed components for Bitcoin based applications.
It is built upon the excellent [`rust-bitcoin`] and [`rust-miniscript`] crates.
> ⚠ The Bitcoin Dev Kit developers are in the process of releasing a `v1.0` which is a fundamental re-write of how the library works.
> See for some background on this project: https://bitcoindevkit.org/blog/road-to-bdk-1/ (ignore the timeline 😁)
> For a release timeline see the [`BDK 1.0 project page`].
## Architecture
The project is split up into several crates in the `/crates` directory:
- [`wallet`](./crates/wallet): Contains the central high level `Wallet` type that is built from the low-level mechanisms provided by the other components
- [`chain`](./crates/chain): Tools for storing and indexing chain data
- [`persist`](./crates/persist): Types that define data persistence of a BDK wallet
- [`file_store`](./crates/file_store): A (experimental) persistence backend for storing chain data in a single file.
- [`esplora`](./crates/esplora): Extends the [`esplora-client`] crate with methods to fetch chain data from an esplora HTTP server in the form that [`bdk_chain`] and `Wallet` can consume.
- [`electrum`](./crates/electrum): Extends the [`electrum-client`] crate with methods to fetch chain data from an electrum server in the form that [`bdk_chain`] and `Wallet` can consume.
Fully working examples of how to use these components are in `/example-crates`:
- [`example_cli`](./example-crates/example_cli): Library used by the `example_*` crates. Provides utilities for syncing, showing the balance, generating addresses and creating transactions without using the bdk_wallet `Wallet`.
- [`example_electrum`](./example-crates/example_electrum): A command line Bitcoin wallet application built on top of `example_cli` and the `electrum` crate. It shows the power of the bdk tools (`chain` + `file_store` + `electrum`), without depending on the main `bdk_wallet` library.
- [`example_esplora`](./example-crates/example_esplora): A command line Bitcoin wallet application built on top of `example_cli` and the `esplora` crate. It shows the power of the bdk tools (`chain` + `file_store` + `esplora`), without depending on the main `bdk_wallet` library.
- [`example_bitcoind_rpc_polling`](./example-crates/example_bitcoind_rpc_polling): A command line Bitcoin wallet application built on top of `example_cli` and the `bitcoind_rpc` crate. It shows the power of the bdk tools (`chain` + `file_store` + `bitcoind_rpc`), without depending on the main `bdk_wallet` library.
- [`wallet_esplora_blocking`](./example-crates/wallet_esplora_blocking): Uses the `Wallet` to sync and spend using the Esplora blocking interface.
- [`wallet_esplora_async`](./example-crates/wallet_esplora_async): Uses the `Wallet` to sync and spend using the Esplora asynchronous interface.
- [`wallet_electrum`](./example-crates/wallet_electrum): Uses the `Wallet` to sync and spend using Electrum.
[`BDK 1.0 project page`]: https://github.com/orgs/bitcoindevkit/projects/14
[`rust-miniscript`]: https://github.com/rust-bitcoin/rust-miniscript
[`rust-bitcoin`]: https://github.com/rust-bitcoin/rust-bitcoin
[`esplora-client`]: https://docs.rs/esplora-client/
[`electrum-client`]: https://docs.rs/electrum-client/
[`bdk_chain`]: https://docs.rs/bdk-chain/
## Minimum Supported Rust Version (MSRV)
This library should compile with any combination of features with Rust 1.63.0.
To build with the MSRV you will need to pin dependencies as follows:
```shell
cargo update -p zstd-sys --precise "2.0.8+zstd.1.5.5"
cargo update -p time --precise "0.3.20"
cargo update -p home --precise "0.5.5"
cargo update -p proptest --precise "1.2.0"
cargo update -p url --precise "2.5.0"
cargo update -p cc --precise "1.0.105"
cargo update -p tokio --precise "1.38.1"
```
## License
Licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <https://www.apache.org/licenses/LICENSE-2.0>)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or <https://opensource.org/licenses/MIT>)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache-2.0
license, shall be dual licensed as above, without any additional terms or
conditions.

9
ci/Dockerfile.ledger Normal file
View File

@ -0,0 +1,9 @@
# Taken from bitcoindevkit/rust-hwi
FROM ghcr.io/ledgerhq/speculos
RUN apt-get update
RUN apt-get install wget -y
RUN wget "https://github.com/LedgerHQ/speculos/blob/master/apps/nanos%23btc%232.1%231c8db8da.elf?raw=true" -O /speculos/btc.elf
ADD automation.json /speculos/automation.json
ENTRYPOINT ["python", "./speculos.py", "--automation", "file:automation.json", "--model", "nanos", "--display", "headless", "--vnc-port", "41000", "btc.elf"]

30
ci/automation.json Normal file
View File

@ -0,0 +1,30 @@
{
"version": 1,
"rules": [
{
"regexp": "Address \\(\\d/\\d\\)|Message hash \\(\\d/\\d\\)|Confirm|Fees|Review|Amount",
"actions": [
[ "button", 2, true ],
[ "button", 2, false ]
]
},
{
"text": "Sign",
"conditions": [
[ "seen", false ]
],
"actions": [
[ "button", 2, true ],
[ "button", 2, false ],
[ "setbool", "seen", true ]
]
},
{
"regexp": "Approve|Sign|Accept",
"actions": [
[ "button", 3, true ],
[ "button", 3, false ]
]
}
]
}

14
ci/start-core.sh Executable file
View File

@ -0,0 +1,14 @@
#!/usr/bin/env sh
echo "Starting bitcoin node."
mkdir $GITHUB_WORKSPACE/.bitcoin
/root/bitcoind -regtest -server -daemon -datadir=$GITHUB_WORKSPACE/.bitcoin -fallbackfee=0.0002 -rpcallowip=0.0.0.0/0 -rpcbind=0.0.0.0 -blockfilterindex=1 -peerblockfilters=1
echo "Waiting for bitcoin node."
until /root/bitcoin-cli -regtest -datadir=$GITHUB_WORKSPACE/.bitcoin getblockchaininfo; do
sleep 1
done
/root/bitcoin-cli -regtest -datadir=$GITHUB_WORKSPACE/.bitcoin createwallet $BDK_RPC_WALLET
echo "Generating 150 bitcoin blocks."
ADDR=$(/root/bitcoin-cli -regtest -datadir=$GITHUB_WORKSPACE/.bitcoin -rpcwallet=$BDK_RPC_WALLET getnewaddress)
/root/bitcoin-cli -regtest -datadir=$GITHUB_WORKSPACE/.bitcoin generatetoaddress 150 $ADDR

1
clippy.toml Normal file
View File

@ -0,0 +1 @@
msrv="1.63.0"

View File

@ -0,0 +1,26 @@
[package]
name = "bdk_bitcoind_rpc"
version = "0.13.0"
edition = "2021"
rust-version = "1.63"
homepage = "https://bitcoindevkit.org"
repository = "https://github.com/bitcoindevkit/bdk"
documentation = "https://docs.rs/bdk_bitcoind_rpc"
description = "This crate is used for emitting blockchain data from the `bitcoind` RPC interface."
license = "MIT OR Apache-2.0"
readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bitcoin = { version = "0.32.0", default-features = false }
bitcoincore-rpc = { version = "0.19.0" }
bdk_chain = { path = "../chain", version = "0.17", default-features = false }
[dev-dependencies]
bdk_testenv = { path = "../testenv", default-features = false }
[features]
default = ["std"]
std = ["bitcoin/std", "bdk_chain/std"]
serde = ["bitcoin/serde", "bdk_chain/serde"]

View File

@ -0,0 +1,3 @@
# BDK Bitcoind RPC
This crate is used for emitting blockchain data from the `bitcoind` RPC interface.

View File

@ -0,0 +1,328 @@
//! This crate is used for emitting blockchain data from the `bitcoind` RPC interface. It does not
//! use the wallet RPC API, so this crate can be used with wallet-disabled Bitcoin Core nodes.
//!
//! [`Emitter`] is the main structure which sources blockchain data from [`bitcoincore_rpc::Client`].
//!
//! To only get block updates (exclude mempool transactions), the caller can use
//! [`Emitter::next_block`] or/and [`Emitter::next_header`] until it returns `Ok(None)` (which means
//! the chain tip is reached). A separate method, [`Emitter::mempool`] can be used to emit the whole
//! mempool.
#![warn(missing_docs)]
use bdk_chain::{local_chain::CheckPoint, BlockId};
use bitcoin::{block::Header, Block, BlockHash, Transaction};
pub use bitcoincore_rpc;
use bitcoincore_rpc::bitcoincore_rpc_json;
/// The [`Emitter`] is used to emit data sourced from [`bitcoincore_rpc::Client`].
///
/// Refer to [module-level documentation] for more.
///
/// [module-level documentation]: crate
pub struct Emitter<'c, C> {
client: &'c C,
start_height: u32,
/// The checkpoint of the last-emitted block that is in the best chain. If it is later found
/// that the block is no longer in the best chain, it will be popped off from here.
last_cp: CheckPoint,
/// The block result returned from rpc of the last-emitted block. As this result contains the
/// next block's block hash (which we use to fetch the next block), we set this to `None`
/// whenever there are no more blocks, or the next block is no longer in the best chain. This
/// gives us an opportunity to re-fetch this result.
last_block: Option<bitcoincore_rpc_json::GetBlockResult>,
/// The latest first-seen epoch of emitted mempool transactions. This is used to determine
/// whether a mempool transaction is already emitted.
last_mempool_time: usize,
/// The last emitted block during our last mempool emission. This is used to determine whether
/// there has been a reorg since our last mempool emission.
last_mempool_tip: Option<u32>,
}
impl<'c, C: bitcoincore_rpc::RpcApi> Emitter<'c, C> {
/// Construct a new [`Emitter`].
///
/// `last_cp` informs the emitter of the chain we are starting off with. This way, the emitter
/// can start emission from a block that connects to the original chain.
///
/// `start_height` starts emission from a given height (if there are no conflicts with the
/// original chain).
pub fn new(client: &'c C, last_cp: CheckPoint, start_height: u32) -> Self {
Self {
client,
start_height,
last_cp,
last_block: None,
last_mempool_time: 0,
last_mempool_tip: None,
}
}
/// Emit mempool transactions, alongside their first-seen unix timestamps.
///
/// This method emits each transaction only once, unless we cannot guarantee the transaction's
/// ancestors are already emitted.
///
/// To understand why, consider a receiver which filters transactions based on whether it
/// alters the UTXO set of tracked script pubkeys. If an emitted mempool transaction spends a
/// tracked UTXO which is confirmed at height `h`, but the receiver has only seen up to block
/// of height `h-1`, we want to re-emit this transaction until the receiver has seen the block
/// at height `h`.
pub fn mempool(&mut self) -> Result<Vec<(Transaction, u64)>, bitcoincore_rpc::Error> {
let client = self.client;
// This is the emitted tip height during the last mempool emission.
let prev_mempool_tip = self
.last_mempool_tip
// We use `start_height - 1` as we cannot guarantee that the block at
// `start_height` has been emitted.
.unwrap_or(self.start_height.saturating_sub(1));
// Mempool txs come with a timestamp of when the tx is introduced to the mempool. We keep
// track of the latest mempool tx's timestamp to determine whether we have seen a tx
// before. `prev_mempool_time` is the previous timestamp and `last_time` records what will
// be the new latest timestamp.
let prev_mempool_time = self.last_mempool_time;
let mut latest_time = prev_mempool_time;
let txs_to_emit = client
.get_raw_mempool_verbose()?
.into_iter()
.filter_map({
let latest_time = &mut latest_time;
move |(txid, tx_entry)| -> Option<Result<_, bitcoincore_rpc::Error>> {
let tx_time = tx_entry.time as usize;
if tx_time > *latest_time {
*latest_time = tx_time;
}
// Avoid emitting transactions that are already emitted if we can guarantee
// blocks containing ancestors are already emitted. The bitcoind rpc interface
// provides us with the block height that the tx is introduced to the mempool.
// If we have already emitted the block of height, we can assume that all
// ancestor txs have been processed by the receiver.
let is_already_emitted = tx_time <= prev_mempool_time;
let is_within_height = tx_entry.height <= prev_mempool_tip as _;
if is_already_emitted && is_within_height {
return None;
}
let tx = match client.get_raw_transaction(&txid, None) {
Ok(tx) => tx,
// the tx is confirmed or evicted since `get_raw_mempool_verbose`
Err(err) if err.is_not_found_error() => return None,
Err(err) => return Some(Err(err)),
};
Some(Ok((tx, tx_time as u64)))
}
})
.collect::<Result<Vec<_>, _>>()?;
self.last_mempool_time = latest_time;
self.last_mempool_tip = Some(self.last_cp.height());
Ok(txs_to_emit)
}
/// Emit the next block height and header (if any).
pub fn next_header(&mut self) -> Result<Option<BlockEvent<Header>>, bitcoincore_rpc::Error> {
Ok(poll(self, |hash| self.client.get_block_header(hash))?
.map(|(checkpoint, block)| BlockEvent { block, checkpoint }))
}
/// Emit the next block height and block (if any).
pub fn next_block(&mut self) -> Result<Option<BlockEvent<Block>>, bitcoincore_rpc::Error> {
Ok(poll(self, |hash| self.client.get_block(hash))?
.map(|(checkpoint, block)| BlockEvent { block, checkpoint }))
}
}
/// A newly emitted block from [`Emitter`].
#[derive(Debug)]
pub struct BlockEvent<B> {
/// Either a full [`Block`] or [`Header`] of the new block.
pub block: B,
/// The checkpoint of the new block.
///
/// A [`CheckPoint`] is a node of a linked list of [`BlockId`]s. This checkpoint is linked to
/// all [`BlockId`]s originally passed in [`Emitter::new`] as well as emitted blocks since then.
/// These blocks are guaranteed to be of the same chain.
///
/// This is important as BDK structures require block-to-apply to be connected with another
/// block in the original chain.
pub checkpoint: CheckPoint,
}
impl<B> BlockEvent<B> {
/// The block height of this new block.
pub fn block_height(&self) -> u32 {
self.checkpoint.height()
}
/// The block hash of this new block.
pub fn block_hash(&self) -> BlockHash {
self.checkpoint.hash()
}
/// The [`BlockId`] of a previous block that this block connects to.
///
/// This either returns a [`BlockId`] of a previously emitted block or from the chain we started
/// with (passed in as `last_cp` in [`Emitter::new`]).
///
/// This value is derived from [`BlockEvent::checkpoint`].
pub fn connected_to(&self) -> BlockId {
match self.checkpoint.prev() {
Some(prev_cp) => prev_cp.block_id(),
// there is no previous checkpoint, so just connect with itself
None => self.checkpoint.block_id(),
}
}
}
enum PollResponse {
Block(bitcoincore_rpc_json::GetBlockResult),
NoMoreBlocks,
/// Fetched block is not in the best chain.
BlockNotInBestChain,
AgreementFound(bitcoincore_rpc_json::GetBlockResult, CheckPoint),
/// Force the genesis checkpoint down the receiver's throat.
AgreementPointNotFound(BlockHash),
}
fn poll_once<C>(emitter: &Emitter<C>) -> Result<PollResponse, bitcoincore_rpc::Error>
where
C: bitcoincore_rpc::RpcApi,
{
let client = emitter.client;
if let Some(last_res) = &emitter.last_block {
let next_hash = if last_res.height < emitter.start_height as _ {
// enforce start height
let next_hash = client.get_block_hash(emitter.start_height as _)?;
// make sure last emission is still in best chain
if client.get_block_hash(last_res.height as _)? != last_res.hash {
return Ok(PollResponse::BlockNotInBestChain);
}
next_hash
} else {
match last_res.nextblockhash {
None => return Ok(PollResponse::NoMoreBlocks),
Some(next_hash) => next_hash,
}
};
let res = client.get_block_info(&next_hash)?;
if res.confirmations < 0 {
return Ok(PollResponse::BlockNotInBestChain);
}
return Ok(PollResponse::Block(res));
}
for cp in emitter.last_cp.iter() {
let res = match client.get_block_info(&cp.hash()) {
// block not in best chain
Ok(res) if res.confirmations < 0 => continue,
Ok(res) => res,
Err(e) if e.is_not_found_error() => {
if cp.height() > 0 {
continue;
}
// if we can't find genesis block, we can't create an update that connects
break;
}
Err(e) => return Err(e),
};
// agreement point found
return Ok(PollResponse::AgreementFound(res, cp));
}
let genesis_hash = client.get_block_hash(0)?;
Ok(PollResponse::AgreementPointNotFound(genesis_hash))
}
fn poll<C, V, F>(
emitter: &mut Emitter<C>,
get_item: F,
) -> Result<Option<(CheckPoint, V)>, bitcoincore_rpc::Error>
where
C: bitcoincore_rpc::RpcApi,
F: Fn(&BlockHash) -> Result<V, bitcoincore_rpc::Error>,
{
loop {
match poll_once(emitter)? {
PollResponse::Block(res) => {
let height = res.height as u32;
let hash = res.hash;
let item = get_item(&hash)?;
let new_cp = emitter
.last_cp
.clone()
.push(BlockId { height, hash })
.expect("must push");
emitter.last_cp = new_cp.clone();
emitter.last_block = Some(res);
return Ok(Some((new_cp, item)));
}
PollResponse::NoMoreBlocks => {
emitter.last_block = None;
return Ok(None);
}
PollResponse::BlockNotInBestChain => {
emitter.last_block = None;
continue;
}
PollResponse::AgreementFound(res, cp) => {
let agreement_h = res.height as u32;
// The tip during the last mempool emission needs to in the best chain, we reduce
// it if it is not.
if let Some(h) = emitter.last_mempool_tip.as_mut() {
if *h > agreement_h {
*h = agreement_h;
}
}
// get rid of evicted blocks
emitter.last_cp = cp;
emitter.last_block = Some(res);
continue;
}
PollResponse::AgreementPointNotFound(genesis_hash) => {
emitter.last_cp = CheckPoint::new(BlockId {
height: 0,
hash: genesis_hash,
});
emitter.last_block = None;
continue;
}
}
}
}
/// Extends [`bitcoincore_rpc::Error`].
pub trait BitcoindRpcErrorExt {
/// Returns whether the error is a "not found" error.
///
/// This is useful since [`Emitter`] emits [`Result<_, bitcoincore_rpc::Error>`]s as
/// [`Iterator::Item`].
fn is_not_found_error(&self) -> bool;
}
impl BitcoindRpcErrorExt for bitcoincore_rpc::Error {
fn is_not_found_error(&self) -> bool {
if let bitcoincore_rpc::Error::JsonRpc(bitcoincore_rpc::jsonrpc::Error::Rpc(rpc_err)) = self
{
rpc_err.code == -5
} else {
false
}
}
}

View File

@ -0,0 +1,738 @@
use std::collections::{BTreeMap, BTreeSet};
use bdk_bitcoind_rpc::Emitter;
use bdk_chain::{
bitcoin::{Address, Amount, Txid},
local_chain::{CheckPoint, LocalChain},
spk_txout::SpkTxOutIndex,
Balance, BlockId, IndexedTxGraph, Merge,
};
use bdk_testenv::{anyhow, TestEnv};
use bitcoin::{hashes::Hash, Block, OutPoint, ScriptBuf, WScriptHash};
use bitcoincore_rpc::RpcApi;
/// Ensure that blocks are emitted in order even after reorg.
///
/// 1. Mine 101 blocks.
/// 2. Emit blocks from [`Emitter`] and update the [`LocalChain`].
/// 3. Reorg highest 6 blocks.
/// 4. Emit blocks from [`Emitter`] and re-update the [`LocalChain`].
#[test]
pub fn test_sync_local_chain() -> anyhow::Result<()> {
let env = TestEnv::new()?;
let network_tip = env.rpc_client().get_block_count()?;
let (mut local_chain, _) = LocalChain::from_genesis_hash(env.rpc_client().get_block_hash(0)?);
let mut emitter = Emitter::new(env.rpc_client(), local_chain.tip(), 0);
// Mine some blocks and return the actual block hashes.
// Because initializing `ElectrsD` already mines some blocks, we must include those too when
// returning block hashes.
let exp_hashes = {
let mut hashes = (0..=network_tip)
.map(|height| env.rpc_client().get_block_hash(height))
.collect::<Result<Vec<_>, _>>()?;
hashes.extend(env.mine_blocks(101 - network_tip as usize, None)?);
hashes
};
// See if the emitter outputs the right blocks.
println!("first sync:");
while let Some(emission) = emitter.next_block()? {
let height = emission.block_height();
let hash = emission.block_hash();
assert_eq!(
emission.block_hash(),
exp_hashes[height as usize],
"emitted block hash is unexpected"
);
assert_eq!(
local_chain.apply_update(emission.checkpoint,)?,
[(height, Some(hash))].into(),
"chain update changeset is unexpected",
);
}
assert_eq!(
local_chain
.iter_checkpoints()
.map(|cp| (cp.height(), cp.hash()))
.collect::<BTreeSet<_>>(),
exp_hashes
.iter()
.enumerate()
.map(|(i, hash)| (i as u32, *hash))
.collect::<BTreeSet<_>>(),
"final local_chain state is unexpected",
);
// Perform reorg.
let reorged_blocks = env.reorg(6)?;
let exp_hashes = exp_hashes
.iter()
.take(exp_hashes.len() - reorged_blocks.len())
.chain(&reorged_blocks)
.cloned()
.collect::<Vec<_>>();
// See if the emitter outputs the right blocks.
println!("after reorg:");
let mut exp_height = exp_hashes.len() - reorged_blocks.len();
while let Some(emission) = emitter.next_block()? {
let height = emission.block_height();
let hash = emission.block_hash();
assert_eq!(
height, exp_height as u32,
"emitted block has unexpected height"
);
assert_eq!(
hash, exp_hashes[height as usize],
"emitted block is unexpected"
);
assert_eq!(
local_chain.apply_update(emission.checkpoint,)?,
if exp_height == exp_hashes.len() - reorged_blocks.len() {
bdk_chain::local_chain::ChangeSet {
blocks: core::iter::once((height, Some(hash)))
.chain((height + 1..exp_hashes.len() as u32).map(|h| (h, None)))
.collect(),
}
} else {
[(height, Some(hash))].into()
},
"chain update changeset is unexpected",
);
exp_height += 1;
}
assert_eq!(
local_chain
.iter_checkpoints()
.map(|cp| (cp.height(), cp.hash()))
.collect::<BTreeSet<_>>(),
exp_hashes
.iter()
.enumerate()
.map(|(i, hash)| (i as u32, *hash))
.collect::<BTreeSet<_>>(),
"final local_chain state is unexpected after reorg",
);
Ok(())
}
/// Ensure that [`EmittedUpdate::into_tx_graph_update`] behaves appropriately for both mempool and
/// block updates.
///
/// [`EmittedUpdate::into_tx_graph_update`]: bdk_bitcoind_rpc::EmittedUpdate::into_tx_graph_update
#[test]
fn test_into_tx_graph() -> anyhow::Result<()> {
let env = TestEnv::new()?;
println!("getting new addresses!");
let addr_0 = env
.rpc_client()
.get_new_address(None, None)?
.assume_checked();
let addr_1 = env
.rpc_client()
.get_new_address(None, None)?
.assume_checked();
let addr_2 = env
.rpc_client()
.get_new_address(None, None)?
.assume_checked();
println!("got new addresses!");
println!("mining block!");
env.mine_blocks(101, None)?;
println!("mined blocks!");
let (mut chain, _) = LocalChain::from_genesis_hash(env.rpc_client().get_block_hash(0)?);
let mut indexed_tx_graph = IndexedTxGraph::<BlockId, _>::new({
let mut index = SpkTxOutIndex::<usize>::default();
index.insert_spk(0, addr_0.script_pubkey());
index.insert_spk(1, addr_1.script_pubkey());
index.insert_spk(2, addr_2.script_pubkey());
index
});
let emitter = &mut Emitter::new(env.rpc_client(), chain.tip(), 0);
while let Some(emission) = emitter.next_block()? {
let height = emission.block_height();
let _ = chain.apply_update(emission.checkpoint)?;
let indexed_additions = indexed_tx_graph.apply_block_relevant(&emission.block, height);
assert!(indexed_additions.is_empty());
}
// send 3 txs to a tracked address, these txs will be in the mempool
let exp_txids = {
let mut txids = BTreeSet::new();
for _ in 0..3 {
txids.insert(env.rpc_client().send_to_address(
&addr_0,
Amount::from_sat(10_000),
None,
None,
None,
None,
None,
None,
)?);
}
txids
};
// expect that the next block should be none and we should get 3 txs from mempool
{
// next block should be `None`
assert!(emitter.next_block()?.is_none());
let mempool_txs = emitter.mempool()?;
let indexed_additions = indexed_tx_graph.batch_insert_unconfirmed(mempool_txs);
assert_eq!(
indexed_additions
.tx_graph
.txs
.iter()
.map(|tx| tx.compute_txid())
.collect::<BTreeSet<Txid>>(),
exp_txids,
"changeset should have the 3 mempool transactions",
);
assert!(indexed_additions.tx_graph.anchors.is_empty());
}
// mine a block that confirms the 3 txs
let exp_block_hash = env.mine_blocks(1, None)?[0];
let exp_block_height = env.rpc_client().get_block_info(&exp_block_hash)?.height as u32;
let exp_anchors = exp_txids
.iter()
.map({
let anchor = BlockId {
height: exp_block_height,
hash: exp_block_hash,
};
move |&txid| (anchor, txid)
})
.collect::<BTreeSet<_>>();
// must receive mined block which will confirm the transactions.
{
let emission = emitter.next_block()?.expect("must get mined block");
let height = emission.block_height();
let _ = chain.apply_update(emission.checkpoint)?;
let indexed_additions = indexed_tx_graph.apply_block_relevant(&emission.block, height);
assert!(indexed_additions.tx_graph.txs.is_empty());
assert!(indexed_additions.tx_graph.txouts.is_empty());
assert_eq!(indexed_additions.tx_graph.anchors, exp_anchors);
}
Ok(())
}
/// Ensure next block emitted after reorg is at reorg height.
///
/// After a reorg, if the last-emitted block height is equal or greater than the reorg height, and
/// the fallback height is equal to or lower than the reorg height, the next block/header emission
/// should be at the reorg height.
///
/// TODO: If the reorg height is lower than the fallback height, how do we find a block height to
/// emit that can connect with our receiver chain?
#[test]
fn ensure_block_emitted_after_reorg_is_at_reorg_height() -> anyhow::Result<()> {
const EMITTER_START_HEIGHT: usize = 100;
const CHAIN_TIP_HEIGHT: usize = 110;
let env = TestEnv::new()?;
let mut emitter = Emitter::new(
env.rpc_client(),
CheckPoint::new(BlockId {
height: 0,
hash: env.rpc_client().get_block_hash(0)?,
}),
EMITTER_START_HEIGHT as _,
);
env.mine_blocks(CHAIN_TIP_HEIGHT, None)?;
while emitter.next_header()?.is_some() {}
for reorg_count in 1..=10 {
let replaced_blocks = env.reorg_empty_blocks(reorg_count)?;
let next_emission = emitter.next_header()?.expect("must emit block after reorg");
assert_eq!(
(
next_emission.block_height() as usize,
next_emission.block_hash()
),
replaced_blocks[0],
"block emitted after reorg should be at the reorg height"
);
while emitter.next_header()?.is_some() {}
}
Ok(())
}
fn process_block(
recv_chain: &mut LocalChain,
recv_graph: &mut IndexedTxGraph<BlockId, SpkTxOutIndex<()>>,
block: Block,
block_height: u32,
) -> anyhow::Result<()> {
recv_chain.apply_update(CheckPoint::from_header(&block.header, block_height))?;
let _ = recv_graph.apply_block(block, block_height);
Ok(())
}
fn sync_from_emitter<C>(
recv_chain: &mut LocalChain,
recv_graph: &mut IndexedTxGraph<BlockId, SpkTxOutIndex<()>>,
emitter: &mut Emitter<C>,
) -> anyhow::Result<()>
where
C: bitcoincore_rpc::RpcApi,
{
while let Some(emission) = emitter.next_block()? {
let height = emission.block_height();
process_block(recv_chain, recv_graph, emission.block, height)?;
}
Ok(())
}
fn get_balance(
recv_chain: &LocalChain,
recv_graph: &IndexedTxGraph<BlockId, SpkTxOutIndex<()>>,
) -> anyhow::Result<Balance> {
let chain_tip = recv_chain.tip().block_id();
let outpoints = recv_graph.index.outpoints().clone();
let balance = recv_graph
.graph()
.balance(recv_chain, chain_tip, outpoints, |_, _| true);
Ok(balance)
}
/// If a block is reorged out, ensure that containing transactions that do not exist in the
/// replacement block(s) become unconfirmed.
#[test]
fn tx_can_become_unconfirmed_after_reorg() -> anyhow::Result<()> {
const PREMINE_COUNT: usize = 101;
const ADDITIONAL_COUNT: usize = 11;
const SEND_AMOUNT: Amount = Amount::from_sat(10_000);
let env = TestEnv::new()?;
let mut emitter = Emitter::new(
env.rpc_client(),
CheckPoint::new(BlockId {
height: 0,
hash: env.rpc_client().get_block_hash(0)?,
}),
0,
);
// setup addresses
let addr_to_mine = env
.rpc_client()
.get_new_address(None, None)?
.assume_checked();
let spk_to_track = ScriptBuf::new_p2wsh(&WScriptHash::all_zeros());
let addr_to_track = Address::from_script(&spk_to_track, bitcoin::Network::Regtest)?;
// setup receiver
let (mut recv_chain, _) = LocalChain::from_genesis_hash(env.rpc_client().get_block_hash(0)?);
let mut recv_graph = IndexedTxGraph::<BlockId, _>::new({
let mut recv_index = SpkTxOutIndex::default();
recv_index.insert_spk((), spk_to_track.clone());
recv_index
});
// mine and sync receiver up to tip
env.mine_blocks(PREMINE_COUNT, Some(addr_to_mine))?;
// create transactions that are tracked by our receiver
for _ in 0..ADDITIONAL_COUNT {
let txid = env.send(&addr_to_track, SEND_AMOUNT)?;
// lock outputs that send to `addr_to_track`
let outpoints_to_lock = env
.rpc_client()
.get_transaction(&txid, None)?
.transaction()?
.output
.into_iter()
.enumerate()
.filter(|(_, txo)| txo.script_pubkey == spk_to_track)
.map(|(vout, _)| OutPoint::new(txid, vout as _))
.collect::<Vec<_>>();
env.rpc_client().lock_unspent(&outpoints_to_lock)?;
let _ = env.mine_blocks(1, None)?;
}
// get emitter up to tip
sync_from_emitter(&mut recv_chain, &mut recv_graph, &mut emitter)?;
assert_eq!(
get_balance(&recv_chain, &recv_graph)?,
Balance {
confirmed: SEND_AMOUNT * ADDITIONAL_COUNT as u64,
..Balance::default()
},
"initial balance must be correct",
);
// perform reorgs with different depths
for reorg_count in 1..=ADDITIONAL_COUNT {
env.reorg_empty_blocks(reorg_count)?;
sync_from_emitter(&mut recv_chain, &mut recv_graph, &mut emitter)?;
assert_eq!(
get_balance(&recv_chain, &recv_graph)?,
Balance {
confirmed: SEND_AMOUNT * (ADDITIONAL_COUNT - reorg_count) as u64,
..Balance::default()
},
"reorg_count: {}",
reorg_count,
);
}
Ok(())
}
/// Ensure avoid-re-emission-logic is sound when [`Emitter`] is synced to tip.
///
/// The receiver (bdk_chain structures) is synced to the chain tip, and there is txs in the mempool.
/// When we call Emitter::mempool multiple times, mempool txs should not be re-emitted, even if the
/// chain tip is extended.
#[test]
fn mempool_avoids_re_emission() -> anyhow::Result<()> {
const BLOCKS_TO_MINE: usize = 101;
const MEMPOOL_TX_COUNT: usize = 2;
let env = TestEnv::new()?;
let mut emitter = Emitter::new(
env.rpc_client(),
CheckPoint::new(BlockId {
height: 0,
hash: env.rpc_client().get_block_hash(0)?,
}),
0,
);
// mine blocks and sync up emitter
let addr = env
.rpc_client()
.get_new_address(None, None)?
.assume_checked();
env.mine_blocks(BLOCKS_TO_MINE, Some(addr.clone()))?;
while emitter.next_header()?.is_some() {}
// have some random txs in mempool
let exp_txids = (0..MEMPOOL_TX_COUNT)
.map(|_| env.send(&addr, Amount::from_sat(2100)))
.collect::<Result<BTreeSet<Txid>, _>>()?;
// the first emission should include all transactions
let emitted_txids = emitter
.mempool()?
.into_iter()
.map(|(tx, _)| tx.compute_txid())
.collect::<BTreeSet<Txid>>();
assert_eq!(
emitted_txids, exp_txids,
"all mempool txs should be emitted"
);
// second emission should be empty
assert!(
emitter.mempool()?.is_empty(),
"second emission should be empty"
);
// mine empty blocks + sync up our emitter -> we should still not re-emit
for _ in 0..BLOCKS_TO_MINE {
env.mine_empty_block()?;
}
while emitter.next_header()?.is_some() {}
assert!(
emitter.mempool()?.is_empty(),
"third emission, after chain tip is extended, should also be empty"
);
Ok(())
}
/// Ensure mempool tx is still re-emitted if [`Emitter`] has not reached the tx's introduction
/// height.
///
/// We introduce a mempool tx after each block, where blocks are empty (does not confirm previous
/// mempool txs). Then we emit blocks from [`Emitter`] (intertwining `mempool` calls). We check
/// that `mempool` should always re-emit txs that have introduced at a height greater than the last
/// emitted block height.
#[test]
fn mempool_re_emits_if_tx_introduction_height_not_reached() -> anyhow::Result<()> {
const PREMINE_COUNT: usize = 101;
const MEMPOOL_TX_COUNT: usize = 21;
let env = TestEnv::new()?;
let mut emitter = Emitter::new(
env.rpc_client(),
CheckPoint::new(BlockId {
height: 0,
hash: env.rpc_client().get_block_hash(0)?,
}),
0,
);
// mine blocks to get initial balance, sync emitter up to tip
let addr = env
.rpc_client()
.get_new_address(None, None)?
.assume_checked();
env.mine_blocks(PREMINE_COUNT, Some(addr.clone()))?;
while emitter.next_header()?.is_some() {}
// mine blocks to introduce txs to mempool at different heights
let tx_introductions = (0..MEMPOOL_TX_COUNT)
.map(|_| -> anyhow::Result<_> {
let (height, _) = env.mine_empty_block()?;
let txid = env.send(&addr, Amount::from_sat(2100))?;
Ok((height, txid))
})
.collect::<anyhow::Result<BTreeSet<_>>>()?;
assert_eq!(
emitter
.mempool()?
.into_iter()
.map(|(tx, _)| tx.compute_txid())
.collect::<BTreeSet<_>>(),
tx_introductions.iter().map(|&(_, txid)| txid).collect(),
"first mempool emission should include all txs",
);
assert_eq!(
emitter
.mempool()?
.into_iter()
.map(|(tx, _)| tx.compute_txid())
.collect::<BTreeSet<_>>(),
tx_introductions.iter().map(|&(_, txid)| txid).collect(),
"second mempool emission should still include all txs",
);
// At this point, the emitter has seen all mempool transactions. It should only re-emit those
// that have introduction heights less than the emitter's last-emitted block tip.
while let Some(emission) = emitter.next_header()? {
let height = emission.block_height();
// We call `mempool()` twice.
// The second call (at height `h`) should skip the tx introduced at height `h`.
for try_index in 0..2 {
let exp_txids = tx_introductions
.range((height as usize + try_index, Txid::all_zeros())..)
.map(|&(_, txid)| txid)
.collect::<BTreeSet<_>>();
let emitted_txids = emitter
.mempool()?
.into_iter()
.map(|(tx, _)| tx.compute_txid())
.collect::<BTreeSet<_>>();
assert_eq!(
emitted_txids, exp_txids,
"\n emission {} (try {}) must only contain txs introduced at that height or lower: \n\t missing: {:?} \n\t extra: {:?}",
height,
try_index,
exp_txids
.difference(&emitted_txids)
.map(|txid| (txid, tx_introductions.iter().find_map(|(h, id)| if id == txid { Some(h) } else { None }).unwrap()))
.collect::<Vec<_>>(),
emitted_txids
.difference(&exp_txids)
.map(|txid| (txid, tx_introductions.iter().find_map(|(h, id)| if id == txid { Some(h) } else { None }).unwrap()))
.collect::<Vec<_>>(),
);
}
}
Ok(())
}
/// Ensure we force re-emit all mempool txs after reorg.
#[test]
fn mempool_during_reorg() -> anyhow::Result<()> {
const TIP_DIFF: usize = 10;
const PREMINE_COUNT: usize = 101;
let env = TestEnv::new()?;
let mut emitter = Emitter::new(
env.rpc_client(),
CheckPoint::new(BlockId {
height: 0,
hash: env.rpc_client().get_block_hash(0)?,
}),
0,
);
// mine blocks to get initial balance
let addr = env
.rpc_client()
.get_new_address(None, None)?
.assume_checked();
env.mine_blocks(PREMINE_COUNT, Some(addr.clone()))?;
// introduce mempool tx at each block extension
for _ in 0..TIP_DIFF {
env.mine_empty_block()?;
env.send(&addr, Amount::from_sat(2100))?;
}
// sync emitter to tip, first mempool emission should include all txs (as we haven't emitted
// from the mempool yet)
while emitter.next_header()?.is_some() {}
assert_eq!(
emitter
.mempool()?
.into_iter()
.map(|(tx, _)| tx.compute_txid())
.collect::<BTreeSet<_>>(),
env.rpc_client()
.get_raw_mempool()?
.into_iter()
.collect::<BTreeSet<_>>(),
"first mempool emission should include all txs",
);
// perform reorgs at different heights, these reorgs will not confirm transactions in the
// mempool
for reorg_count in 1..TIP_DIFF {
println!("REORG COUNT: {}", reorg_count);
env.reorg_empty_blocks(reorg_count)?;
// This is a map of mempool txids to tip height where the tx was introduced to the mempool
// we recalculate this at every loop as reorgs may evict transactions from mempool. We use
// the introduction height to determine whether we expect a tx to appear in a mempool
// emission.
// TODO: How can have have reorg logic in `TestEnv` NOT blacklast old blocks first?
let tx_introductions = dbg!(env
.rpc_client()
.get_raw_mempool_verbose()?
.into_iter()
.map(|(txid, entry)| (txid, entry.height as usize))
.collect::<BTreeMap<_, _>>());
// `next_header` emits the replacement block of the reorg
if let Some(emission) = emitter.next_header()? {
let height = emission.block_height();
println!("\t- replacement height: {}", height);
// the mempool emission (that follows the first block emission after reorg) should only
// include mempool txs introduced at reorg height or greater
let mempool = emitter
.mempool()?
.into_iter()
.map(|(tx, _)| tx.compute_txid())
.collect::<BTreeSet<_>>();
let exp_mempool = tx_introductions
.iter()
.filter(|(_, &intro_h)| intro_h >= (height as usize))
.map(|(&txid, _)| txid)
.collect::<BTreeSet<_>>();
assert_eq!(
mempool, exp_mempool,
"the first mempool emission after reorg should only include mempool txs introduced at reorg height or greater"
);
let mempool = emitter
.mempool()?
.into_iter()
.map(|(tx, _)| tx.compute_txid())
.collect::<BTreeSet<_>>();
let exp_mempool = tx_introductions
.iter()
.filter(|&(_, &intro_height)| intro_height > (height as usize))
.map(|(&txid, _)| txid)
.collect::<BTreeSet<_>>();
assert_eq!(
mempool, exp_mempool,
"following mempool emissions after reorg should exclude mempool introduction heights <= last emitted block height: \n\t missing: {:?} \n\t extra: {:?}",
exp_mempool
.difference(&mempool)
.map(|txid| (txid, tx_introductions.get(txid).unwrap()))
.collect::<Vec<_>>(),
mempool
.difference(&exp_mempool)
.map(|txid| (txid, tx_introductions.get(txid).unwrap()))
.collect::<Vec<_>>(),
);
}
// sync emitter to tip
while emitter.next_header()?.is_some() {}
}
Ok(())
}
/// If blockchain re-org includes the start height, emit new start height block
///
/// 1. mine 101 blocks
/// 2. emit blocks 99a, 100a
/// 3. invalidate blocks 99a, 100a, 101a
/// 4. mine new blocks 99b, 100b, 101b
/// 5. emit block 99b
///
/// The block hash of 99b should be different than 99a, but their previous block hashes should
/// be the same.
#[test]
fn no_agreement_point() -> anyhow::Result<()> {
const PREMINE_COUNT: usize = 101;
let env = TestEnv::new()?;
// start height is 99
let mut emitter = Emitter::new(
env.rpc_client(),
CheckPoint::new(BlockId {
height: 0,
hash: env.rpc_client().get_block_hash(0)?,
}),
(PREMINE_COUNT - 2) as u32,
);
// mine 101 blocks
env.mine_blocks(PREMINE_COUNT, None)?;
// emit block 99a
let block_header_99a = emitter.next_header()?.expect("block 99a header").block;
let block_hash_99a = block_header_99a.block_hash();
let block_hash_98a = block_header_99a.prev_blockhash;
// emit block 100a
let block_header_100a = emitter.next_header()?.expect("block 100a header").block;
let block_hash_100a = block_header_100a.block_hash();
// get hash for block 101a
let block_hash_101a = env.rpc_client().get_block_hash(101)?;
// invalidate blocks 99a, 100a, 101a
env.rpc_client().invalidate_block(&block_hash_99a)?;
env.rpc_client().invalidate_block(&block_hash_100a)?;
env.rpc_client().invalidate_block(&block_hash_101a)?;
// mine new blocks 99b, 100b, 101b
env.mine_blocks(3, None)?;
// emit block header 99b
let block_header_99b = emitter.next_header()?.expect("block 99b header").block;
let block_hash_99b = block_header_99b.block_hash();
let block_hash_98b = block_header_99b.prev_blockhash;
assert_ne!(block_hash_99a, block_hash_99b);
assert_eq!(block_hash_98a, block_hash_98b);
Ok(())
}

35
crates/chain/Cargo.toml Normal file
View File

@ -0,0 +1,35 @@
[package]
name = "bdk_chain"
version = "0.17.0"
edition = "2021"
rust-version = "1.63"
homepage = "https://bitcoindevkit.org"
repository = "https://github.com/bitcoindevkit/bdk"
documentation = "https://docs.rs/bdk_chain"
description = "Collection of core structures for Bitcoin Dev Kit."
license = "MIT OR Apache-2.0"
readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bitcoin = { version = "0.32.0", default-features = false }
serde_crate = { package = "serde", version = "1", optional = true, features = ["derive", "rc"] }
# Use hashbrown as a feature flag to have HashSet and HashMap from it.
hashbrown = { version = "0.9.1", optional = true, features = ["serde"] }
miniscript = { version = "12.0.0", optional = true, default-features = false }
# Feature dependencies
rusqlite_crate = { package = "rusqlite", version = "0.31.0", features = ["bundled"], optional = true }
serde_json = {version = "1", optional = true }
[dev-dependencies]
rand = "0.8"
proptest = "1.2.0"
[features]
default = ["std", "miniscript"]
std = ["bitcoin/std", "miniscript?/std"]
serde = ["serde_crate", "bitcoin/serde", "miniscript?/serde"]
rusqlite = ["std", "rusqlite_crate", "serde", "serde_json"]

3
crates/chain/README.md Normal file
View File

@ -0,0 +1,3 @@
# BDK Chain
BDK keychain tracker, tools for storing and indexing chain data.

View File

@ -0,0 +1,57 @@
use bitcoin::Amount;
/// Balance, differentiated into various categories.
#[derive(Debug, PartialEq, Eq, Clone, Default)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate",)
)]
pub struct Balance {
/// All coinbase outputs not yet matured
pub immature: Amount,
/// Unconfirmed UTXOs generated by a wallet tx
pub trusted_pending: Amount,
/// Unconfirmed UTXOs received from an external wallet
pub untrusted_pending: Amount,
/// Confirmed and immediately spendable balance
pub confirmed: Amount,
}
impl Balance {
/// Get sum of trusted_pending and confirmed coins.
///
/// This is the balance you can spend right now that shouldn't get cancelled via another party
/// double spending it.
pub fn trusted_spendable(&self) -> Amount {
self.confirmed + self.trusted_pending
}
/// Get the whole balance visible to the wallet.
pub fn total(&self) -> Amount {
self.confirmed + self.trusted_pending + self.untrusted_pending + self.immature
}
}
impl core::fmt::Display for Balance {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"{{ immature: {}, trusted_pending: {}, untrusted_pending: {}, confirmed: {} }}",
self.immature, self.trusted_pending, self.untrusted_pending, self.confirmed
)
}
}
impl core::ops::Add for Balance {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
immature: self.immature + other.immature,
trusted_pending: self.trusted_pending + other.trusted_pending,
untrusted_pending: self.untrusted_pending + other.untrusted_pending,
confirmed: self.confirmed + other.confirmed,
}
}
}

View File

@ -0,0 +1,287 @@
use bitcoin::{hashes::Hash, BlockHash, OutPoint, TxOut, Txid};
use crate::{Anchor, AnchorFromBlockPosition, COINBASE_MATURITY};
/// Represents the observed position of some chain data.
///
/// The generic `A` should be a [`Anchor`] implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, core::hash::Hash)]
pub enum ChainPosition<A> {
/// The chain data is seen as confirmed, and in anchored by `A`.
Confirmed(A),
/// The chain data is not confirmed and last seen in the mempool at this timestamp.
Unconfirmed(u64),
}
impl<A> ChainPosition<A> {
/// Returns whether [`ChainPosition`] is confirmed or not.
pub fn is_confirmed(&self) -> bool {
matches!(self, Self::Confirmed(_))
}
}
impl<A: Clone> ChainPosition<&A> {
/// Maps a [`ChainPosition<&A>`] into a [`ChainPosition<A>`] by cloning the contents.
pub fn cloned(self) -> ChainPosition<A> {
match self {
ChainPosition::Confirmed(a) => ChainPosition::Confirmed(a.clone()),
ChainPosition::Unconfirmed(last_seen) => ChainPosition::Unconfirmed(last_seen),
}
}
}
impl<A: Anchor> ChainPosition<A> {
/// Determines the upper bound of the confirmation height.
pub fn confirmation_height_upper_bound(&self) -> Option<u32> {
match self {
ChainPosition::Confirmed(a) => Some(a.confirmation_height_upper_bound()),
ChainPosition::Unconfirmed(_) => None,
}
}
}
/// Block height and timestamp at which a transaction is confirmed.
#[derive(Debug, Clone, PartialEq, Eq, Copy, PartialOrd, Ord, core::hash::Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate")
)]
pub enum ConfirmationTime {
/// The transaction is confirmed
Confirmed {
/// Confirmation height.
height: u32,
/// Confirmation time in unix seconds.
time: u64,
},
/// The transaction is unconfirmed
Unconfirmed {
/// The last-seen timestamp in unix seconds.
last_seen: u64,
},
}
impl ConfirmationTime {
/// Construct an unconfirmed variant using the given `last_seen` time in unix seconds.
pub fn unconfirmed(last_seen: u64) -> Self {
Self::Unconfirmed { last_seen }
}
/// Returns whether [`ConfirmationTime`] is the confirmed variant.
pub fn is_confirmed(&self) -> bool {
matches!(self, Self::Confirmed { .. })
}
}
impl From<ChainPosition<ConfirmationBlockTime>> for ConfirmationTime {
fn from(observed_as: ChainPosition<ConfirmationBlockTime>) -> Self {
match observed_as {
ChainPosition::Confirmed(a) => Self::Confirmed {
height: a.block_id.height,
time: a.confirmation_time,
},
ChainPosition::Unconfirmed(last_seen) => Self::Unconfirmed { last_seen },
}
}
}
/// A reference to a block in the canonical chain.
///
/// `BlockId` implements [`Anchor`]. When a transaction is anchored to `BlockId`, the confirmation
/// block and anchor block are the same block.
#[derive(Debug, Clone, PartialEq, Eq, Copy, PartialOrd, Ord, core::hash::Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate")
)]
pub struct BlockId {
/// The height of the block.
pub height: u32,
/// The hash of the block.
pub hash: BlockHash,
}
impl Anchor for BlockId {
fn anchor_block(&self) -> Self {
*self
}
}
impl AnchorFromBlockPosition for BlockId {
fn from_block_position(_block: &bitcoin::Block, block_id: BlockId, _tx_pos: usize) -> Self {
block_id
}
}
impl Default for BlockId {
fn default() -> Self {
Self {
height: Default::default(),
hash: BlockHash::all_zeros(),
}
}
}
impl From<(u32, BlockHash)> for BlockId {
fn from((height, hash): (u32, BlockHash)) -> Self {
Self { height, hash }
}
}
impl From<BlockId> for (u32, BlockHash) {
fn from(block_id: BlockId) -> Self {
(block_id.height, block_id.hash)
}
}
impl From<(&u32, &BlockHash)> for BlockId {
fn from((height, hash): (&u32, &BlockHash)) -> Self {
Self {
height: *height,
hash: *hash,
}
}
}
/// An [`Anchor`] implementation that also records the exact confirmation time of the transaction.
///
/// Refer to [`Anchor`] for more details.
#[derive(Debug, Default, Clone, PartialEq, Eq, Copy, PartialOrd, Ord, core::hash::Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate")
)]
pub struct ConfirmationBlockTime {
/// The anchor block.
pub block_id: BlockId,
/// The confirmation time of the transaction being anchored.
pub confirmation_time: u64,
}
impl Anchor for ConfirmationBlockTime {
fn anchor_block(&self) -> BlockId {
self.block_id
}
fn confirmation_height_upper_bound(&self) -> u32 {
self.block_id.height
}
}
impl AnchorFromBlockPosition for ConfirmationBlockTime {
fn from_block_position(block: &bitcoin::Block, block_id: BlockId, _tx_pos: usize) -> Self {
Self {
block_id,
confirmation_time: block.header.time as _,
}
}
}
/// A `TxOut` with as much data as we can retrieve about it
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FullTxOut<A> {
/// The position of the transaction in `outpoint` in the overall chain.
pub chain_position: ChainPosition<A>,
/// The location of the `TxOut`.
pub outpoint: OutPoint,
/// The `TxOut`.
pub txout: TxOut,
/// The txid and chain position of the transaction (if any) that has spent this output.
pub spent_by: Option<(ChainPosition<A>, Txid)>,
/// Whether this output is on a coinbase transaction.
pub is_on_coinbase: bool,
}
impl<A: Anchor> FullTxOut<A> {
/// Whether the `txout` is considered mature.
///
/// Depending on the implementation of [`confirmation_height_upper_bound`] in [`Anchor`], this
/// method may return false-negatives. In other words, interpreted confirmation count may be
/// less than the actual value.
///
/// [`confirmation_height_upper_bound`]: Anchor::confirmation_height_upper_bound
pub fn is_mature(&self, tip: u32) -> bool {
if self.is_on_coinbase {
let tx_height = match &self.chain_position {
ChainPosition::Confirmed(anchor) => anchor.confirmation_height_upper_bound(),
ChainPosition::Unconfirmed(_) => {
debug_assert!(false, "coinbase tx can never be unconfirmed");
return false;
}
};
let age = tip.saturating_sub(tx_height);
if age + 1 < COINBASE_MATURITY {
return false;
}
}
true
}
/// Whether the utxo is/was/will be spendable with chain `tip`.
///
/// This method does not take into account the lock time.
///
/// Depending on the implementation of [`confirmation_height_upper_bound`] in [`Anchor`], this
/// method may return false-negatives. In other words, interpreted confirmation count may be
/// less than the actual value.
///
/// [`confirmation_height_upper_bound`]: Anchor::confirmation_height_upper_bound
pub fn is_confirmed_and_spendable(&self, tip: u32) -> bool {
if !self.is_mature(tip) {
return false;
}
let confirmation_height = match &self.chain_position {
ChainPosition::Confirmed(anchor) => anchor.confirmation_height_upper_bound(),
ChainPosition::Unconfirmed(_) => return false,
};
if confirmation_height > tip {
return false;
}
// if the spending tx is confirmed within tip height, the txout is no longer spendable
if let Some((ChainPosition::Confirmed(spending_anchor), _)) = &self.spent_by {
if spending_anchor.anchor_block().height <= tip {
return false;
}
}
true
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn chain_position_ord() {
let unconf1 = ChainPosition::<ConfirmationBlockTime>::Unconfirmed(10);
let unconf2 = ChainPosition::<ConfirmationBlockTime>::Unconfirmed(20);
let conf1 = ChainPosition::Confirmed(ConfirmationBlockTime {
confirmation_time: 20,
block_id: BlockId {
height: 9,
..Default::default()
},
});
let conf2 = ChainPosition::Confirmed(ConfirmationBlockTime {
confirmation_time: 15,
block_id: BlockId {
height: 12,
..Default::default()
},
});
assert!(unconf2 > unconf1, "higher last_seen means higher ord");
assert!(unconf1 > conf1, "unconfirmed is higher ord than confirmed");
assert!(
conf2 > conf1,
"confirmation_height is higher then it should be higher ord"
);
}
}

View File

@ -0,0 +1,25 @@
use crate::BlockId;
/// Represents a service that tracks the blockchain.
///
/// The main method is [`is_block_in_chain`] which determines whether a given block of [`BlockId`]
/// is an ancestor of the `chain_tip`.
///
/// [`is_block_in_chain`]: Self::is_block_in_chain
pub trait ChainOracle {
/// Error type.
type Error: core::fmt::Debug;
/// Determines whether `block` of [`BlockId`] exists as an ancestor of `chain_tip`.
///
/// If `None` is returned, it means the implementation cannot determine whether `block` exists
/// under `chain_tip`.
fn is_block_in_chain(
&self,
block: BlockId,
chain_tip: BlockId,
) -> Result<Option<bool>, Self::Error>;
/// Get the best chain's chain tip.
fn get_chain_tip(&self) -> Result<BlockId, Self::Error>;
}

View File

@ -0,0 +1,38 @@
use crate::miniscript::{Descriptor, DescriptorPublicKey};
use bitcoin::hashes::{hash_newtype, sha256, Hash};
hash_newtype! {
/// Represents the unique ID of a descriptor.
///
/// This is useful for having a fixed-length unique representation of a descriptor,
/// in particular, we use it to persist application state changes related to the
/// descriptor without having to re-write the whole descriptor each time.
///
pub struct DescriptorId(pub sha256::Hash);
}
/// A trait to extend the functionality of a miniscript descriptor.
pub trait DescriptorExt {
/// Returns the minimum value (in satoshis) at which an output is broadcastable.
/// Panics if the descriptor wildcard is hardened.
fn dust_value(&self) -> u64;
/// Returns the descriptor ID, calculated as the sha256 hash of the spk derived from the
/// descriptor at index 0.
fn descriptor_id(&self) -> DescriptorId;
}
impl DescriptorExt for Descriptor<DescriptorPublicKey> {
fn dust_value(&self) -> u64 {
self.at_derivation_index(0)
.expect("descriptor can't have hardened derivation")
.script_pubkey()
.minimal_non_dust()
.to_sat()
}
fn descriptor_id(&self) -> DescriptorId {
let spk = self.at_derivation_index(0).unwrap().script_pubkey();
DescriptorId(sha256::Hash::hash(spk.as_bytes()))
}
}

View File

@ -0,0 +1,30 @@
#![allow(unused)]
use alloc::vec::Vec;
use bitcoin::{
consensus,
hashes::{hex::FromHex, Hash},
Transaction,
};
use crate::BlockId;
pub const RAW_TX_1: &str = "0200000000010116d6174da7183d70d0a7d4dc314d517a7d135db79ad63515028b293a76f4f9d10000000000feffffff023a21fc8350060000160014531c405e1881ef192294b8813631e258bf98ea7a1027000000000000225120a60869f0dbcf1dc659c9cecbaf8050135ea9e8cdc487053f1dc6880949dc684c024730440220591b1a172a122da49ba79a3e79f98aaa03fd7a372f9760da18890b6a327e6010022013e82319231da6c99abf8123d7c07e13cf9bd8d76e113e18dc452e5024db156d012102318a2d558b2936c52e320decd6d92a88d7f530be91b6fe0af5caf41661e77da3ef2e0100";
pub const RAW_TX_2: &str = "02000000000101a688607020cfae91a61e7c516b5ef1264d5d77f17200c3866826c6c808ebf1620000000000feffffff021027000000000000225120a60869f0dbcf1dc659c9cecbaf8050135ea9e8cdc487053f1dc6880949dc684c20fd48ff530600001600146886c525e41d4522042bd0b159dfbade2504a6bb024730440220740ff7e665cd20565d4296b549df8d26b941be3f1e3af89a0b60e50c0dbeb69a02206213ab7030cf6edc6c90d4ccf33010644261e029950a688dc0b1a9ebe6ddcc5a012102f2ac6b396a97853cb6cd62242c8ae4842024742074475023532a51e9c53194253e760100";
pub const RAW_TX_3: &str = "0200000000010135d67ee47b557e68b8c6223958f597381965ed719f1207ee2b9e20432a24a5dc0100000000feffffff021027000000000000225120a82f29944d65b86ae6b5e5cc75e294ead6c59391a1edc5e016e3498c67fc7bbb62215a5055060000160014070df7671dea67a50c4799a744b5c9be8f4bac690247304402207ebf8d29f71fd03e7e6977b3ea78ca5fcc5c49a42ae822348fc401862fdd766c02201d7e4ff0684ecb008b6142f36ead1b0b4d615524c4f58c261113d361f4427e25012103e6a75e2fab85e5ecad641afc4ffba7222f998649d9f18cac92f0fcc8618883b3ee760100";
pub const RAW_TX_4: &str = "02000000000101d00e8f76ed313e19b339ee293c0f52b0325c95e24c8f3966fa353fb2bedbcf580100000000feffffff021027000000000000225120882d74e5d0572d5a816cef0041a96b6c1de832f6f9676d9605c44d5e9a97d3dc9cda55fe53060000160014852b5864b8edd42fab4060c87f818e50780865ff0247304402201dccbb9bed7fba924b6d249c5837cc9b37470c0e3d8fbea77cb59baba3efe6fa0220700cc170916913b9bfc2bc0fefb6af776e8b542c561702f136cddc1c7aa43141012103acec3fc79dbbca745815c2a807dc4e81010c80e308e84913f59cb42a275dad97f3760100";
pub fn tx_from_hex(s: &str) -> Transaction {
let raw = Vec::from_hex(s).expect("data must be in hex");
consensus::deserialize(raw.as_slice()).expect("must deserialize")
}
pub fn new_hash<H: Hash>(s: &str) -> H {
<H as bitcoin::hashes::Hash>::hash(s.as_bytes())
}
pub fn new_block_id(height: u32, hash: &str) -> BlockId {
BlockId {
height,
hash: new_hash(hash),
}
}

View File

@ -0,0 +1,362 @@
//! Contains the [`IndexedTxGraph`] and associated types. Refer to the
//! [`IndexedTxGraph`] documentation for more.
use core::fmt::Debug;
use alloc::vec::Vec;
use bitcoin::{Block, OutPoint, Transaction, TxOut, Txid};
use crate::{
tx_graph::{self, TxGraph},
Anchor, AnchorFromBlockPosition, BlockId, Indexer, Merge,
};
/// The [`IndexedTxGraph`] combines a [`TxGraph`] and an [`Indexer`] implementation.
///
/// It ensures that [`TxGraph`] and [`Indexer`] are updated atomically.
#[derive(Debug)]
pub struct IndexedTxGraph<A, I> {
/// Transaction index.
pub index: I,
graph: TxGraph<A>,
}
impl<A, I: Default> Default for IndexedTxGraph<A, I> {
fn default() -> Self {
Self {
graph: Default::default(),
index: Default::default(),
}
}
}
impl<A, I> IndexedTxGraph<A, I> {
/// Construct a new [`IndexedTxGraph`] with a given `index`.
pub fn new(index: I) -> Self {
Self {
index,
graph: TxGraph::default(),
}
}
/// Get a reference of the internal transaction graph.
pub fn graph(&self) -> &TxGraph<A> {
&self.graph
}
}
impl<A: Anchor, I: Indexer> IndexedTxGraph<A, I> {
/// Applies the [`ChangeSet`] to the [`IndexedTxGraph`].
pub fn apply_changeset(&mut self, changeset: ChangeSet<A, I::ChangeSet>) {
self.index.apply_changeset(changeset.indexer);
for tx in &changeset.tx_graph.txs {
self.index.index_tx(tx);
}
for (&outpoint, txout) in &changeset.tx_graph.txouts {
self.index.index_txout(outpoint, txout);
}
self.graph.apply_changeset(changeset.tx_graph);
}
/// Determines the [`ChangeSet`] between `self` and an empty [`IndexedTxGraph`].
pub fn initial_changeset(&self) -> ChangeSet<A, I::ChangeSet> {
let graph = self.graph.initial_changeset();
let indexer = self.index.initial_changeset();
ChangeSet {
tx_graph: graph,
indexer,
}
}
}
impl<A: Anchor, I: Indexer> IndexedTxGraph<A, I>
where
I::ChangeSet: Default + Merge,
{
fn index_tx_graph_changeset(
&mut self,
tx_graph_changeset: &tx_graph::ChangeSet<A>,
) -> I::ChangeSet {
let mut changeset = I::ChangeSet::default();
for added_tx in &tx_graph_changeset.txs {
changeset.merge(self.index.index_tx(added_tx));
}
for (&added_outpoint, added_txout) in &tx_graph_changeset.txouts {
changeset.merge(self.index.index_txout(added_outpoint, added_txout));
}
changeset
}
/// Apply an `update` directly.
///
/// `update` is a [`TxGraph<A>`] and the resultant changes is returned as [`ChangeSet`].
pub fn apply_update(&mut self, update: TxGraph<A>) -> ChangeSet<A, I::ChangeSet> {
let graph = self.graph.apply_update(update);
let indexer = self.index_tx_graph_changeset(&graph);
ChangeSet {
tx_graph: graph,
indexer,
}
}
/// Insert a floating `txout` of given `outpoint`.
pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) -> ChangeSet<A, I::ChangeSet> {
let graph = self.graph.insert_txout(outpoint, txout);
let indexer = self.index_tx_graph_changeset(&graph);
ChangeSet {
tx_graph: graph,
indexer,
}
}
/// Insert and index a transaction into the graph.
pub fn insert_tx(&mut self, tx: Transaction) -> ChangeSet<A, I::ChangeSet> {
let graph = self.graph.insert_tx(tx);
let indexer = self.index_tx_graph_changeset(&graph);
ChangeSet {
tx_graph: graph,
indexer,
}
}
/// Insert an `anchor` for a given transaction.
pub fn insert_anchor(&mut self, txid: Txid, anchor: A) -> ChangeSet<A, I::ChangeSet> {
self.graph.insert_anchor(txid, anchor).into()
}
/// Insert a unix timestamp of when a transaction is seen in the mempool.
///
/// This is used for transaction conflict resolution in [`TxGraph`] where the transaction with
/// the later last-seen is prioritized.
pub fn insert_seen_at(&mut self, txid: Txid, seen_at: u64) -> ChangeSet<A, I::ChangeSet> {
self.graph.insert_seen_at(txid, seen_at).into()
}
/// Batch insert transactions, filtering out those that are irrelevant.
///
/// Relevancy is determined by the [`Indexer::is_tx_relevant`] implementation of `I`. Irrelevant
/// transactions in `txs` will be ignored. `txs` do not need to be in topological order.
pub fn batch_insert_relevant<'t>(
&mut self,
txs: impl IntoIterator<Item = (&'t Transaction, impl IntoIterator<Item = A>)>,
) -> ChangeSet<A, I::ChangeSet> {
// The algorithm below allows for non-topologically ordered transactions by using two loops.
// This is achieved by:
// 1. insert all txs into the index. If they are irrelevant then that's fine it will just
// not store anything about them.
// 2. decide whether to insert them into the graph depending on whether `is_tx_relevant`
// returns true or not. (in a second loop).
let txs = txs.into_iter().collect::<Vec<_>>();
let mut indexer = I::ChangeSet::default();
for (tx, _) in &txs {
indexer.merge(self.index.index_tx(tx));
}
let mut graph = tx_graph::ChangeSet::default();
for (tx, anchors) in txs {
if self.index.is_tx_relevant(tx) {
let txid = tx.compute_txid();
graph.merge(self.graph.insert_tx(tx.clone()));
for anchor in anchors {
graph.merge(self.graph.insert_anchor(txid, anchor));
}
}
}
ChangeSet {
tx_graph: graph,
indexer,
}
}
/// Batch insert unconfirmed transactions, filtering out those that are irrelevant.
///
/// Relevancy is determined by the internal [`Indexer::is_tx_relevant`] implementation of `I`.
/// Irrelevant transactions in `txs` will be ignored.
///
/// Items of `txs` are tuples containing the transaction and a *last seen* timestamp. The
/// *last seen* communicates when the transaction is last seen in the mempool which is used for
/// conflict-resolution in [`TxGraph`] (refer to [`TxGraph::insert_seen_at`] for details).
pub fn batch_insert_relevant_unconfirmed<'t>(
&mut self,
unconfirmed_txs: impl IntoIterator<Item = (&'t Transaction, u64)>,
) -> ChangeSet<A, I::ChangeSet> {
// The algorithm below allows for non-topologically ordered transactions by using two loops.
// This is achieved by:
// 1. insert all txs into the index. If they are irrelevant then that's fine it will just
// not store anything about them.
// 2. decide whether to insert them into the graph depending on whether `is_tx_relevant`
// returns true or not. (in a second loop).
let txs = unconfirmed_txs.into_iter().collect::<Vec<_>>();
let mut indexer = I::ChangeSet::default();
for (tx, _) in &txs {
indexer.merge(self.index.index_tx(tx));
}
let graph = self.graph.batch_insert_unconfirmed(
txs.into_iter()
.filter(|(tx, _)| self.index.is_tx_relevant(tx))
.map(|(tx, seen_at)| (tx.clone(), seen_at)),
);
ChangeSet {
tx_graph: graph,
indexer,
}
}
/// Batch insert unconfirmed transactions.
///
/// Items of `txs` are tuples containing the transaction and a *last seen* timestamp. The
/// *last seen* communicates when the transaction is last seen in the mempool which is used for
/// conflict-resolution in [`TxGraph`] (refer to [`TxGraph::insert_seen_at`] for details).
///
/// To filter out irrelevant transactions, use [`batch_insert_relevant_unconfirmed`] instead.
///
/// [`batch_insert_relevant_unconfirmed`]: IndexedTxGraph::batch_insert_relevant_unconfirmed
pub fn batch_insert_unconfirmed(
&mut self,
txs: impl IntoIterator<Item = (Transaction, u64)>,
) -> ChangeSet<A, I::ChangeSet> {
let graph = self.graph.batch_insert_unconfirmed(txs);
let indexer = self.index_tx_graph_changeset(&graph);
ChangeSet {
tx_graph: graph,
indexer,
}
}
}
/// Methods are available if the anchor (`A`) implements [`AnchorFromBlockPosition`].
impl<A: Anchor, I: Indexer> IndexedTxGraph<A, I>
where
I::ChangeSet: Default + Merge,
A: AnchorFromBlockPosition,
{
/// Batch insert all transactions of the given `block` of `height`, filtering out those that are
/// irrelevant.
///
/// Each inserted transaction's anchor will be constructed from
/// [`AnchorFromBlockPosition::from_block_position`].
///
/// Relevancy is determined by the internal [`Indexer::is_tx_relevant`] implementation of `I`.
/// Irrelevant transactions in `txs` will be ignored.
pub fn apply_block_relevant(
&mut self,
block: &Block,
height: u32,
) -> ChangeSet<A, I::ChangeSet> {
let block_id = BlockId {
hash: block.block_hash(),
height,
};
let mut changeset = ChangeSet::<A, I::ChangeSet>::default();
for (tx_pos, tx) in block.txdata.iter().enumerate() {
changeset.indexer.merge(self.index.index_tx(tx));
if self.index.is_tx_relevant(tx) {
let txid = tx.compute_txid();
let anchor = A::from_block_position(block, block_id, tx_pos);
changeset.tx_graph.merge(self.graph.insert_tx(tx.clone()));
changeset
.tx_graph
.merge(self.graph.insert_anchor(txid, anchor));
}
}
changeset
}
/// Batch insert all transactions of the given `block` of `height`.
///
/// Each inserted transaction's anchor will be constructed from
/// [`AnchorFromBlockPosition::from_block_position`].
///
/// To only insert relevant transactions, use [`apply_block_relevant`] instead.
///
/// [`apply_block_relevant`]: IndexedTxGraph::apply_block_relevant
pub fn apply_block(&mut self, block: Block, height: u32) -> ChangeSet<A, I::ChangeSet> {
let block_id = BlockId {
hash: block.block_hash(),
height,
};
let mut graph = tx_graph::ChangeSet::default();
for (tx_pos, tx) in block.txdata.iter().enumerate() {
let anchor = A::from_block_position(&block, block_id, tx_pos);
graph.merge(self.graph.insert_anchor(tx.compute_txid(), anchor));
graph.merge(self.graph.insert_tx(tx.clone()));
}
let indexer = self.index_tx_graph_changeset(&graph);
ChangeSet {
tx_graph: graph,
indexer,
}
}
}
impl<A, I> AsRef<TxGraph<A>> for IndexedTxGraph<A, I> {
fn as_ref(&self) -> &TxGraph<A> {
&self.graph
}
}
/// Represents changes to an [`IndexedTxGraph`].
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(
crate = "serde_crate",
bound(
deserialize = "A: Ord + serde::Deserialize<'de>, IA: serde::Deserialize<'de>",
serialize = "A: Ord + serde::Serialize, IA: serde::Serialize"
)
)
)]
#[must_use]
pub struct ChangeSet<A, IA> {
/// [`TxGraph`] changeset.
pub tx_graph: tx_graph::ChangeSet<A>,
/// [`Indexer`] changeset.
pub indexer: IA,
}
impl<A, IA: Default> Default for ChangeSet<A, IA> {
fn default() -> Self {
Self {
tx_graph: Default::default(),
indexer: Default::default(),
}
}
}
impl<A: Anchor, IA: Merge> Merge for ChangeSet<A, IA> {
fn merge(&mut self, other: Self) {
self.tx_graph.merge(other.tx_graph);
self.indexer.merge(other.indexer);
}
fn is_empty(&self) -> bool {
self.tx_graph.is_empty() && self.indexer.is_empty()
}
}
impl<A, IA: Default> From<tx_graph::ChangeSet<A>> for ChangeSet<A, IA> {
fn from(graph: tx_graph::ChangeSet<A>) -> Self {
Self {
tx_graph: graph,
..Default::default()
}
}
}
#[cfg(feature = "miniscript")]
impl<A> From<crate::keychain_txout::ChangeSet> for ChangeSet<A, crate::keychain_txout::ChangeSet> {
fn from(indexer: crate::keychain_txout::ChangeSet) -> Self {
Self {
tx_graph: Default::default(),
indexer,
}
}
}

View File

@ -0,0 +1,33 @@
//! [`Indexer`] provides utilities for indexing transaction data.
use bitcoin::{OutPoint, Transaction, TxOut};
#[cfg(feature = "miniscript")]
pub mod keychain_txout;
pub mod spk_txout;
/// Utilities for indexing transaction data.
///
/// Types which implement this trait can be used to construct an [`IndexedTxGraph`].
/// This trait's methods should rarely be called directly.
///
/// [`IndexedTxGraph`]: crate::IndexedTxGraph
pub trait Indexer {
/// The resultant "changeset" when new transaction data is indexed.
type ChangeSet;
/// Scan and index the given `outpoint` and `txout`.
fn index_txout(&mut self, outpoint: OutPoint, txout: &TxOut) -> Self::ChangeSet;
/// Scans a transaction for relevant outpoints, which are stored and indexed internally.
fn index_tx(&mut self, tx: &Transaction) -> Self::ChangeSet;
/// Apply changeset to itself.
fn apply_changeset(&mut self, changeset: Self::ChangeSet);
/// Determines the [`ChangeSet`](Indexer::ChangeSet) between `self` and an empty [`Indexer`].
fn initial_changeset(&self) -> Self::ChangeSet;
/// Determines whether the transaction should be included in the index.
fn is_tx_relevant(&self, tx: &Transaction) -> bool;
}

View File

@ -0,0 +1,881 @@
//! [`KeychainTxOutIndex`] controls how script pubkeys are revealed for multiple keychains and
//! indexes [`TxOut`]s with them.
use crate::{
collections::*,
miniscript::{Descriptor, DescriptorPublicKey},
spk_iter::BIP32_MAX_INDEX,
spk_txout::SpkTxOutIndex,
DescriptorExt, DescriptorId, Indexed, Indexer, KeychainIndexed, SpkIterator,
};
use alloc::{borrow::ToOwned, vec::Vec};
use bitcoin::{Amount, OutPoint, ScriptBuf, SignedAmount, Transaction, TxOut, Txid};
use core::{
fmt::Debug,
ops::{Bound, RangeBounds},
};
use crate::Merge;
/// The default lookahead for a [`KeychainTxOutIndex`]
pub const DEFAULT_LOOKAHEAD: u32 = 25;
/// [`KeychainTxOutIndex`] controls how script pubkeys are revealed for multiple keychains, and
/// indexes [`TxOut`]s with them.
///
/// A single keychain is a chain of script pubkeys derived from a single [`Descriptor`]. Keychains
/// are identified using the `K` generic. Script pubkeys are identified by the keychain that they
/// are derived from `K`, as well as the derivation index `u32`.
///
/// There is a strict 1-to-1 relationship between descriptors and keychains. Each keychain has one
/// and only one descriptor and each descriptor has one and only one keychain. The
/// [`insert_descriptor`] method will return an error if you try and violate this invariant. This
/// rule is a proxy for a stronger rule: no two descriptors should produce the same script pubkey.
/// Having two descriptors produce the same script pubkey should cause whichever keychain derives
/// the script pubkey first to be the effective owner of it but you should not rely on this
/// behaviour. ⚠ It is up you, the developer, not to violate this invariant.
///
/// # Revealed script pubkeys
///
/// Tracking how script pubkeys are revealed is useful for collecting chain data. For example, if
/// the user has requested 5 script pubkeys (to receive money with), we only need to use those
/// script pubkeys to scan for chain data.
///
/// Call [`reveal_to_target`] or [`reveal_next_spk`] to reveal more script pubkeys.
/// Call [`revealed_keychain_spks`] or [`revealed_spks`] to iterate through revealed script pubkeys.
///
/// # Lookahead script pubkeys
///
/// When an user first recovers a wallet (i.e. from a recovery phrase and/or descriptor), we will
/// NOT have knowledge of which script pubkeys are revealed. So when we index a transaction or
/// txout (using [`index_tx`]/[`index_txout`]) we scan the txouts against script pubkeys derived
/// above the last revealed index. These additionally-derived script pubkeys are called the
/// lookahead.
///
/// The [`KeychainTxOutIndex`] is constructed with the `lookahead` and cannot be altered. See
/// [`DEFAULT_LOOKAHEAD`] for the value used in the `Default` implementation. Use [`new`] to set a
/// custom `lookahead`.
///
/// # Unbounded script pubkey iterator
///
/// For script-pubkey-based chain sources (such as Electrum/Esplora), an initial scan is best done
/// by iterating though derived script pubkeys one by one and requesting transaction histories for
/// each script pubkey. We will stop after x-number of script pubkeys have empty histories. An
/// unbounded script pubkey iterator is useful to pass to such a chain source because it doesn't
/// require holding a reference to the index.
///
/// Call [`unbounded_spk_iter`] to get an unbounded script pubkey iterator for a given keychain.
/// Call [`all_unbounded_spk_iters`] to get unbounded script pubkey iterators for all keychains.
///
/// # Change sets
///
/// Methods that can update the last revealed index or add keychains will return [`ChangeSet`] to report
/// these changes. This should be persisted for future recovery.
///
/// ## Synopsis
///
/// ```
/// use bdk_chain::indexer::keychain_txout::KeychainTxOutIndex;
/// # use bdk_chain::{ miniscript::{Descriptor, DescriptorPublicKey} };
/// # use core::str::FromStr;
///
/// // imagine our service has internal and external addresses but also addresses for users
/// #[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
/// enum MyKeychain {
/// External,
/// Internal,
/// MyAppUser {
/// user_id: u32
/// }
/// }
///
/// let mut txout_index = KeychainTxOutIndex::<MyKeychain>::default();
///
/// # let secp = bdk_chain::bitcoin::secp256k1::Secp256k1::signing_only();
/// # let (external_descriptor,_) = Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, "tr([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/0/*)").unwrap();
/// # let (internal_descriptor,_) = Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, "tr([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/*)").unwrap();
/// # let (descriptor_42, _) = Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, "tr([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/2/*)").unwrap();
/// let _ = txout_index.insert_descriptor(MyKeychain::External, external_descriptor)?;
/// let _ = txout_index.insert_descriptor(MyKeychain::Internal, internal_descriptor)?;
/// let _ = txout_index.insert_descriptor(MyKeychain::MyAppUser { user_id: 42 }, descriptor_42)?;
///
/// let new_spk_for_user = txout_index.reveal_next_spk(MyKeychain::MyAppUser{ user_id: 42 });
/// # Ok::<_, bdk_chain::indexer::keychain_txout::InsertDescriptorError<_>>(())
/// ```
///
/// [`Ord`]: core::cmp::Ord
/// [`SpkTxOutIndex`]: crate::spk_txout_index::SpkTxOutIndex
/// [`Descriptor`]: crate::miniscript::Descriptor
/// [`reveal_to_target`]: Self::reveal_to_target
/// [`reveal_next_spk`]: Self::reveal_next_spk
/// [`revealed_keychain_spks`]: Self::revealed_keychain_spks
/// [`revealed_spks`]: Self::revealed_spks
/// [`index_tx`]: Self::index_tx
/// [`index_txout`]: Self::index_txout
/// [`new`]: Self::new
/// [`unbounded_spk_iter`]: Self::unbounded_spk_iter
/// [`all_unbounded_spk_iters`]: Self::all_unbounded_spk_iters
/// [`outpoints`]: Self::outpoints
/// [`txouts`]: Self::txouts
/// [`unused_spks`]: Self::unused_spks
/// [`insert_descriptor`]: Self::insert_descriptor
#[derive(Clone, Debug)]
pub struct KeychainTxOutIndex<K> {
inner: SpkTxOutIndex<(K, u32)>,
keychain_to_descriptor_id: BTreeMap<K, DescriptorId>,
descriptor_id_to_keychain: HashMap<DescriptorId, K>,
descriptors: HashMap<DescriptorId, Descriptor<DescriptorPublicKey>>,
last_revealed: HashMap<DescriptorId, u32>,
lookahead: u32,
}
impl<K> Default for KeychainTxOutIndex<K> {
fn default() -> Self {
Self::new(DEFAULT_LOOKAHEAD)
}
}
impl<K: Clone + Ord + Debug> Indexer for KeychainTxOutIndex<K> {
type ChangeSet = ChangeSet;
fn index_txout(&mut self, outpoint: OutPoint, txout: &TxOut) -> Self::ChangeSet {
let mut changeset = ChangeSet::default();
if let Some((keychain, index)) = self.inner.scan_txout(outpoint, txout).cloned() {
let did = self
.keychain_to_descriptor_id
.get(&keychain)
.expect("invariant");
if self.last_revealed.get(did) < Some(&index) {
self.last_revealed.insert(*did, index);
changeset.last_revealed.insert(*did, index);
self.replenish_inner_index(*did, &keychain, self.lookahead);
}
}
changeset
}
fn index_tx(&mut self, tx: &bitcoin::Transaction) -> Self::ChangeSet {
let mut changeset = ChangeSet::default();
let txid = tx.compute_txid();
for (op, txout) in tx.output.iter().enumerate() {
changeset.merge(self.index_txout(OutPoint::new(txid, op as u32), txout));
}
changeset
}
fn initial_changeset(&self) -> Self::ChangeSet {
ChangeSet {
last_revealed: self.last_revealed.clone().into_iter().collect(),
}
}
fn apply_changeset(&mut self, changeset: Self::ChangeSet) {
self.apply_changeset(changeset)
}
fn is_tx_relevant(&self, tx: &bitcoin::Transaction) -> bool {
self.inner.is_relevant(tx)
}
}
impl<K> KeychainTxOutIndex<K> {
/// Construct a [`KeychainTxOutIndex`] with the given `lookahead`.
///
/// The `lookahead` is the number of script pubkeys to derive and cache from the internal
/// descriptors over and above the last revealed script index. Without a lookahead the index
/// will miss outputs you own when processing transactions whose output script pubkeys lie
/// beyond the last revealed index. In certain situations, such as when performing an initial
/// scan of the blockchain during wallet import, it may be uncertain or unknown what the index
/// of the last revealed script pubkey actually is.
///
/// Refer to [struct-level docs](KeychainTxOutIndex) for more about `lookahead`.
pub fn new(lookahead: u32) -> Self {
Self {
inner: SpkTxOutIndex::default(),
keychain_to_descriptor_id: Default::default(),
descriptors: Default::default(),
descriptor_id_to_keychain: Default::default(),
last_revealed: Default::default(),
lookahead,
}
}
}
/// Methods that are *re-exposed* from the internal [`SpkTxOutIndex`].
impl<K: Clone + Ord + Debug> KeychainTxOutIndex<K> {
/// Return a reference to the internal [`SpkTxOutIndex`].
///
/// **WARNING**: The internal index will contain lookahead spks. Refer to
/// [struct-level docs](KeychainTxOutIndex) for more about `lookahead`.
pub fn inner(&self) -> &SpkTxOutIndex<(K, u32)> {
&self.inner
}
/// Get the set of indexed outpoints, corresponding to tracked keychains.
pub fn outpoints(&self) -> &BTreeSet<KeychainIndexed<K, OutPoint>> {
self.inner.outpoints()
}
/// Iterate over known txouts that spend to tracked script pubkeys.
pub fn txouts(
&self,
) -> impl DoubleEndedIterator<Item = KeychainIndexed<K, (OutPoint, &TxOut)>> + ExactSizeIterator
{
self.inner
.txouts()
.map(|(index, op, txout)| (index.clone(), (op, txout)))
}
/// Finds all txouts on a transaction that has previously been scanned and indexed.
pub fn txouts_in_tx(
&self,
txid: Txid,
) -> impl DoubleEndedIterator<Item = KeychainIndexed<K, (OutPoint, &TxOut)>> {
self.inner
.txouts_in_tx(txid)
.map(|(index, op, txout)| (index.clone(), (op, txout)))
}
/// Return the [`TxOut`] of `outpoint` if it has been indexed, and if it corresponds to a
/// tracked keychain.
///
/// The associated keychain and keychain index of the txout's spk is also returned.
///
/// This calls [`SpkTxOutIndex::txout`] internally.
pub fn txout(&self, outpoint: OutPoint) -> Option<KeychainIndexed<K, &TxOut>> {
self.inner
.txout(outpoint)
.map(|(index, txout)| (index.clone(), txout))
}
/// Return the script that exists under the given `keychain`'s `index`.
///
/// This calls [`SpkTxOutIndex::spk_at_index`] internally.
pub fn spk_at_index(&self, keychain: K, index: u32) -> Option<ScriptBuf> {
self.inner.spk_at_index(&(keychain.clone(), index))
}
/// Returns the keychain and keychain index associated with the spk.
///
/// This calls [`SpkTxOutIndex::index_of_spk`] internally.
pub fn index_of_spk(&self, script: ScriptBuf) -> Option<&(K, u32)> {
self.inner.index_of_spk(script)
}
/// Returns whether the spk under the `keychain`'s `index` has been used.
///
/// Here, "unused" means that after the script pubkey was stored in the index, the index has
/// never scanned a transaction output with it.
///
/// This calls [`SpkTxOutIndex::is_used`] internally.
pub fn is_used(&self, keychain: K, index: u32) -> bool {
self.inner.is_used(&(keychain, index))
}
/// Marks the script pubkey at `index` as used even though the tracker hasn't seen an output
/// with it.
///
/// This only has an effect when the `index` had been added to `self` already and was unused.
///
/// Returns whether the spk under the given `keychain` and `index` is successfully
/// marked as used. Returns false either when there is no descriptor under the given
/// keychain, or when the spk is already marked as used.
///
/// This is useful when you want to reserve a script pubkey for something but don't want to add
/// the transaction output using it to the index yet. Other callers will consider `index` on
/// `keychain` used until you call [`unmark_used`].
///
/// This calls [`SpkTxOutIndex::mark_used`] internally.
///
/// [`unmark_used`]: Self::unmark_used
pub fn mark_used(&mut self, keychain: K, index: u32) -> bool {
self.inner.mark_used(&(keychain, index))
}
/// Undoes the effect of [`mark_used`]. Returns whether the `index` is inserted back into
/// `unused`.
///
/// Note that if `self` has scanned an output with this script pubkey, then this will have no
/// effect.
///
/// This calls [`SpkTxOutIndex::unmark_used`] internally.
///
/// [`mark_used`]: Self::mark_used
pub fn unmark_used(&mut self, keychain: K, index: u32) -> bool {
self.inner.unmark_used(&(keychain, index))
}
/// Computes the total value transfer effect `tx` has on the script pubkeys belonging to the
/// keychains in `range`. Value is *sent* when a script pubkey in the `range` is on an input and
/// *received* when it is on an output. For `sent` to be computed correctly, the output being
/// spent must have already been scanned by the index. Calculating received just uses the
/// [`Transaction`] outputs directly, so it will be correct even if it has not been scanned.
pub fn sent_and_received(
&self,
tx: &Transaction,
range: impl RangeBounds<K>,
) -> (Amount, Amount) {
self.inner
.sent_and_received(tx, self.map_to_inner_bounds(range))
}
/// Computes the net value that this transaction gives to the script pubkeys in the index and
/// *takes* from the transaction outputs in the index. Shorthand for calling
/// [`sent_and_received`] and subtracting sent from received.
///
/// This calls [`SpkTxOutIndex::net_value`] internally.
///
/// [`sent_and_received`]: Self::sent_and_received
pub fn net_value(&self, tx: &Transaction, range: impl RangeBounds<K>) -> SignedAmount {
self.inner.net_value(tx, self.map_to_inner_bounds(range))
}
}
impl<K: Clone + Ord + Debug> KeychainTxOutIndex<K> {
/// Return all keychains and their corresponding descriptors.
pub fn keychains(
&self,
) -> impl DoubleEndedIterator<Item = (K, &Descriptor<DescriptorPublicKey>)> + ExactSizeIterator + '_
{
self.keychain_to_descriptor_id
.iter()
.map(|(k, did)| (k.clone(), self.descriptors.get(did).expect("invariant")))
}
/// Insert a descriptor with a keychain associated to it.
///
/// Adding a descriptor means you will be able to derive new script pubkeys under it and the
/// txout index will discover transaction outputs with those script pubkeys (once they've been
/// derived and added to the index).
///
/// keychain <-> descriptor is a one-to-one mapping that cannot be changed. Attempting to do so
/// will return a [`InsertDescriptorError<K>`].
///
/// [`KeychainTxOutIndex`] will prevent you from inserting two descriptors which derive the same
/// script pubkey at index 0, but it's up to you to ensure that descriptors don't collide at
/// other indices. If they do nothing catastrophic happens at the `KeychainTxOutIndex` level
/// (one keychain just becomes the defacto owner of that spk arbitrarily) but this may have
/// subtle implications up the application stack like one UTXO being missing from one keychain
/// because it has been assigned to another which produces the same script pubkey.
pub fn insert_descriptor(
&mut self,
keychain: K,
descriptor: Descriptor<DescriptorPublicKey>,
) -> Result<bool, InsertDescriptorError<K>> {
let did = descriptor.descriptor_id();
if !self.keychain_to_descriptor_id.contains_key(&keychain)
&& !self.descriptor_id_to_keychain.contains_key(&did)
{
self.descriptors.insert(did, descriptor.clone());
self.keychain_to_descriptor_id.insert(keychain.clone(), did);
self.descriptor_id_to_keychain.insert(did, keychain.clone());
self.replenish_inner_index(did, &keychain, self.lookahead);
return Ok(true);
}
if let Some(existing_desc_id) = self.keychain_to_descriptor_id.get(&keychain) {
let descriptor = self.descriptors.get(existing_desc_id).expect("invariant");
if *existing_desc_id != did {
return Err(InsertDescriptorError::KeychainAlreadyAssigned {
existing_assignment: descriptor.clone(),
keychain,
});
}
}
if let Some(existing_keychain) = self.descriptor_id_to_keychain.get(&did) {
let descriptor = self.descriptors.get(&did).expect("invariant").clone();
if *existing_keychain != keychain {
return Err(InsertDescriptorError::DescriptorAlreadyAssigned {
existing_assignment: existing_keychain.clone(),
descriptor,
});
}
}
Ok(false)
}
/// Gets the descriptor associated with the keychain. Returns `None` if the keychain doesn't
/// have a descriptor associated with it.
pub fn get_descriptor(&self, keychain: K) -> Option<&Descriptor<DescriptorPublicKey>> {
let did = self.keychain_to_descriptor_id.get(&keychain)?;
self.descriptors.get(did)
}
/// Get the lookahead setting.
///
/// Refer to [`new`] for more information on the `lookahead`.
///
/// [`new`]: Self::new
pub fn lookahead(&self) -> u32 {
self.lookahead
}
/// Store lookahead scripts until `target_index` (inclusive).
///
/// This does not change the global `lookahead` setting.
pub fn lookahead_to_target(&mut self, keychain: K, target_index: u32) {
if let Some((next_index, _)) = self.next_index(keychain.clone()) {
let temp_lookahead = (target_index + 1)
.checked_sub(next_index)
.filter(|&index| index > 0);
if let Some(temp_lookahead) = temp_lookahead {
self.replenish_inner_index_keychain(keychain, temp_lookahead);
}
}
}
fn replenish_inner_index_did(&mut self, did: DescriptorId, lookahead: u32) {
if let Some(keychain) = self.descriptor_id_to_keychain.get(&did).cloned() {
self.replenish_inner_index(did, &keychain, lookahead);
}
}
fn replenish_inner_index_keychain(&mut self, keychain: K, lookahead: u32) {
if let Some(did) = self.keychain_to_descriptor_id.get(&keychain) {
self.replenish_inner_index(*did, &keychain, lookahead);
}
}
/// Syncs the state of the inner spk index after changes to a keychain
fn replenish_inner_index(&mut self, did: DescriptorId, keychain: &K, lookahead: u32) {
let descriptor = self.descriptors.get(&did).expect("invariant");
let next_store_index = self
.inner
.all_spks()
.range(&(keychain.clone(), u32::MIN)..=&(keychain.clone(), u32::MAX))
.last()
.map_or(0, |((_, index), _)| *index + 1);
let next_reveal_index = self.last_revealed.get(&did).map_or(0, |v| *v + 1);
for (new_index, new_spk) in
SpkIterator::new_with_range(descriptor, next_store_index..next_reveal_index + lookahead)
{
let _inserted = self
.inner
.insert_spk((keychain.clone(), new_index), new_spk);
debug_assert!(_inserted, "replenish lookahead: must not have existing spk: keychain={:?}, lookahead={}, next_store_index={}, next_reveal_index={}", keychain, lookahead, next_store_index, next_reveal_index);
}
}
/// Get an unbounded spk iterator over a given `keychain`. Returns `None` if the provided
/// keychain doesn't exist
pub fn unbounded_spk_iter(
&self,
keychain: K,
) -> Option<SpkIterator<Descriptor<DescriptorPublicKey>>> {
let descriptor = self.get_descriptor(keychain)?.clone();
Some(SpkIterator::new(descriptor))
}
/// Get unbounded spk iterators for all keychains.
pub fn all_unbounded_spk_iters(
&self,
) -> BTreeMap<K, SpkIterator<Descriptor<DescriptorPublicKey>>> {
self.keychain_to_descriptor_id
.iter()
.map(|(k, did)| {
(
k.clone(),
SpkIterator::new(self.descriptors.get(did).expect("invariant").clone()),
)
})
.collect()
}
/// Iterate over revealed spks of keychains in `range`
pub fn revealed_spks(
&self,
range: impl RangeBounds<K>,
) -> impl Iterator<Item = KeychainIndexed<K, ScriptBuf>> + '_ {
let start = range.start_bound();
let end = range.end_bound();
let mut iter_last_revealed = self
.keychain_to_descriptor_id
.range((start, end))
.map(|(k, did)| (k, self.last_revealed.get(did).cloned()));
let mut iter_spks = self
.inner
.all_spks()
.range(self.map_to_inner_bounds((start, end)));
let mut current_keychain = iter_last_revealed.next();
// The reason we need a tricky algorithm is because of the "lookahead" feature which means
// that some of the spks in the SpkTxoutIndex will not have been revealed yet. So we need to
// filter out those spks that are above the last_revealed for that keychain. To do this we
// iterate through the last_revealed for each keychain and the spks for each keychain in
// tandem. This minimizes BTreeMap queries.
core::iter::from_fn(move || loop {
let ((keychain, index), spk) = iter_spks.next()?;
// We need to find the last revealed that matches the current spk we are considering so
// we skip ahead.
while current_keychain?.0 < keychain {
current_keychain = iter_last_revealed.next();
}
let (current_keychain, last_revealed) = current_keychain?;
if current_keychain == keychain && Some(*index) <= last_revealed {
break Some(((keychain.clone(), *index), spk.clone()));
}
})
}
/// Iterate over revealed spks of the given `keychain` with ascending indices.
///
/// This is a double ended iterator so you can easily reverse it to get an iterator where
/// the script pubkeys that were most recently revealed are first.
pub fn revealed_keychain_spks(
&self,
keychain: K,
) -> impl DoubleEndedIterator<Item = Indexed<ScriptBuf>> + '_ {
let end = self
.last_revealed_index(keychain.clone())
.map(|v| v + 1)
.unwrap_or(0);
self.inner
.all_spks()
.range((keychain.clone(), 0)..(keychain.clone(), end))
.map(|((_, index), spk)| (*index, spk.clone()))
}
/// Iterate over revealed, but unused, spks of all keychains.
pub fn unused_spks(
&self,
) -> impl DoubleEndedIterator<Item = KeychainIndexed<K, ScriptBuf>> + Clone + '_ {
self.keychain_to_descriptor_id.keys().flat_map(|keychain| {
self.unused_keychain_spks(keychain.clone())
.map(|(i, spk)| ((keychain.clone(), i), spk.clone()))
})
}
/// Iterate over revealed, but unused, spks of the given `keychain`.
/// Returns an empty iterator if the provided keychain doesn't exist.
pub fn unused_keychain_spks(
&self,
keychain: K,
) -> impl DoubleEndedIterator<Item = Indexed<ScriptBuf>> + Clone + '_ {
let end = match self.keychain_to_descriptor_id.get(&keychain) {
Some(did) => self.last_revealed.get(did).map(|v| *v + 1).unwrap_or(0),
None => 0,
};
self.inner
.unused_spks((keychain.clone(), 0)..(keychain.clone(), end))
.map(|((_, i), spk)| (*i, spk))
}
/// Get the next derivation index for `keychain`. The next index is the index after the last revealed
/// derivation index.
///
/// The second field in the returned tuple represents whether the next derivation index is new.
/// There are two scenarios where the next derivation index is reused (not new):
///
/// 1. The keychain's descriptor has no wildcard, and a script has already been revealed.
/// 2. The number of revealed scripts has already reached 2^31 (refer to BIP-32).
///
/// Not checking the second field of the tuple may result in address reuse.
///
/// Returns None if the provided `keychain` doesn't exist.
pub fn next_index(&self, keychain: K) -> Option<(u32, bool)> {
let did = self.keychain_to_descriptor_id.get(&keychain)?;
let last_index = self.last_revealed.get(did).cloned();
let descriptor = self.descriptors.get(did).expect("invariant");
// we can only get the next index if the wildcard exists.
let has_wildcard = descriptor.has_wildcard();
Some(match last_index {
// if there is no index, next_index is always 0.
None => (0, true),
// descriptors without wildcards can only have one index.
Some(_) if !has_wildcard => (0, false),
// derivation index must be < 2^31 (BIP-32).
Some(index) if index > BIP32_MAX_INDEX => {
unreachable!("index is out of bounds")
}
Some(index) if index == BIP32_MAX_INDEX => (index, false),
// get the next derivation index.
Some(index) => (index + 1, true),
})
}
/// Get the last derivation index that is revealed for each keychain.
///
/// Keychains with no revealed indices will not be included in the returned [`BTreeMap`].
pub fn last_revealed_indices(&self) -> BTreeMap<K, u32> {
self.last_revealed
.iter()
.filter_map(|(desc_id, index)| {
let keychain = self.descriptor_id_to_keychain.get(desc_id)?;
Some((keychain.clone(), *index))
})
.collect()
}
/// Get the last derivation index revealed for `keychain`. Returns None if the keychain doesn't
/// exist, or if the keychain doesn't have any revealed scripts.
pub fn last_revealed_index(&self, keychain: K) -> Option<u32> {
let descriptor_id = self.keychain_to_descriptor_id.get(&keychain)?;
self.last_revealed.get(descriptor_id).cloned()
}
/// Convenience method to call [`Self::reveal_to_target`] on multiple keychains.
pub fn reveal_to_target_multi(&mut self, keychains: &BTreeMap<K, u32>) -> ChangeSet {
let mut changeset = ChangeSet::default();
for (keychain, &index) in keychains {
if let Some((_, new_changeset)) = self.reveal_to_target(keychain.clone(), index) {
changeset.merge(new_changeset);
}
}
changeset
}
/// Reveals script pubkeys of the `keychain`'s descriptor **up to and including** the
/// `target_index`.
///
/// If the `target_index` cannot be reached (due to the descriptor having no wildcard and/or
/// the `target_index` is in the hardened index range), this method will make a best-effort and
/// reveal up to the last possible index.
///
/// This returns list of newly revealed indices (alongside their scripts) and a
/// [`ChangeSet`], which reports updates to the latest revealed index. If no new script
/// pubkeys are revealed, then both of these will be empty.
///
/// Returns None if the provided `keychain` doesn't exist.
#[must_use]
pub fn reveal_to_target(
&mut self,
keychain: K,
target_index: u32,
) -> Option<(Vec<Indexed<ScriptBuf>>, ChangeSet)> {
let mut changeset = ChangeSet::default();
let mut spks: Vec<Indexed<ScriptBuf>> = vec![];
while let Some((i, new)) = self.next_index(keychain.clone()) {
if !new || i > target_index {
break;
}
match self.reveal_next_spk(keychain.clone()) {
Some(((i, spk), change)) => {
spks.push((i, spk));
changeset.merge(change);
}
None => break,
}
}
Some((spks, changeset))
}
/// Attempts to reveal the next script pubkey for `keychain`.
///
/// Returns the derivation index of the revealed script pubkey, the revealed script pubkey and a
/// [`ChangeSet`] which represents changes in the last revealed index (if any).
/// Returns None if the provided keychain doesn't exist.
///
/// When a new script cannot be revealed, we return the last revealed script and an empty
/// [`ChangeSet`]. There are two scenarios when a new script pubkey cannot be derived:
///
/// 1. The descriptor has no wildcard and already has one script revealed.
/// 2. The descriptor has already revealed scripts up to the numeric bound.
/// 3. There is no descriptor associated with the given keychain.
pub fn reveal_next_spk(&mut self, keychain: K) -> Option<(Indexed<ScriptBuf>, ChangeSet)> {
let (next_index, new) = self.next_index(keychain.clone())?;
let mut changeset = ChangeSet::default();
if new {
let did = self.keychain_to_descriptor_id.get(&keychain)?;
self.last_revealed.insert(*did, next_index);
changeset.last_revealed.insert(*did, next_index);
self.replenish_inner_index(*did, &keychain, self.lookahead);
}
let script = self
.inner
.spk_at_index(&(keychain.clone(), next_index))
.expect("we just inserted it");
Some(((next_index, script), changeset))
}
/// Gets the next unused script pubkey in the keychain. I.e., the script pubkey with the lowest
/// index that has not been used yet.
///
/// This will derive and reveal a new script pubkey if no more unused script pubkeys exist.
///
/// If the descriptor has no wildcard and already has a used script pubkey or if a descriptor
/// has used all scripts up to the derivation bounds, then the last derived script pubkey will be
/// returned.
///
/// Returns `None` if there are no script pubkeys that have been used and no new script pubkey
/// could be revealed (see [`reveal_next_spk`] for when this happens).
///
/// [`reveal_next_spk`]: Self::reveal_next_spk
pub fn next_unused_spk(&mut self, keychain: K) -> Option<(Indexed<ScriptBuf>, ChangeSet)> {
let next_unused = self
.unused_keychain_spks(keychain.clone())
.next()
.map(|(i, spk)| ((i, spk.to_owned()), ChangeSet::default()));
next_unused.or_else(|| self.reveal_next_spk(keychain))
}
/// Iterate over all [`OutPoint`]s that have `TxOut`s with script pubkeys derived from
/// `keychain`.
pub fn keychain_outpoints(
&self,
keychain: K,
) -> impl DoubleEndedIterator<Item = Indexed<OutPoint>> + '_ {
self.keychain_outpoints_in_range(keychain.clone()..=keychain)
.map(|((_, i), op)| (i, op))
}
/// Iterate over [`OutPoint`]s that have script pubkeys derived from keychains in `range`.
pub fn keychain_outpoints_in_range<'a>(
&'a self,
range: impl RangeBounds<K> + 'a,
) -> impl DoubleEndedIterator<Item = KeychainIndexed<K, OutPoint>> + 'a {
self.inner
.outputs_in_range(self.map_to_inner_bounds(range))
.map(|((k, i), op)| ((k.clone(), *i), op))
}
fn map_to_inner_bounds(&self, bound: impl RangeBounds<K>) -> impl RangeBounds<(K, u32)> {
let start = match bound.start_bound() {
Bound::Included(keychain) => Bound::Included((keychain.clone(), u32::MIN)),
Bound::Excluded(keychain) => Bound::Excluded((keychain.clone(), u32::MAX)),
Bound::Unbounded => Bound::Unbounded,
};
let end = match bound.end_bound() {
Bound::Included(keychain) => Bound::Included((keychain.clone(), u32::MAX)),
Bound::Excluded(keychain) => Bound::Excluded((keychain.clone(), u32::MIN)),
Bound::Unbounded => Bound::Unbounded,
};
(start, end)
}
/// Returns the highest derivation index of the `keychain` where [`KeychainTxOutIndex`] has
/// found a [`TxOut`] with it's script pubkey.
pub fn last_used_index(&self, keychain: K) -> Option<u32> {
self.keychain_outpoints(keychain).last().map(|(i, _)| i)
}
/// Returns the highest derivation index of each keychain that [`KeychainTxOutIndex`] has found
/// a [`TxOut`] with it's script pubkey.
pub fn last_used_indices(&self) -> BTreeMap<K, u32> {
self.keychain_to_descriptor_id
.iter()
.filter_map(|(keychain, _)| {
self.last_used_index(keychain.clone())
.map(|index| (keychain.clone(), index))
})
.collect()
}
/// Applies the `ChangeSet<K>` to the [`KeychainTxOutIndex<K>`]
pub fn apply_changeset(&mut self, changeset: ChangeSet) {
for (&desc_id, &index) in &changeset.last_revealed {
let v = self.last_revealed.entry(desc_id).or_default();
*v = index.max(*v);
self.replenish_inner_index_did(desc_id, self.lookahead);
}
}
}
#[derive(Clone, Debug, PartialEq)]
/// Error returned from [`KeychainTxOutIndex::insert_descriptor`]
pub enum InsertDescriptorError<K> {
/// The descriptor has already been assigned to a keychain so you can't assign it to another
DescriptorAlreadyAssigned {
/// The descriptor you have attempted to reassign
descriptor: Descriptor<DescriptorPublicKey>,
/// The keychain that the descriptor is already assigned to
existing_assignment: K,
},
/// The keychain is already assigned to a descriptor so you can't reassign it
KeychainAlreadyAssigned {
/// The keychain that you have attempted to reassign
keychain: K,
/// The descriptor that the keychain is already assigned to
existing_assignment: Descriptor<DescriptorPublicKey>,
},
}
impl<K: core::fmt::Debug> core::fmt::Display for InsertDescriptorError<K> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
InsertDescriptorError::DescriptorAlreadyAssigned {
existing_assignment: existing,
descriptor,
} => {
write!(
f,
"attempt to re-assign descriptor {descriptor:?} already assigned to {existing:?}"
)
}
InsertDescriptorError::KeychainAlreadyAssigned {
existing_assignment: existing,
keychain,
} => {
write!(
f,
"attempt to re-assign keychain {keychain:?} already assigned to {existing:?}"
)
}
}
}
}
#[cfg(feature = "std")]
impl<K: core::fmt::Debug> std::error::Error for InsertDescriptorError<K> {}
/// Represents updates to the derivation index of a [`KeychainTxOutIndex`].
/// It maps each keychain `K` to a descriptor and its last revealed index.
///
/// It can be applied to [`KeychainTxOutIndex`] with [`apply_changeset`].
///
/// The `last_revealed` field is monotone in that [`merge`] will never decrease it.
/// `keychains_added` is *not* monotone, once it is set any attempt to change it is subject to the
/// same *one-to-one* keychain <-> descriptor mapping invariant as [`KeychainTxOutIndex`] itself.
///
/// [`KeychainTxOutIndex`]: crate::keychain_txout::KeychainTxOutIndex
/// [`apply_changeset`]: crate::keychain_txout::KeychainTxOutIndex::apply_changeset
/// [`merge`]: Self::merge
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate")
)]
#[must_use]
pub struct ChangeSet {
/// Contains for each descriptor_id the last revealed index of derivation
pub last_revealed: BTreeMap<DescriptorId, u32>,
}
impl Merge for ChangeSet {
/// Merge another [`ChangeSet`] into self.
fn merge(&mut self, other: Self) {
// for `last_revealed`, entries of `other` will take precedence ONLY if it is greater than
// what was originally in `self`.
for (desc_id, index) in other.last_revealed {
use crate::collections::btree_map::Entry;
match self.last_revealed.entry(desc_id) {
Entry::Vacant(entry) => {
entry.insert(index);
}
Entry::Occupied(mut entry) => {
if *entry.get() < index {
entry.insert(index);
}
}
}
}
}
/// Returns whether the changeset are empty.
fn is_empty(&self) -> bool {
self.last_revealed.is_empty()
}
}

View File

@ -0,0 +1,337 @@
//! [`SpkTxOutIndex`] is an index storing [`TxOut`]s that have a script pubkey that matches those in a list.
use core::ops::RangeBounds;
use crate::{
collections::{hash_map::Entry, BTreeMap, BTreeSet, HashMap},
Indexer,
};
use bitcoin::{Amount, OutPoint, ScriptBuf, SignedAmount, Transaction, TxOut, Txid};
/// An index storing [`TxOut`]s that have a script pubkey that matches those in a list.
///
/// The basic idea is that you insert script pubkeys you care about into the index with
/// [`insert_spk`] and then when you call [`Indexer::index_tx`] or [`Indexer::index_txout`], the
/// index will look at any txouts you pass in and store and index any txouts matching one of its
/// script pubkeys.
///
/// Each script pubkey is associated with an application-defined index script index `I`, which must be
/// [`Ord`]. Usually, this is used to associate the derivation index of the script pubkey or even a
/// combination of `(keychain, derivation_index)`.
///
/// Note there is no harm in scanning transactions that disappear from the blockchain or were never
/// in there in the first place. `SpkTxOutIndex` is intentionally *monotone* -- you cannot delete or
/// modify txouts that have been indexed. To find out which txouts from the index are actually in the
/// chain or unspent, you must use other sources of information like a [`TxGraph`].
///
/// [`TxOut`]: bitcoin::TxOut
/// [`insert_spk`]: Self::insert_spk
/// [`Ord`]: core::cmp::Ord
/// [`TxGraph`]: crate::tx_graph::TxGraph
#[derive(Clone, Debug)]
pub struct SpkTxOutIndex<I> {
/// script pubkeys ordered by index
spks: BTreeMap<I, ScriptBuf>,
/// A reverse lookup from spk to spk index
spk_indices: HashMap<ScriptBuf, I>,
/// The set of unused indexes.
unused: BTreeSet<I>,
/// Lookup index and txout by outpoint.
txouts: BTreeMap<OutPoint, (I, TxOut)>,
/// Lookup from spk index to outpoints that had that spk
spk_txouts: BTreeSet<(I, OutPoint)>,
}
impl<I> Default for SpkTxOutIndex<I> {
fn default() -> Self {
Self {
txouts: Default::default(),
spks: Default::default(),
spk_indices: Default::default(),
spk_txouts: Default::default(),
unused: Default::default(),
}
}
}
impl<I: Clone + Ord + core::fmt::Debug> Indexer for SpkTxOutIndex<I> {
type ChangeSet = ();
fn index_txout(&mut self, outpoint: OutPoint, txout: &TxOut) -> Self::ChangeSet {
self.scan_txout(outpoint, txout);
Default::default()
}
fn index_tx(&mut self, tx: &Transaction) -> Self::ChangeSet {
self.scan(tx);
Default::default()
}
fn initial_changeset(&self) -> Self::ChangeSet {}
fn apply_changeset(&mut self, _changeset: Self::ChangeSet) {
// This applies nothing.
}
fn is_tx_relevant(&self, tx: &Transaction) -> bool {
self.is_relevant(tx)
}
}
impl<I: Clone + Ord + core::fmt::Debug> SpkTxOutIndex<I> {
/// Scans a transaction's outputs for matching script pubkeys.
///
/// Typically, this is used in two situations:
///
/// 1. After loading transaction data from the disk, you may scan over all the txouts to restore all
/// your txouts.
/// 2. When getting new data from the chain, you usually scan it before incorporating it into your chain state.
pub fn scan(&mut self, tx: &Transaction) -> BTreeSet<I> {
let mut scanned_indices = BTreeSet::new();
let txid = tx.compute_txid();
for (i, txout) in tx.output.iter().enumerate() {
let op = OutPoint::new(txid, i as u32);
if let Some(spk_i) = self.scan_txout(op, txout) {
scanned_indices.insert(spk_i.clone());
}
}
scanned_indices
}
/// Scan a single `TxOut` for a matching script pubkey and returns the index that matches the
/// script pubkey (if any).
pub fn scan_txout(&mut self, op: OutPoint, txout: &TxOut) -> Option<&I> {
let spk_i = self.spk_indices.get(&txout.script_pubkey);
if let Some(spk_i) = spk_i {
self.txouts.insert(op, (spk_i.clone(), txout.clone()));
self.spk_txouts.insert((spk_i.clone(), op));
self.unused.remove(spk_i);
}
spk_i
}
/// Get a reference to the set of indexed outpoints.
pub fn outpoints(&self) -> &BTreeSet<(I, OutPoint)> {
&self.spk_txouts
}
/// Iterate over all known txouts that spend to tracked script pubkeys.
pub fn txouts(
&self,
) -> impl DoubleEndedIterator<Item = (&I, OutPoint, &TxOut)> + ExactSizeIterator {
self.txouts
.iter()
.map(|(op, (index, txout))| (index, *op, txout))
}
/// Finds all txouts on a transaction that has previously been scanned and indexed.
pub fn txouts_in_tx(
&self,
txid: Txid,
) -> impl DoubleEndedIterator<Item = (&I, OutPoint, &TxOut)> {
self.txouts
.range(OutPoint::new(txid, u32::MIN)..=OutPoint::new(txid, u32::MAX))
.map(|(op, (index, txout))| (index, *op, txout))
}
/// Iterates over all the outputs with script pubkeys in an index range.
pub fn outputs_in_range(
&self,
range: impl RangeBounds<I>,
) -> impl DoubleEndedIterator<Item = (&I, OutPoint)> {
use bitcoin::hashes::Hash;
use core::ops::Bound::*;
let min_op = OutPoint {
txid: Txid::all_zeros(),
vout: u32::MIN,
};
let max_op = OutPoint {
txid: Txid::from_byte_array([0xff; Txid::LEN]),
vout: u32::MAX,
};
let start = match range.start_bound() {
Included(index) => Included((index.clone(), min_op)),
Excluded(index) => Excluded((index.clone(), max_op)),
Unbounded => Unbounded,
};
let end = match range.end_bound() {
Included(index) => Included((index.clone(), max_op)),
Excluded(index) => Excluded((index.clone(), min_op)),
Unbounded => Unbounded,
};
self.spk_txouts.range((start, end)).map(|(i, op)| (i, *op))
}
/// Returns the txout and script pubkey index of the `TxOut` at `OutPoint`.
///
/// Returns `None` if the `TxOut` hasn't been scanned or if nothing matching was found there.
pub fn txout(&self, outpoint: OutPoint) -> Option<(&I, &TxOut)> {
self.txouts.get(&outpoint).map(|v| (&v.0, &v.1))
}
/// Returns the script that has been inserted at the `index`.
///
/// If that index hasn't been inserted yet, it will return `None`.
pub fn spk_at_index(&self, index: &I) -> Option<ScriptBuf> {
self.spks.get(index).cloned()
}
/// The script pubkeys that are being tracked by the index.
pub fn all_spks(&self) -> &BTreeMap<I, ScriptBuf> {
&self.spks
}
/// Adds a script pubkey to scan for. Returns `false` and does nothing if spk already exists in the map
///
/// the index will look for outputs spending to this spk whenever it scans new data.
pub fn insert_spk(&mut self, index: I, spk: ScriptBuf) -> bool {
match self.spk_indices.entry(spk.clone()) {
Entry::Vacant(value) => {
value.insert(index.clone());
self.spks.insert(index.clone(), spk);
self.unused.insert(index);
true
}
Entry::Occupied(_) => false,
}
}
/// Iterates over all unused script pubkeys in an index range.
///
/// Here, "unused" means that after the script pubkey was stored in the index, the index has
/// never scanned a transaction output with it.
///
/// # Example
///
/// ```rust
/// # use bdk_chain::spk_txout::SpkTxOutIndex;
///
/// // imagine our spks are indexed like (keychain, derivation_index).
/// let txout_index = SpkTxOutIndex::<(u32, u32)>::default();
/// let all_unused_spks = txout_index.unused_spks(..);
/// let change_index = 1;
/// let unused_change_spks =
/// txout_index.unused_spks((change_index, u32::MIN)..(change_index, u32::MAX));
/// ```
pub fn unused_spks<R>(
&self,
range: R,
) -> impl DoubleEndedIterator<Item = (&I, ScriptBuf)> + Clone + '_
where
R: RangeBounds<I>,
{
self.unused
.range(range)
.map(move |index| (index, self.spk_at_index(index).expect("must exist")))
}
/// Returns whether the script pubkey at `index` has been used or not.
///
/// Here, "unused" means that after the script pubkey was stored in the index, the index has
/// never scanned a transaction output with it.
pub fn is_used(&self, index: &I) -> bool {
!self.unused.contains(index)
}
/// Marks the script pubkey at `index` as used even though it hasn't seen an output spending to it.
/// This only affects when the `index` had already been added to `self` and was unused.
///
/// Returns whether the `index` was initially present as `unused`.
///
/// This is useful when you want to reserve a script pubkey for something but don't want to add
/// the transaction output using it to the index yet. Other callers will consider the `index` used
/// until you call [`unmark_used`].
///
/// [`unmark_used`]: Self::unmark_used
pub fn mark_used(&mut self, index: &I) -> bool {
self.unused.remove(index)
}
/// Undoes the effect of [`mark_used`]. Returns whether the `index` is inserted back into
/// `unused`.
///
/// Note that if `self` has scanned an output with this script pubkey then this will have no
/// effect.
///
/// [`mark_used`]: Self::mark_used
pub fn unmark_used(&mut self, index: &I) -> bool {
// we cannot set the index as unused when it does not exist
if !self.spks.contains_key(index) {
return false;
}
// we cannot set the index as unused when txouts are indexed under it
if self.outputs_in_range(index..=index).next().is_some() {
return false;
}
self.unused.insert(index.clone())
}
/// Returns the index associated with the script pubkey.
pub fn index_of_spk(&self, script: ScriptBuf) -> Option<&I> {
self.spk_indices.get(script.as_script())
}
/// Computes the total value transfer effect `tx` has on the script pubkeys in `range`. Value is
/// *sent* when a script pubkey in the `range` is on an input and *received* when it is on an
/// output. For `sent` to be computed correctly, the output being spent must have already been
/// scanned by the index. Calculating received just uses the [`Transaction`] outputs directly,
/// so it will be correct even if it has not been scanned.
pub fn sent_and_received(
&self,
tx: &Transaction,
range: impl RangeBounds<I>,
) -> (Amount, Amount) {
let mut sent = Amount::ZERO;
let mut received = Amount::ZERO;
for txin in &tx.input {
if let Some((index, txout)) = self.txout(txin.previous_output) {
if range.contains(index) {
sent += txout.value;
}
}
}
for txout in &tx.output {
if let Some(index) = self.index_of_spk(txout.script_pubkey.clone()) {
if range.contains(index) {
received += txout.value;
}
}
}
(sent, received)
}
/// Computes the net value transfer effect of `tx` on the script pubkeys in `range`. Shorthand
/// for calling [`sent_and_received`] and subtracting sent from received.
///
/// [`sent_and_received`]: Self::sent_and_received
pub fn net_value(&self, tx: &Transaction, range: impl RangeBounds<I>) -> SignedAmount {
let (sent, received) = self.sent_and_received(tx, range);
received.to_signed().expect("valid `SignedAmount`")
- sent.to_signed().expect("valid `SignedAmount`")
}
/// Whether any of the inputs of this transaction spend a txout tracked or whether any output
/// matches one of our script pubkeys.
///
/// It is easily possible to misuse this method and get false negatives by calling it before you
/// have scanned the `TxOut`s the transaction is spending. For example, if you want to filter out
/// all the transactions in a block that are irrelevant, you **must first scan all the
/// transactions in the block** and only then use this method.
pub fn is_relevant(&self, tx: &Transaction) -> bool {
let input_matches = tx
.input
.iter()
.any(|input| self.txouts.contains_key(&input.previous_output));
let output_matches = tx
.output
.iter()
.any(|output| self.spk_indices.contains_key(&output.script_pubkey));
input_matches || output_matches
}
}

128
crates/chain/src/lib.rs Normal file
View File

@ -0,0 +1,128 @@
//! This crate is a collection of core structures for [Bitcoin Dev Kit].
//!
//! The goal of this crate is to give wallets the mechanisms needed to:
//!
//! 1. Figure out what data they need to fetch.
//! 2. Process the data in a way that never leads to inconsistent states.
//! 3. Fully index that data and expose it to be consumed without friction.
//!
//! Our design goals for these mechanisms are:
//!
//! 1. Data source agnostic -- nothing in `bdk_chain` cares about where you get data from or whether
//! you do it synchronously or asynchronously. If you know a fact about the blockchain, you can just
//! tell `bdk_chain`'s APIs about it, and that information will be integrated, if it can be done
//! consistently.
//! 2. Data persistence agnostic -- `bdk_chain` does not care where you cache on-chain data, what you
//! cache or how you retrieve it from persistent storage.
//!
//! [Bitcoin Dev Kit]: https://bitcoindevkit.org/
#![no_std]
#![warn(missing_docs)]
pub use bitcoin;
mod balance;
pub use balance::*;
mod chain_data;
pub use chain_data::*;
pub mod indexed_tx_graph;
pub use indexed_tx_graph::IndexedTxGraph;
pub mod indexer;
pub use indexer::spk_txout;
pub use indexer::Indexer;
pub mod local_chain;
mod tx_data_traits;
pub mod tx_graph;
pub use tx_data_traits::*;
pub use tx_graph::TxGraph;
mod chain_oracle;
pub use chain_oracle::*;
mod persist;
pub use persist::*;
#[doc(hidden)]
pub mod example_utils;
#[cfg(feature = "miniscript")]
pub use miniscript;
#[cfg(feature = "miniscript")]
mod descriptor_ext;
#[cfg(feature = "miniscript")]
pub use descriptor_ext::{DescriptorExt, DescriptorId};
#[cfg(feature = "miniscript")]
mod spk_iter;
#[cfg(feature = "miniscript")]
pub use indexer::keychain_txout;
#[cfg(feature = "miniscript")]
pub use spk_iter::*;
#[cfg(feature = "rusqlite")]
pub mod rusqlite_impl;
pub mod spk_client;
#[allow(unused_imports)]
#[macro_use]
extern crate alloc;
#[cfg(feature = "rusqlite")]
pub extern crate rusqlite_crate as rusqlite;
#[cfg(feature = "serde")]
pub extern crate serde_crate as serde;
#[cfg(feature = "std")]
#[macro_use]
extern crate std;
#[cfg(all(not(feature = "std"), feature = "hashbrown"))]
extern crate hashbrown;
// When no-std use `alloc`'s Hash collections. This is activated by default
#[cfg(all(not(feature = "std"), not(feature = "hashbrown")))]
#[doc(hidden)]
pub mod collections {
#![allow(dead_code)]
pub type HashSet<K> = alloc::collections::BTreeSet<K>;
pub type HashMap<K, V> = alloc::collections::BTreeMap<K, V>;
pub use alloc::collections::{btree_map as hash_map, *};
}
// When we have std, use `std`'s all collections
#[cfg(all(feature = "std", not(feature = "hashbrown")))]
#[doc(hidden)]
pub mod collections {
pub use std::collections::{hash_map, *};
}
// With this special feature `hashbrown`, use `hashbrown`'s hash collections, and else from `alloc`.
#[cfg(feature = "hashbrown")]
#[doc(hidden)]
pub mod collections {
#![allow(dead_code)]
pub type HashSet<K> = hashbrown::HashSet<K>;
pub type HashMap<K, V> = hashbrown::HashMap<K, V>;
pub use alloc::collections::*;
pub use hashbrown::hash_map;
}
/// How many confirmations are needed f or a coinbase output to be spent.
pub const COINBASE_MATURITY: u32 = 100;
/// A tuple of keychain index and `T` representing the indexed value.
pub type Indexed<T> = (u32, T);
/// A tuple of keychain `K`, derivation index (`u32`) and a `T` associated with them.
pub type KeychainIndexed<K, T> = ((K, u32), T);
/// A wrapper that we use to impl remote traits for types in our crate or dependency crates.
pub struct Impl<T>(pub T);
impl<T> From<T> for Impl<T> {
fn from(value: T) -> Self {
Self(value)
}
}
impl<T> core::ops::Deref for Impl<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}

View File

@ -0,0 +1,902 @@
//! The [`LocalChain`] is a local implementation of [`ChainOracle`].
use core::convert::Infallible;
use core::ops::RangeBounds;
use crate::collections::BTreeMap;
use crate::{BlockId, ChainOracle, Merge};
use alloc::sync::Arc;
use bitcoin::block::Header;
use bitcoin::BlockHash;
/// A [`LocalChain`] checkpoint is used to find the agreement point between two chains and as a
/// transaction anchor.
///
/// Each checkpoint contains the height and hash of a block ([`BlockId`]).
///
/// Internally, checkpoints are nodes of a reference-counted linked-list. This allows the caller to
/// cheaply clone a [`CheckPoint`] without copying the whole list and to view the entire chain
/// without holding a lock on [`LocalChain`].
#[derive(Debug, Clone)]
pub struct CheckPoint(Arc<CPInner>);
/// The internal contents of [`CheckPoint`].
#[derive(Debug, Clone)]
struct CPInner {
/// Block id (hash and height).
block: BlockId,
/// Previous checkpoint (if any).
prev: Option<Arc<CPInner>>,
}
impl PartialEq for CheckPoint {
fn eq(&self, other: &Self) -> bool {
let self_cps = self.iter().map(|cp| cp.block_id());
let other_cps = other.iter().map(|cp| cp.block_id());
self_cps.eq(other_cps)
}
}
impl CheckPoint {
/// Construct a new base block at the front of a linked list.
pub fn new(block: BlockId) -> Self {
Self(Arc::new(CPInner { block, prev: None }))
}
/// Construct a checkpoint from a list of [`BlockId`]s in ascending height order.
///
/// # Errors
///
/// This method will error if any of the follow occurs:
///
/// - The `blocks` iterator is empty, in which case, the error will be `None`.
/// - The `blocks` iterator is not in ascending height order.
/// - The `blocks` iterator contains multiple [`BlockId`]s of the same height.
///
/// The error type is the last successful checkpoint constructed (if any).
pub fn from_block_ids(
block_ids: impl IntoIterator<Item = BlockId>,
) -> Result<Self, Option<Self>> {
let mut blocks = block_ids.into_iter();
let mut acc = CheckPoint::new(blocks.next().ok_or(None)?);
for id in blocks {
acc = acc.push(id).map_err(Some)?;
}
Ok(acc)
}
/// Construct a checkpoint from the given `header` and block `height`.
///
/// If `header` is of the genesis block, the checkpoint won't have a [`prev`] node. Otherwise,
/// we return a checkpoint linked with the previous block.
///
/// [`prev`]: CheckPoint::prev
pub fn from_header(header: &bitcoin::block::Header, height: u32) -> Self {
let hash = header.block_hash();
let this_block_id = BlockId { height, hash };
let prev_height = match height.checked_sub(1) {
Some(h) => h,
None => return Self::new(this_block_id),
};
let prev_block_id = BlockId {
height: prev_height,
hash: header.prev_blockhash,
};
CheckPoint::new(prev_block_id)
.push(this_block_id)
.expect("must construct checkpoint")
}
/// Puts another checkpoint onto the linked list representing the blockchain.
///
/// Returns an `Err(self)` if the block you are pushing on is not at a greater height that the one you
/// are pushing on to.
pub fn push(self, block: BlockId) -> Result<Self, Self> {
if self.height() < block.height {
Ok(Self(Arc::new(CPInner {
block,
prev: Some(self.0),
})))
} else {
Err(self)
}
}
/// Extends the checkpoint linked list by a iterator of block ids.
///
/// Returns an `Err(self)` if there is block which does not have a greater height than the
/// previous one.
pub fn extend(self, blocks: impl IntoIterator<Item = BlockId>) -> Result<Self, Self> {
let mut curr = self.clone();
for block in blocks {
curr = curr.push(block).map_err(|_| self.clone())?;
}
Ok(curr)
}
/// Get the [`BlockId`] of the checkpoint.
pub fn block_id(&self) -> BlockId {
self.0.block
}
/// Get the height of the checkpoint.
pub fn height(&self) -> u32 {
self.0.block.height
}
/// Get the block hash of the checkpoint.
pub fn hash(&self) -> BlockHash {
self.0.block.hash
}
/// Get the previous checkpoint in the chain
pub fn prev(&self) -> Option<CheckPoint> {
self.0.prev.clone().map(CheckPoint)
}
/// Iterate from this checkpoint in descending height.
pub fn iter(&self) -> CheckPointIter {
self.clone().into_iter()
}
/// Get checkpoint at `height`.
///
/// Returns `None` if checkpoint at `height` does not exist`.
pub fn get(&self, height: u32) -> Option<Self> {
self.range(height..=height).next()
}
/// Iterate checkpoints over a height range.
///
/// Note that we always iterate checkpoints in reverse height order (iteration starts at tip
/// height).
pub fn range<R>(&self, range: R) -> impl Iterator<Item = CheckPoint>
where
R: RangeBounds<u32>,
{
let start_bound = range.start_bound().cloned();
let end_bound = range.end_bound().cloned();
self.iter()
.skip_while(move |cp| match end_bound {
core::ops::Bound::Included(inc_bound) => cp.height() > inc_bound,
core::ops::Bound::Excluded(exc_bound) => cp.height() >= exc_bound,
core::ops::Bound::Unbounded => false,
})
.take_while(move |cp| match start_bound {
core::ops::Bound::Included(inc_bound) => cp.height() >= inc_bound,
core::ops::Bound::Excluded(exc_bound) => cp.height() > exc_bound,
core::ops::Bound::Unbounded => true,
})
}
/// Inserts `block_id` at its height within the chain.
///
/// The effect of `insert` depends on whether a height already exists. If it doesn't the
/// `block_id` we inserted and all pre-existing blocks higher than it will be re-inserted after
/// it. If the height already existed and has a conflicting block hash then it will be purged
/// along with all block followin it. The returned chain will have a tip of the `block_id`
/// passed in. Of course, if the `block_id` was already present then this just returns `self`.
#[must_use]
pub fn insert(self, block_id: BlockId) -> Self {
assert_ne!(block_id.height, 0, "cannot insert the genesis block");
let mut cp = self.clone();
let mut tail = vec![];
let base = loop {
if cp.height() == block_id.height {
if cp.hash() == block_id.hash {
return self;
}
// if we have a conflict we just return the inserted block because the tail is by
// implication invalid.
tail = vec![];
break cp.prev().expect("can't be called on genesis block");
}
if cp.height() < block_id.height {
break cp;
}
tail.push(cp.block_id());
cp = cp.prev().expect("will break before genesis block");
};
base.extend(core::iter::once(block_id).chain(tail.into_iter().rev()))
.expect("tail is in order")
}
/// Apply `changeset` to the checkpoint.
fn apply_changeset(mut self, changeset: &ChangeSet) -> Result<CheckPoint, MissingGenesisError> {
if let Some(start_height) = changeset.blocks.keys().next().cloned() {
// changes after point of agreement
let mut extension = BTreeMap::default();
// point of agreement
let mut base: Option<CheckPoint> = None;
for cp in self.iter() {
if cp.height() >= start_height {
extension.insert(cp.height(), cp.hash());
} else {
base = Some(cp);
break;
}
}
for (&height, &hash) in &changeset.blocks {
match hash {
Some(hash) => {
extension.insert(height, hash);
}
None => {
extension.remove(&height);
}
};
}
let new_tip = match base {
Some(base) => base
.extend(extension.into_iter().map(BlockId::from))
.expect("extension is strictly greater than base"),
None => LocalChain::from_blocks(extension)?.tip(),
};
self = new_tip;
}
Ok(self)
}
}
/// Iterates over checkpoints backwards.
pub struct CheckPointIter {
current: Option<Arc<CPInner>>,
}
impl Iterator for CheckPointIter {
type Item = CheckPoint;
fn next(&mut self) -> Option<Self::Item> {
let current = self.current.clone()?;
self.current.clone_from(&current.prev);
Some(CheckPoint(current))
}
}
impl IntoIterator for CheckPoint {
type Item = CheckPoint;
type IntoIter = CheckPointIter;
fn into_iter(self) -> Self::IntoIter {
CheckPointIter {
current: Some(self.0),
}
}
}
/// This is a local implementation of [`ChainOracle`].
#[derive(Debug, Clone, PartialEq)]
pub struct LocalChain {
tip: CheckPoint,
}
impl ChainOracle for LocalChain {
type Error = Infallible;
fn is_block_in_chain(
&self,
block: BlockId,
chain_tip: BlockId,
) -> Result<Option<bool>, Self::Error> {
let chain_tip_cp = match self.tip.get(chain_tip.height) {
// we can only determine whether `block` is in chain of `chain_tip` if `chain_tip` can
// be identified in chain
Some(cp) if cp.hash() == chain_tip.hash => cp,
_ => return Ok(None),
};
match chain_tip_cp.get(block.height) {
Some(cp) => Ok(Some(cp.hash() == block.hash)),
None => Ok(None),
}
}
fn get_chain_tip(&self) -> Result<BlockId, Self::Error> {
Ok(self.tip.block_id())
}
}
impl LocalChain {
/// Get the genesis hash.
pub fn genesis_hash(&self) -> BlockHash {
self.tip.get(0).expect("genesis must exist").hash()
}
/// Construct [`LocalChain`] from genesis `hash`.
#[must_use]
pub fn from_genesis_hash(hash: BlockHash) -> (Self, ChangeSet) {
let height = 0;
let chain = Self {
tip: CheckPoint::new(BlockId { height, hash }),
};
let changeset = chain.initial_changeset();
(chain, changeset)
}
/// Construct a [`LocalChain`] from an initial `changeset`.
pub fn from_changeset(changeset: ChangeSet) -> Result<Self, MissingGenesisError> {
let genesis_entry = changeset.blocks.get(&0).copied().flatten();
let genesis_hash = match genesis_entry {
Some(hash) => hash,
None => return Err(MissingGenesisError),
};
let (mut chain, _) = Self::from_genesis_hash(genesis_hash);
chain.apply_changeset(&changeset)?;
debug_assert!(chain._check_changeset_is_applied(&changeset));
Ok(chain)
}
/// Construct a [`LocalChain`] from a given `checkpoint` tip.
pub fn from_tip(tip: CheckPoint) -> Result<Self, MissingGenesisError> {
let genesis_cp = tip.iter().last().expect("must have at least one element");
if genesis_cp.height() != 0 {
return Err(MissingGenesisError);
}
Ok(Self { tip })
}
/// Constructs a [`LocalChain`] from a [`BTreeMap`] of height to [`BlockHash`].
///
/// The [`BTreeMap`] enforces the height order. However, the caller must ensure the blocks are
/// all of the same chain.
pub fn from_blocks(blocks: BTreeMap<u32, BlockHash>) -> Result<Self, MissingGenesisError> {
if !blocks.contains_key(&0) {
return Err(MissingGenesisError);
}
let mut tip: Option<CheckPoint> = None;
for block in &blocks {
match tip {
Some(curr) => {
tip = Some(
curr.push(BlockId::from(block))
.expect("BTreeMap is ordered"),
)
}
None => tip = Some(CheckPoint::new(BlockId::from(block))),
}
}
Ok(Self {
tip: tip.expect("already checked to have genesis"),
})
}
/// Get the highest checkpoint.
pub fn tip(&self) -> CheckPoint {
self.tip.clone()
}
/// Applies the given `update` to the chain.
///
/// The method returns [`ChangeSet`] on success. This represents the changes applied to `self`.
///
/// There must be no ambiguity about which of the existing chain's blocks are still valid and
/// which are now invalid. That is, the new chain must implicitly connect to a definite block in
/// the existing chain and invalidate the block after it (if it exists) by including a block at
/// the same height but with a different hash to explicitly exclude it as a connection point.
///
/// # Errors
///
/// An error will occur if the update does not correctly connect with `self`.
///
/// [module-level documentation]: crate::local_chain
pub fn apply_update(&mut self, update: CheckPoint) -> Result<ChangeSet, CannotConnectError> {
let (new_tip, changeset) = merge_chains(self.tip.clone(), update)?;
self.tip = new_tip;
self._check_changeset_is_applied(&changeset);
Ok(changeset)
}
/// Update the chain with a given [`Header`] at `height` which you claim is connected to a existing block in the chain.
///
/// This is useful when you have a block header that you want to record as part of the chain but
/// don't necessarily know that the `prev_blockhash` is in the chain.
///
/// This will usually insert two new [`BlockId`]s into the chain: the header's block and the
/// header's `prev_blockhash` block. `connected_to` must already be in the chain but is allowed
/// to be `prev_blockhash` (in which case only one new block id will be inserted).
/// To be successful, `connected_to` must be chosen carefully so that `LocalChain`'s [update
/// rules][`apply_update`] are satisfied.
///
/// # Errors
///
/// [`ApplyHeaderError::InconsistentBlocks`] occurs if the `connected_to` block and the
/// [`Header`] is inconsistent. For example, if the `connected_to` block is the same height as
/// `header` or `prev_blockhash`, but has a different block hash. Or if the `connected_to`
/// height is greater than the header's `height`.
///
/// [`ApplyHeaderError::CannotConnect`] occurs if the internal call to [`apply_update`] fails.
///
/// [`apply_update`]: Self::apply_update
pub fn apply_header_connected_to(
&mut self,
header: &Header,
height: u32,
connected_to: BlockId,
) -> Result<ChangeSet, ApplyHeaderError> {
let this = BlockId {
height,
hash: header.block_hash(),
};
let prev = height.checked_sub(1).map(|prev_height| BlockId {
height: prev_height,
hash: header.prev_blockhash,
});
let conn = match connected_to {
// `connected_to` can be ignored if same as `this` or `prev` (duplicate)
conn if conn == this || Some(conn) == prev => None,
// this occurs if:
// - `connected_to` height is the same as `prev`, but different hash
// - `connected_to` height is the same as `this`, but different hash
// - `connected_to` height is greater than `this` (this is not allowed)
conn if conn.height >= height.saturating_sub(1) => {
return Err(ApplyHeaderError::InconsistentBlocks)
}
conn => Some(conn),
};
let update = CheckPoint::from_block_ids([conn, prev, Some(this)].into_iter().flatten())
.expect("block ids must be in order");
self.apply_update(update)
.map_err(ApplyHeaderError::CannotConnect)
}
/// Update the chain with a given [`Header`] connecting it with the previous block.
///
/// This is a convenience method to call [`apply_header_connected_to`] with the `connected_to`
/// parameter being `height-1:prev_blockhash`. If there is no previous block (i.e. genesis), we
/// use the current block as `connected_to`.
///
/// [`apply_header_connected_to`]: LocalChain::apply_header_connected_to
pub fn apply_header(
&mut self,
header: &Header,
height: u32,
) -> Result<ChangeSet, CannotConnectError> {
let connected_to = match height.checked_sub(1) {
Some(prev_height) => BlockId {
height: prev_height,
hash: header.prev_blockhash,
},
None => BlockId {
height,
hash: header.block_hash(),
},
};
self.apply_header_connected_to(header, height, connected_to)
.map_err(|err| match err {
ApplyHeaderError::InconsistentBlocks => {
unreachable!("connected_to is derived from the block so is always consistent")
}
ApplyHeaderError::CannotConnect(err) => err,
})
}
/// Apply the given `changeset`.
pub fn apply_changeset(&mut self, changeset: &ChangeSet) -> Result<(), MissingGenesisError> {
let old_tip = self.tip.clone();
let new_tip = old_tip.apply_changeset(changeset)?;
self.tip = new_tip;
debug_assert!(self._check_changeset_is_applied(changeset));
Ok(())
}
/// Insert a [`BlockId`].
///
/// # Errors
///
/// Replacing the block hash of an existing checkpoint will result in an error.
pub fn insert_block(&mut self, block_id: BlockId) -> Result<ChangeSet, AlterCheckPointError> {
if let Some(original_cp) = self.tip.get(block_id.height) {
let original_hash = original_cp.hash();
if original_hash != block_id.hash {
return Err(AlterCheckPointError {
height: block_id.height,
original_hash,
update_hash: Some(block_id.hash),
});
}
return Ok(ChangeSet::default());
}
let mut changeset = ChangeSet::default();
changeset
.blocks
.insert(block_id.height, Some(block_id.hash));
self.apply_changeset(&changeset)
.map_err(|_| AlterCheckPointError {
height: 0,
original_hash: self.genesis_hash(),
update_hash: changeset.blocks.get(&0).cloned().flatten(),
})?;
Ok(changeset)
}
/// Removes blocks from (and inclusive of) the given `block_id`.
///
/// This will remove blocks with a height equal or greater than `block_id`, but only if
/// `block_id` exists in the chain.
///
/// # Errors
///
/// This will fail with [`MissingGenesisError`] if the caller attempts to disconnect from the
/// genesis block.
pub fn disconnect_from(&mut self, block_id: BlockId) -> Result<ChangeSet, MissingGenesisError> {
let mut remove_from = Option::<CheckPoint>::None;
let mut changeset = ChangeSet::default();
for cp in self.tip().iter() {
let cp_id = cp.block_id();
if cp_id.height < block_id.height {
break;
}
changeset.blocks.insert(cp_id.height, None);
if cp_id == block_id {
remove_from = Some(cp);
}
}
self.tip = match remove_from.map(|cp| cp.prev()) {
// The checkpoint below the earliest checkpoint to remove will be the new tip.
Some(Some(new_tip)) => new_tip,
// If there is no checkpoint below the earliest checkpoint to remove, it means the
// "earliest checkpoint to remove" is the genesis block. We disallow removing the
// genesis block.
Some(None) => return Err(MissingGenesisError),
// If there is nothing to remove, we return an empty changeset.
None => return Ok(ChangeSet::default()),
};
Ok(changeset)
}
/// Derives an initial [`ChangeSet`], meaning that it can be applied to an empty chain to
/// recover the current chain.
pub fn initial_changeset(&self) -> ChangeSet {
ChangeSet {
blocks: self
.tip
.iter()
.map(|cp| {
let block_id = cp.block_id();
(block_id.height, Some(block_id.hash))
})
.collect(),
}
}
/// Iterate over checkpoints in descending height order.
pub fn iter_checkpoints(&self) -> CheckPointIter {
CheckPointIter {
current: Some(self.tip.0.clone()),
}
}
fn _check_changeset_is_applied(&self, changeset: &ChangeSet) -> bool {
let mut curr_cp = self.tip.clone();
for (height, exp_hash) in changeset.blocks.iter().rev() {
match curr_cp.get(*height) {
Some(query_cp) => {
if query_cp.height() != *height || Some(query_cp.hash()) != *exp_hash {
return false;
}
curr_cp = query_cp;
}
None => {
if exp_hash.is_some() {
return false;
}
}
}
}
true
}
/// Get checkpoint at given `height` (if it exists).
///
/// This is a shorthand for calling [`CheckPoint::get`] on the [`tip`].
///
/// [`tip`]: LocalChain::tip
pub fn get(&self, height: u32) -> Option<CheckPoint> {
self.tip.get(height)
}
/// Iterate checkpoints over a height range.
///
/// Note that we always iterate checkpoints in reverse height order (iteration starts at tip
/// height).
///
/// This is a shorthand for calling [`CheckPoint::range`] on the [`tip`].
///
/// [`tip`]: LocalChain::tip
pub fn range<R>(&self, range: R) -> impl Iterator<Item = CheckPoint>
where
R: RangeBounds<u32>,
{
self.tip.range(range)
}
}
/// The [`ChangeSet`] represents changes to [`LocalChain`].
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate")
)]
pub struct ChangeSet {
/// Changes to the [`LocalChain`] blocks.
///
/// The key represents the block height, and the value either represents added a new [`CheckPoint`]
/// (if [`Some`]), or removing a [`CheckPoint`] (if [`None`]).
pub blocks: BTreeMap<u32, Option<BlockHash>>,
}
impl Merge for ChangeSet {
fn merge(&mut self, other: Self) {
Merge::merge(&mut self.blocks, other.blocks)
}
fn is_empty(&self) -> bool {
self.blocks.is_empty()
}
}
impl<B: IntoIterator<Item = (u32, Option<BlockHash>)>> From<B> for ChangeSet {
fn from(blocks: B) -> Self {
Self {
blocks: blocks.into_iter().collect(),
}
}
}
impl FromIterator<(u32, Option<BlockHash>)> for ChangeSet {
fn from_iter<T: IntoIterator<Item = (u32, Option<BlockHash>)>>(iter: T) -> Self {
Self {
blocks: iter.into_iter().collect(),
}
}
}
impl FromIterator<(u32, BlockHash)> for ChangeSet {
fn from_iter<T: IntoIterator<Item = (u32, BlockHash)>>(iter: T) -> Self {
Self {
blocks: iter
.into_iter()
.map(|(height, hash)| (height, Some(hash)))
.collect(),
}
}
}
/// An error which occurs when a [`LocalChain`] is constructed without a genesis checkpoint.
#[derive(Clone, Debug, PartialEq)]
pub struct MissingGenesisError;
impl core::fmt::Display for MissingGenesisError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"cannot construct `LocalChain` without a genesis checkpoint"
)
}
}
#[cfg(feature = "std")]
impl std::error::Error for MissingGenesisError {}
/// Represents a failure when trying to insert/remove a checkpoint to/from [`LocalChain`].
#[derive(Clone, Debug, PartialEq)]
pub struct AlterCheckPointError {
/// The checkpoint's height.
pub height: u32,
/// The original checkpoint's block hash which cannot be replaced/removed.
pub original_hash: BlockHash,
/// The attempted update to the `original_block` hash.
pub update_hash: Option<BlockHash>,
}
impl core::fmt::Display for AlterCheckPointError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self.update_hash {
Some(update_hash) => write!(
f,
"failed to insert block at height {}: original={} update={}",
self.height, self.original_hash, update_hash
),
None => write!(
f,
"failed to remove block at height {}: original={}",
self.height, self.original_hash
),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for AlterCheckPointError {}
/// Occurs when an update does not have a common checkpoint with the original chain.
#[derive(Clone, Debug, PartialEq)]
pub struct CannotConnectError {
/// The suggested checkpoint to include to connect the two chains.
pub try_include_height: u32,
}
impl core::fmt::Display for CannotConnectError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"introduced chain cannot connect with the original chain, try include height {}",
self.try_include_height,
)
}
}
#[cfg(feature = "std")]
impl std::error::Error for CannotConnectError {}
/// The error type for [`LocalChain::apply_header_connected_to`].
#[derive(Debug, Clone, PartialEq)]
pub enum ApplyHeaderError {
/// Occurs when `connected_to` block conflicts with either the current block or previous block.
InconsistentBlocks,
/// Occurs when the update cannot connect with the original chain.
CannotConnect(CannotConnectError),
}
impl core::fmt::Display for ApplyHeaderError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
ApplyHeaderError::InconsistentBlocks => write!(
f,
"the `connected_to` block conflicts with either the current or previous block"
),
ApplyHeaderError::CannotConnect(err) => core::fmt::Display::fmt(err, f),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ApplyHeaderError {}
/// Applies `update_tip` onto `original_tip`.
///
/// On success, a tuple is returned `(changeset, can_replace)`. If `can_replace` is true, then the
/// `update_tip` can replace the `original_tip`.
fn merge_chains(
original_tip: CheckPoint,
update_tip: CheckPoint,
) -> Result<(CheckPoint, ChangeSet), CannotConnectError> {
let mut changeset = ChangeSet::default();
let mut orig = original_tip.iter();
let mut update = update_tip.iter();
let mut curr_orig = None;
let mut curr_update = None;
let mut prev_orig: Option<CheckPoint> = None;
let mut prev_update: Option<CheckPoint> = None;
let mut point_of_agreement_found = false;
let mut prev_orig_was_invalidated = false;
let mut potentially_invalidated_heights = vec![];
// If we can, we want to return the update tip as the new tip because this allows checkpoints
// in multiple locations to keep the same `Arc` pointers when they are being updated from each
// other using this function. We can do this as long as long as the update contains every
// block's height of the original chain.
let mut is_update_height_superset_of_original = true;
// To find the difference between the new chain and the original we iterate over both of them
// from the tip backwards in tandem. We always dealing with the highest one from either chain
// first and move to the next highest. The crucial logic is applied when they have blocks at the
// same height.
loop {
if curr_orig.is_none() {
curr_orig = orig.next();
}
if curr_update.is_none() {
curr_update = update.next();
}
match (curr_orig.as_ref(), curr_update.as_ref()) {
// Update block that doesn't exist in the original chain
(o, Some(u)) if Some(u.height()) > o.map(|o| o.height()) => {
changeset.blocks.insert(u.height(), Some(u.hash()));
prev_update = curr_update.take();
}
// Original block that isn't in the update
(Some(o), u) if Some(o.height()) > u.map(|u| u.height()) => {
// this block might be gone if an earlier block gets invalidated
potentially_invalidated_heights.push(o.height());
prev_orig_was_invalidated = false;
prev_orig = curr_orig.take();
is_update_height_superset_of_original = false;
// OPTIMIZATION: we have run out of update blocks so we don't need to continue
// iterating because there's no possibility of adding anything to changeset.
if u.is_none() {
break;
}
}
(Some(o), Some(u)) => {
if o.hash() == u.hash() {
// We have found our point of agreement 🎉 -- we require that the previous (i.e.
// higher because we are iterating backwards) block in the original chain was
// invalidated (if it exists). This ensures that there is an unambiguous point of
// connection to the original chain from the update chain (i.e. we know the
// precisely which original blocks are invalid).
if !prev_orig_was_invalidated && !point_of_agreement_found {
if let (Some(prev_orig), Some(_prev_update)) = (&prev_orig, &prev_update) {
return Err(CannotConnectError {
try_include_height: prev_orig.height(),
});
}
}
point_of_agreement_found = true;
prev_orig_was_invalidated = false;
// OPTIMIZATION 2 -- if we have the same underlying pointer at this point, we
// can guarantee that no older blocks are introduced.
if Arc::as_ptr(&o.0) == Arc::as_ptr(&u.0) {
if is_update_height_superset_of_original {
return Ok((update_tip, changeset));
} else {
let new_tip =
original_tip.apply_changeset(&changeset).map_err(|_| {
CannotConnectError {
try_include_height: 0,
}
})?;
return Ok((new_tip, changeset));
}
}
} else {
// We have an invalidation height so we set the height to the updated hash and
// also purge all the original chain block hashes above this block.
changeset.blocks.insert(u.height(), Some(u.hash()));
for invalidated_height in potentially_invalidated_heights.drain(..) {
changeset.blocks.insert(invalidated_height, None);
}
prev_orig_was_invalidated = true;
}
prev_update = curr_update.take();
prev_orig = curr_orig.take();
}
(None, None) => {
break;
}
_ => {
unreachable!("compiler cannot tell that everything has been covered")
}
}
}
// When we don't have a point of agreement you can imagine it is implicitly the
// genesis block so we need to do the final connectivity check which in this case
// just means making sure the entire original chain was invalidated.
if !prev_orig_was_invalidated && !point_of_agreement_found {
if let Some(prev_orig) = prev_orig {
return Err(CannotConnectError {
try_include_height: prev_orig.height(),
});
}
}
let new_tip = original_tip
.apply_changeset(&changeset)
.map_err(|_| CannotConnectError {
try_include_height: 0,
})?;
Ok((new_tip, changeset))
}

169
crates/chain/src/persist.rs Normal file
View File

@ -0,0 +1,169 @@
use core::{
future::Future,
ops::{Deref, DerefMut},
pin::Pin,
};
use alloc::boxed::Box;
use crate::Merge;
/// Represents a type that contains staged changes.
pub trait Staged {
/// Type for staged changes.
type ChangeSet: Merge;
/// Get mutable reference of staged changes.
fn staged(&mut self) -> &mut Self::ChangeSet;
}
/// Trait that persists the type with `Db`.
///
/// Methods of this trait should not be called directly.
pub trait PersistWith<Db>: Staged + Sized {
/// Parameters for [`PersistWith::create`].
type CreateParams;
/// Parameters for [`PersistWith::load`].
type LoadParams;
/// Error type of [`PersistWith::create`].
type CreateError;
/// Error type of [`PersistWith::load`].
type LoadError;
/// Error type of [`PersistWith::persist`].
type PersistError;
/// Initialize the `Db` and create `Self`.
fn create(db: &mut Db, params: Self::CreateParams) -> Result<Self, Self::CreateError>;
/// Initialize the `Db` and load a previously-persisted `Self`.
fn load(db: &mut Db, params: Self::LoadParams) -> Result<Option<Self>, Self::LoadError>;
/// Persist changes to the `Db`.
fn persist(
db: &mut Db,
changeset: &<Self as Staged>::ChangeSet,
) -> Result<(), Self::PersistError>;
}
type FutureResult<'a, T, E> = Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>;
/// Trait that persists the type with an async `Db`.
pub trait PersistAsyncWith<Db>: Staged + Sized {
/// Parameters for [`PersistAsyncWith::create`].
type CreateParams;
/// Parameters for [`PersistAsyncWith::load`].
type LoadParams;
/// Error type of [`PersistAsyncWith::create`].
type CreateError;
/// Error type of [`PersistAsyncWith::load`].
type LoadError;
/// Error type of [`PersistAsyncWith::persist`].
type PersistError;
/// Initialize the `Db` and create `Self`.
fn create(db: &mut Db, params: Self::CreateParams) -> FutureResult<Self, Self::CreateError>;
/// Initialize the `Db` and load a previously-persisted `Self`.
fn load(db: &mut Db, params: Self::LoadParams) -> FutureResult<Option<Self>, Self::LoadError>;
/// Persist changes to the `Db`.
fn persist<'a>(
db: &'a mut Db,
changeset: &'a <Self as Staged>::ChangeSet,
) -> FutureResult<'a, (), Self::PersistError>;
}
/// Represents a persisted `T`.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Persisted<T> {
inner: T,
}
impl<T> Persisted<T> {
/// Create a new persisted `T`.
pub fn create<Db>(db: &mut Db, params: T::CreateParams) -> Result<Self, T::CreateError>
where
T: PersistWith<Db>,
{
T::create(db, params).map(|inner| Self { inner })
}
/// Create a new persisted `T` with async `Db`.
pub async fn create_async<Db>(
db: &mut Db,
params: T::CreateParams,
) -> Result<Self, T::CreateError>
where
T: PersistAsyncWith<Db>,
{
T::create(db, params).await.map(|inner| Self { inner })
}
/// Construct a persisted `T` from `Db`.
pub fn load<Db>(db: &mut Db, params: T::LoadParams) -> Result<Option<Self>, T::LoadError>
where
T: PersistWith<Db>,
{
Ok(T::load(db, params)?.map(|inner| Self { inner }))
}
/// Construct a persisted `T` from an async `Db`.
pub async fn load_async<Db>(
db: &mut Db,
params: T::LoadParams,
) -> Result<Option<Self>, T::LoadError>
where
T: PersistAsyncWith<Db>,
{
Ok(T::load(db, params).await?.map(|inner| Self { inner }))
}
/// Persist staged changes of `T` into `Db`.
///
/// If the database errors, the staged changes will not be cleared.
pub fn persist<Db>(&mut self, db: &mut Db) -> Result<bool, T::PersistError>
where
T: PersistWith<Db>,
{
let stage = T::staged(&mut self.inner);
if stage.is_empty() {
return Ok(false);
}
T::persist(db, &*stage)?;
stage.take();
Ok(true)
}
/// Persist staged changes of `T` into an async `Db`.
///
/// If the database errors, the staged changes will not be cleared.
pub async fn persist_async<'a, Db>(
&'a mut self,
db: &'a mut Db,
) -> Result<bool, T::PersistError>
where
T: PersistAsyncWith<Db>,
{
let stage = T::staged(&mut self.inner);
if stage.is_empty() {
return Ok(false);
}
T::persist(db, &*stage).await?;
stage.take();
Ok(true)
}
}
impl<T> Deref for Persisted<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> DerefMut for Persisted<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}

View File

@ -0,0 +1,530 @@
//! Module for stuff
use crate::*;
use core::str::FromStr;
use alloc::{borrow::ToOwned, boxed::Box, string::ToString, sync::Arc, vec::Vec};
use bitcoin::consensus::{Decodable, Encodable};
use rusqlite;
use rusqlite::named_params;
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use rusqlite::OptionalExtension;
use rusqlite::Transaction;
/// Table name for schemas.
pub const SCHEMAS_TABLE_NAME: &str = "bdk_schemas";
/// Initialize the schema table.
fn init_schemas_table(db_tx: &Transaction) -> rusqlite::Result<()> {
let sql = format!("CREATE TABLE IF NOT EXISTS {}( name TEXT PRIMARY KEY NOT NULL, version INTEGER NOT NULL ) STRICT", SCHEMAS_TABLE_NAME);
db_tx.execute(&sql, ())?;
Ok(())
}
/// Get schema version of `schema_name`.
fn schema_version(db_tx: &Transaction, schema_name: &str) -> rusqlite::Result<Option<u32>> {
let sql = format!(
"SELECT version FROM {} WHERE name=:name",
SCHEMAS_TABLE_NAME
);
db_tx
.query_row(&sql, named_params! { ":name": schema_name }, |row| {
row.get::<_, u32>("version")
})
.optional()
}
/// Set the `schema_version` of `schema_name`.
fn set_schema_version(
db_tx: &Transaction,
schema_name: &str,
schema_version: u32,
) -> rusqlite::Result<()> {
let sql = format!(
"REPLACE INTO {}(name, version) VALUES(:name, :version)",
SCHEMAS_TABLE_NAME,
);
db_tx.execute(
&sql,
named_params! { ":name": schema_name, ":version": schema_version },
)?;
Ok(())
}
/// Runs logic that initializes/migrates the table schemas.
pub fn migrate_schema(
db_tx: &Transaction,
schema_name: &str,
versioned_scripts: &[&[&str]],
) -> rusqlite::Result<()> {
init_schemas_table(db_tx)?;
let current_version = schema_version(db_tx, schema_name)?;
let exec_from = current_version.map_or(0_usize, |v| v as usize + 1);
let scripts_to_exec = versioned_scripts.iter().enumerate().skip(exec_from);
for (version, &script) in scripts_to_exec {
set_schema_version(db_tx, schema_name, version as u32)?;
for statement in script {
db_tx.execute(statement, ())?;
}
}
Ok(())
}
impl FromSql for Impl<bitcoin::Txid> {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
bitcoin::Txid::from_str(value.as_str()?)
.map(Self)
.map_err(from_sql_error)
}
}
impl ToSql for Impl<bitcoin::Txid> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(self.to_string().into())
}
}
impl FromSql for Impl<bitcoin::BlockHash> {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
bitcoin::BlockHash::from_str(value.as_str()?)
.map(Self)
.map_err(from_sql_error)
}
}
impl ToSql for Impl<bitcoin::BlockHash> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(self.to_string().into())
}
}
#[cfg(feature = "miniscript")]
impl FromSql for Impl<DescriptorId> {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
DescriptorId::from_str(value.as_str()?)
.map(Self)
.map_err(from_sql_error)
}
}
#[cfg(feature = "miniscript")]
impl ToSql for Impl<DescriptorId> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(self.to_string().into())
}
}
impl FromSql for Impl<bitcoin::Transaction> {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
bitcoin::Transaction::consensus_decode_from_finite_reader(&mut value.as_bytes()?)
.map(Self)
.map_err(from_sql_error)
}
}
impl ToSql for Impl<bitcoin::Transaction> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
let mut bytes = Vec::<u8>::new();
self.consensus_encode(&mut bytes).map_err(to_sql_error)?;
Ok(bytes.into())
}
}
impl FromSql for Impl<bitcoin::ScriptBuf> {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
Ok(bitcoin::Script::from_bytes(value.as_bytes()?)
.to_owned()
.into())
}
}
impl ToSql for Impl<bitcoin::ScriptBuf> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(self.as_bytes().into())
}
}
impl FromSql for Impl<bitcoin::Amount> {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
Ok(bitcoin::Amount::from_sat(value.as_i64()?.try_into().map_err(from_sql_error)?).into())
}
}
impl ToSql for Impl<bitcoin::Amount> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
let amount: i64 = self.to_sat().try_into().map_err(to_sql_error)?;
Ok(amount.into())
}
}
impl<A: Anchor + serde_crate::de::DeserializeOwned> FromSql for Impl<A> {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
serde_json::from_str(value.as_str()?)
.map(Impl)
.map_err(from_sql_error)
}
}
impl<A: Anchor + serde_crate::Serialize> ToSql for Impl<A> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
serde_json::to_string(&self.0)
.map(Into::into)
.map_err(to_sql_error)
}
}
#[cfg(feature = "miniscript")]
impl FromSql for Impl<miniscript::Descriptor<miniscript::DescriptorPublicKey>> {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
miniscript::Descriptor::from_str(value.as_str()?)
.map(Self)
.map_err(from_sql_error)
}
}
#[cfg(feature = "miniscript")]
impl ToSql for Impl<miniscript::Descriptor<miniscript::DescriptorPublicKey>> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(self.to_string().into())
}
}
impl FromSql for Impl<bitcoin::Network> {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
bitcoin::Network::from_str(value.as_str()?)
.map(Self)
.map_err(from_sql_error)
}
}
impl ToSql for Impl<bitcoin::Network> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(self.to_string().into())
}
}
fn from_sql_error<E: std::error::Error + Send + Sync + 'static>(err: E) -> FromSqlError {
FromSqlError::Other(Box::new(err))
}
fn to_sql_error<E: std::error::Error + Send + Sync + 'static>(err: E) -> rusqlite::Error {
rusqlite::Error::ToSqlConversionFailure(Box::new(err))
}
impl<A> tx_graph::ChangeSet<A>
where
A: Anchor + Clone + Ord + serde::Serialize + serde::de::DeserializeOwned,
{
/// Schema name for [`tx_graph::ChangeSet`].
pub const SCHEMA_NAME: &'static str = "bdk_txgraph";
/// Name of table that stores full transactions and `last_seen` timestamps.
pub const TXS_TABLE_NAME: &'static str = "bdk_txs";
/// Name of table that stores floating txouts.
pub const TXOUTS_TABLE_NAME: &'static str = "bdk_txouts";
/// Name of table that stores [`Anchor`]s.
pub const ANCHORS_TABLE_NAME: &'static str = "bdk_anchors";
/// Initialize sqlite tables.
fn init_sqlite_tables(db_tx: &rusqlite::Transaction) -> rusqlite::Result<()> {
let schema_v0: &[&str] = &[
// full transactions
&format!(
"CREATE TABLE {} ( \
txid TEXT PRIMARY KEY NOT NULL, \
raw_tx BLOB, \
last_seen INTEGER \
) STRICT",
Self::TXS_TABLE_NAME,
),
// floating txouts
&format!(
"CREATE TABLE {} ( \
txid TEXT NOT NULL, \
vout INTEGER NOT NULL, \
value INTEGER NOT NULL, \
script BLOB NOT NULL, \
PRIMARY KEY (txid, vout) \
) STRICT",
Self::TXOUTS_TABLE_NAME,
),
// anchors
&format!(
"CREATE TABLE {} ( \
txid TEXT NOT NULL REFERENCES {} (txid), \
block_height INTEGER NOT NULL, \
block_hash TEXT NOT NULL, \
anchor BLOB NOT NULL, \
PRIMARY KEY (txid, block_height, block_hash) \
) STRICT",
Self::ANCHORS_TABLE_NAME,
Self::TXS_TABLE_NAME,
),
];
migrate_schema(db_tx, Self::SCHEMA_NAME, &[schema_v0])
}
/// Construct a [`TxGraph`] from an sqlite database.
pub fn from_sqlite(db_tx: &rusqlite::Transaction) -> rusqlite::Result<Self> {
Self::init_sqlite_tables(db_tx)?;
let mut changeset = Self::default();
let mut statement = db_tx.prepare(&format!(
"SELECT txid, raw_tx, last_seen FROM {}",
Self::TXS_TABLE_NAME,
))?;
let row_iter = statement.query_map([], |row| {
Ok((
row.get::<_, Impl<bitcoin::Txid>>("txid")?,
row.get::<_, Option<Impl<bitcoin::Transaction>>>("raw_tx")?,
row.get::<_, Option<u64>>("last_seen")?,
))
})?;
for row in row_iter {
let (Impl(txid), tx, last_seen) = row?;
if let Some(Impl(tx)) = tx {
changeset.txs.insert(Arc::new(tx));
}
if let Some(last_seen) = last_seen {
changeset.last_seen.insert(txid, last_seen);
}
}
let mut statement = db_tx.prepare(&format!(
"SELECT txid, vout, value, script FROM {}",
Self::TXOUTS_TABLE_NAME,
))?;
let row_iter = statement.query_map([], |row| {
Ok((
row.get::<_, Impl<bitcoin::Txid>>("txid")?,
row.get::<_, u32>("vout")?,
row.get::<_, Impl<bitcoin::Amount>>("value")?,
row.get::<_, Impl<bitcoin::ScriptBuf>>("script")?,
))
})?;
for row in row_iter {
let (Impl(txid), vout, Impl(value), Impl(script_pubkey)) = row?;
changeset.txouts.insert(
bitcoin::OutPoint { txid, vout },
bitcoin::TxOut {
value,
script_pubkey,
},
);
}
let mut statement = db_tx.prepare(&format!(
"SELECT json(anchor), txid FROM {}",
Self::ANCHORS_TABLE_NAME,
))?;
let row_iter = statement.query_map([], |row| {
Ok((
row.get::<_, Impl<A>>("json(anchor)")?,
row.get::<_, Impl<bitcoin::Txid>>("txid")?,
))
})?;
for row in row_iter {
let (Impl(anchor), Impl(txid)) = row?;
changeset.anchors.insert((anchor, txid));
}
Ok(changeset)
}
/// Persist `changeset` to the sqlite database.
pub fn persist_to_sqlite(&self, db_tx: &rusqlite::Transaction) -> rusqlite::Result<()> {
Self::init_sqlite_tables(db_tx)?;
let mut statement = db_tx.prepare_cached(&format!(
"INSERT INTO {}(txid, raw_tx) VALUES(:txid, :raw_tx) ON CONFLICT(txid) DO UPDATE SET raw_tx=:raw_tx",
Self::TXS_TABLE_NAME,
))?;
for tx in &self.txs {
statement.execute(named_params! {
":txid": Impl(tx.compute_txid()),
":raw_tx": Impl(tx.as_ref().clone()),
})?;
}
let mut statement = db_tx
.prepare_cached(&format!(
"INSERT INTO {}(txid, last_seen) VALUES(:txid, :last_seen) ON CONFLICT(txid) DO UPDATE SET last_seen=:last_seen",
Self::TXS_TABLE_NAME,
))?;
for (&txid, &last_seen) in &self.last_seen {
statement.execute(named_params! {
":txid": Impl(txid),
":last_seen": Some(last_seen),
})?;
}
let mut statement = db_tx.prepare_cached(&format!(
"REPLACE INTO {}(txid, vout, value, script) VALUES(:txid, :vout, :value, :script)",
Self::TXOUTS_TABLE_NAME,
))?;
for (op, txo) in &self.txouts {
statement.execute(named_params! {
":txid": Impl(op.txid),
":vout": op.vout,
":value": Impl(txo.value),
":script": Impl(txo.script_pubkey.clone()),
})?;
}
let mut statement = db_tx.prepare_cached(&format!(
"REPLACE INTO {}(txid, block_height, block_hash, anchor) VALUES(:txid, :block_height, :block_hash, jsonb(:anchor))",
Self::ANCHORS_TABLE_NAME,
))?;
for (anchor, txid) in &self.anchors {
let anchor_block = anchor.anchor_block();
statement.execute(named_params! {
":txid": Impl(*txid),
":block_height": anchor_block.height,
":block_hash": Impl(anchor_block.hash),
":anchor": Impl(anchor.clone()),
})?;
}
Ok(())
}
}
impl local_chain::ChangeSet {
/// Schema name for the changeset.
pub const SCHEMA_NAME: &'static str = "bdk_localchain";
/// Name of sqlite table that stores blocks of [`LocalChain`](local_chain::LocalChain).
pub const BLOCKS_TABLE_NAME: &'static str = "bdk_blocks";
/// Initialize sqlite tables for persisting [`local_chain::LocalChain`].
fn init_sqlite_tables(db_tx: &rusqlite::Transaction) -> rusqlite::Result<()> {
let schema_v0: &[&str] = &[
// blocks
&format!(
"CREATE TABLE {} ( \
block_height INTEGER PRIMARY KEY NOT NULL, \
block_hash TEXT NOT NULL \
) STRICT",
Self::BLOCKS_TABLE_NAME,
),
];
migrate_schema(db_tx, Self::SCHEMA_NAME, &[schema_v0])
}
/// Construct a [`LocalChain`](local_chain::LocalChain) from sqlite database.
pub fn from_sqlite(db_tx: &rusqlite::Transaction) -> rusqlite::Result<Self> {
Self::init_sqlite_tables(db_tx)?;
let mut changeset = Self::default();
let mut statement = db_tx.prepare(&format!(
"SELECT block_height, block_hash FROM {}",
Self::BLOCKS_TABLE_NAME,
))?;
let row_iter = statement.query_map([], |row| {
Ok((
row.get::<_, u32>("block_height")?,
row.get::<_, Impl<bitcoin::BlockHash>>("block_hash")?,
))
})?;
for row in row_iter {
let (height, Impl(hash)) = row?;
changeset.blocks.insert(height, Some(hash));
}
Ok(changeset)
}
/// Persist `changeset` to the sqlite database.
pub fn persist_to_sqlite(&self, db_tx: &rusqlite::Transaction) -> rusqlite::Result<()> {
Self::init_sqlite_tables(db_tx)?;
let mut replace_statement = db_tx.prepare_cached(&format!(
"REPLACE INTO {}(block_height, block_hash) VALUES(:block_height, :block_hash)",
Self::BLOCKS_TABLE_NAME,
))?;
let mut delete_statement = db_tx.prepare_cached(&format!(
"DELETE FROM {} WHERE block_height=:block_height",
Self::BLOCKS_TABLE_NAME,
))?;
for (&height, &hash) in &self.blocks {
match hash {
Some(hash) => replace_statement.execute(named_params! {
":block_height": height,
":block_hash": Impl(hash),
})?,
None => delete_statement.execute(named_params! {
":block_height": height,
})?,
};
}
Ok(())
}
}
#[cfg(feature = "miniscript")]
impl keychain_txout::ChangeSet {
/// Schema name for the changeset.
pub const SCHEMA_NAME: &'static str = "bdk_keychaintxout";
/// Name for table that stores last revealed indices per descriptor id.
pub const LAST_REVEALED_TABLE_NAME: &'static str = "bdk_descriptor_last_revealed";
/// Initialize sqlite tables for persisting
/// [`KeychainTxOutIndex`](keychain_txout::KeychainTxOutIndex).
fn init_sqlite_tables(db_tx: &rusqlite::Transaction) -> rusqlite::Result<()> {
let schema_v0: &[&str] = &[
// last revealed
&format!(
"CREATE TABLE {} ( \
descriptor_id TEXT PRIMARY KEY NOT NULL, \
last_revealed INTEGER NOT NULL \
) STRICT",
Self::LAST_REVEALED_TABLE_NAME,
),
];
migrate_schema(db_tx, Self::SCHEMA_NAME, &[schema_v0])
}
/// Construct [`KeychainTxOutIndex`](keychain_txout::KeychainTxOutIndex) from sqlite database
/// and given parameters.
pub fn from_sqlite(db_tx: &rusqlite::Transaction) -> rusqlite::Result<Self> {
Self::init_sqlite_tables(db_tx)?;
let mut changeset = Self::default();
let mut statement = db_tx.prepare(&format!(
"SELECT descriptor_id, last_revealed FROM {}",
Self::LAST_REVEALED_TABLE_NAME,
))?;
let row_iter = statement.query_map([], |row| {
Ok((
row.get::<_, Impl<DescriptorId>>("descriptor_id")?,
row.get::<_, u32>("last_revealed")?,
))
})?;
for row in row_iter {
let (Impl(descriptor_id), last_revealed) = row?;
changeset.last_revealed.insert(descriptor_id, last_revealed);
}
Ok(changeset)
}
/// Persist `changeset` to the sqlite database.
pub fn persist_to_sqlite(&self, db_tx: &rusqlite::Transaction) -> rusqlite::Result<()> {
Self::init_sqlite_tables(db_tx)?;
let mut statement = db_tx.prepare_cached(&format!(
"REPLACE INTO {}(descriptor_id, last_revealed) VALUES(:descriptor_id, :last_revealed)",
Self::LAST_REVEALED_TABLE_NAME,
))?;
for (&descriptor_id, &last_revealed) in &self.last_revealed {
statement.execute(named_params! {
":descriptor_id": Impl(descriptor_id),
":last_revealed": last_revealed,
})?;
}
Ok(())
}
}

View File

@ -0,0 +1,388 @@
//! Helper types for spk-based blockchain clients.
use crate::{
collections::BTreeMap, local_chain::CheckPoint, ConfirmationBlockTime, Indexed, TxGraph,
};
use alloc::boxed::Box;
use bitcoin::{OutPoint, Script, ScriptBuf, Txid};
use core::marker::PhantomData;
/// Data required to perform a spk-based blockchain client sync.
///
/// A client sync fetches relevant chain data for a known list of scripts, transaction ids and
/// outpoints. The sync process also updates the chain from the given [`CheckPoint`].
pub struct SyncRequest {
/// A checkpoint for the current chain [`LocalChain::tip`].
/// The sync process will return a new chain update that extends this tip.
///
/// [`LocalChain::tip`]: crate::local_chain::LocalChain::tip
pub chain_tip: CheckPoint,
/// Transactions that spend from or to these indexed script pubkeys.
pub spks: Box<dyn ExactSizeIterator<Item = ScriptBuf> + Send>,
/// Transactions with these txids.
pub txids: Box<dyn ExactSizeIterator<Item = Txid> + Send>,
/// Transactions with these outpoints or spent from these outpoints.
pub outpoints: Box<dyn ExactSizeIterator<Item = OutPoint> + Send>,
}
impl SyncRequest {
/// Construct a new [`SyncRequest`] from a given `cp` tip.
pub fn from_chain_tip(cp: CheckPoint) -> Self {
Self {
chain_tip: cp,
spks: Box::new(core::iter::empty()),
txids: Box::new(core::iter::empty()),
outpoints: Box::new(core::iter::empty()),
}
}
/// Set the [`Script`]s that will be synced against.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn set_spks(
mut self,
spks: impl IntoIterator<IntoIter = impl ExactSizeIterator<Item = ScriptBuf> + Send + 'static>,
) -> Self {
self.spks = Box::new(spks.into_iter());
self
}
/// Set the [`Txid`]s that will be synced against.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn set_txids(
mut self,
txids: impl IntoIterator<IntoIter = impl ExactSizeIterator<Item = Txid> + Send + 'static>,
) -> Self {
self.txids = Box::new(txids.into_iter());
self
}
/// Set the [`OutPoint`]s that will be synced against.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn set_outpoints(
mut self,
outpoints: impl IntoIterator<
IntoIter = impl ExactSizeIterator<Item = OutPoint> + Send + 'static,
>,
) -> Self {
self.outpoints = Box::new(outpoints.into_iter());
self
}
/// Chain on additional [`Script`]s that will be synced against.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn chain_spks(
mut self,
spks: impl IntoIterator<
IntoIter = impl ExactSizeIterator<Item = ScriptBuf> + Send + 'static,
Item = ScriptBuf,
>,
) -> Self {
self.spks = Box::new(ExactSizeChain::new(self.spks, spks.into_iter()));
self
}
/// Chain on additional [`Txid`]s that will be synced against.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn chain_txids(
mut self,
txids: impl IntoIterator<
IntoIter = impl ExactSizeIterator<Item = Txid> + Send + 'static,
Item = Txid,
>,
) -> Self {
self.txids = Box::new(ExactSizeChain::new(self.txids, txids.into_iter()));
self
}
/// Chain on additional [`OutPoint`]s that will be synced against.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn chain_outpoints(
mut self,
outpoints: impl IntoIterator<
IntoIter = impl ExactSizeIterator<Item = OutPoint> + Send + 'static,
Item = OutPoint,
>,
) -> Self {
self.outpoints = Box::new(ExactSizeChain::new(self.outpoints, outpoints.into_iter()));
self
}
/// Add a closure that will be called for [`Script`]s previously added to this request.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn inspect_spks(
mut self,
mut inspect: impl FnMut(&Script) + Send + Sync + 'static,
) -> Self {
self.spks = Box::new(self.spks.inspect(move |spk| inspect(spk)));
self
}
/// Add a closure that will be called for [`Txid`]s previously added to this request.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn inspect_txids(mut self, mut inspect: impl FnMut(&Txid) + Send + Sync + 'static) -> Self {
self.txids = Box::new(self.txids.inspect(move |txid| inspect(txid)));
self
}
/// Add a closure that will be called for [`OutPoint`]s previously added to this request.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn inspect_outpoints(
mut self,
mut inspect: impl FnMut(&OutPoint) + Send + Sync + 'static,
) -> Self {
self.outpoints = Box::new(self.outpoints.inspect(move |op| inspect(op)));
self
}
/// Populate the request with revealed script pubkeys from `index` with the given `spk_range`.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[cfg(feature = "miniscript")]
#[must_use]
pub fn populate_with_revealed_spks<K: Clone + Ord + core::fmt::Debug + Send + Sync>(
self,
index: &crate::indexer::keychain_txout::KeychainTxOutIndex<K>,
spk_range: impl core::ops::RangeBounds<K>,
) -> Self {
use alloc::borrow::ToOwned;
use alloc::vec::Vec;
self.chain_spks(
index
.revealed_spks(spk_range)
.map(|(_, spk)| spk.to_owned())
.collect::<Vec<_>>(),
)
}
}
/// Data returned from a spk-based blockchain client sync.
///
/// See also [`SyncRequest`].
pub struct SyncResult<A = ConfirmationBlockTime> {
/// The update to apply to the receiving [`TxGraph`].
pub graph_update: TxGraph<A>,
/// The update to apply to the receiving [`LocalChain`](crate::local_chain::LocalChain).
pub chain_update: CheckPoint,
}
/// Data required to perform a spk-based blockchain client full scan.
///
/// A client full scan iterates through all the scripts for the given keychains, fetching relevant
/// data until some stop gap number of scripts is found that have no data. This operation is
/// generally only used when importing or restoring previously used keychains in which the list of
/// used scripts is not known. The full scan process also updates the chain from the given [`CheckPoint`].
pub struct FullScanRequest<K> {
/// A checkpoint for the current [`LocalChain::tip`].
/// The full scan process will return a new chain update that extends this tip.
///
/// [`LocalChain::tip`]: crate::local_chain::LocalChain::tip
pub chain_tip: CheckPoint,
/// Iterators of script pubkeys indexed by the keychain index.
pub spks_by_keychain: BTreeMap<K, Box<dyn Iterator<Item = Indexed<ScriptBuf>> + Send>>,
}
impl<K: Ord + Clone> FullScanRequest<K> {
/// Construct a new [`FullScanRequest`] from a given `chain_tip`.
#[must_use]
pub fn from_chain_tip(chain_tip: CheckPoint) -> Self {
Self {
chain_tip,
spks_by_keychain: BTreeMap::new(),
}
}
/// Construct a new [`FullScanRequest`] from a given `chain_tip` and `index`.
///
/// Unbounded script pubkey iterators for each keychain (`K`) are extracted using
/// [`KeychainTxOutIndex::all_unbounded_spk_iters`] and is used to populate the
/// [`FullScanRequest`].
///
/// [`KeychainTxOutIndex::all_unbounded_spk_iters`]: crate::indexer::keychain_txout::KeychainTxOutIndex::all_unbounded_spk_iters
#[cfg(feature = "miniscript")]
#[must_use]
pub fn from_keychain_txout_index(
chain_tip: CheckPoint,
index: &crate::indexer::keychain_txout::KeychainTxOutIndex<K>,
) -> Self
where
K: core::fmt::Debug,
{
let mut req = Self::from_chain_tip(chain_tip);
for (keychain, spks) in index.all_unbounded_spk_iters() {
req = req.set_spks_for_keychain(keychain, spks);
}
req
}
/// Set the [`Script`]s for a given `keychain`.
///
/// This consumes the [`FullScanRequest`] and returns the updated one.
#[must_use]
pub fn set_spks_for_keychain(
mut self,
keychain: K,
spks: impl IntoIterator<IntoIter = impl Iterator<Item = Indexed<ScriptBuf>> + Send + 'static>,
) -> Self {
self.spks_by_keychain
.insert(keychain, Box::new(spks.into_iter()));
self
}
/// Chain on additional [`Script`]s that will be synced against.
///
/// This consumes the [`FullScanRequest`] and returns the updated one.
#[must_use]
pub fn chain_spks_for_keychain(
mut self,
keychain: K,
spks: impl IntoIterator<IntoIter = impl Iterator<Item = Indexed<ScriptBuf>> + Send + 'static>,
) -> Self {
match self.spks_by_keychain.remove(&keychain) {
// clippy here suggests to remove `into_iter` from `spks.into_iter()`, but doing so
// results in a compilation error
#[allow(clippy::useless_conversion)]
Some(keychain_spks) => self
.spks_by_keychain
.insert(keychain, Box::new(keychain_spks.chain(spks.into_iter()))),
None => self
.spks_by_keychain
.insert(keychain, Box::new(spks.into_iter())),
};
self
}
/// Add a closure that will be called for every [`Script`] previously added to any keychain in
/// this request.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn inspect_spks_for_all_keychains(
mut self,
inspect: impl FnMut(K, u32, &Script) + Send + Sync + Clone + 'static,
) -> Self
where
K: Send + 'static,
{
for (keychain, spks) in core::mem::take(&mut self.spks_by_keychain) {
let mut inspect = inspect.clone();
self.spks_by_keychain.insert(
keychain.clone(),
Box::new(spks.inspect(move |(i, spk)| inspect(keychain.clone(), *i, spk))),
);
}
self
}
/// Add a closure that will be called for every [`Script`] previously added to a given
/// `keychain` in this request.
///
/// This consumes the [`SyncRequest`] and returns the updated one.
#[must_use]
pub fn inspect_spks_for_keychain(
mut self,
keychain: K,
mut inspect: impl FnMut(u32, &Script) + Send + Sync + 'static,
) -> Self
where
K: Send + 'static,
{
if let Some(spks) = self.spks_by_keychain.remove(&keychain) {
self.spks_by_keychain.insert(
keychain,
Box::new(spks.inspect(move |(i, spk)| inspect(*i, spk))),
);
}
self
}
}
/// Data returned from a spk-based blockchain client full scan.
///
/// See also [`FullScanRequest`].
pub struct FullScanResult<K, A = ConfirmationBlockTime> {
/// The update to apply to the receiving [`LocalChain`](crate::local_chain::LocalChain).
pub graph_update: TxGraph<A>,
/// The update to apply to the receiving [`TxGraph`].
pub chain_update: CheckPoint,
/// Last active indices for the corresponding keychains (`K`).
pub last_active_indices: BTreeMap<K, u32>,
}
/// A version of [`core::iter::Chain`] which can combine two [`ExactSizeIterator`]s to form a new
/// [`ExactSizeIterator`].
///
/// The danger of this is explained in [the `ExactSizeIterator` docs]
/// (https://doc.rust-lang.org/core/iter/trait.ExactSizeIterator.html#when-shouldnt-an-adapter-be-exactsizeiterator).
/// This does not apply here since it would be impossible to scan an item count that overflows
/// `usize` anyway.
struct ExactSizeChain<A, B, I> {
a: Option<A>,
b: Option<B>,
i: PhantomData<I>,
}
impl<A, B, I> ExactSizeChain<A, B, I> {
fn new(a: A, b: B) -> Self {
ExactSizeChain {
a: Some(a),
b: Some(b),
i: PhantomData,
}
}
}
impl<A, B, I> Iterator for ExactSizeChain<A, B, I>
where
A: Iterator<Item = I>,
B: Iterator<Item = I>,
{
type Item = I;
fn next(&mut self) -> Option<Self::Item> {
if let Some(a) = &mut self.a {
let item = a.next();
if item.is_some() {
return item;
}
self.a = None;
}
if let Some(b) = &mut self.b {
let item = b.next();
if item.is_some() {
return item;
}
self.b = None;
}
None
}
}
impl<A, B, I> ExactSizeIterator for ExactSizeChain<A, B, I>
where
A: ExactSizeIterator<Item = I>,
B: ExactSizeIterator<Item = I>,
{
fn len(&self) -> usize {
let a_len = self.a.as_ref().map(|a| a.len()).unwrap_or(0);
let b_len = self.b.as_ref().map(|a| a.len()).unwrap_or(0);
a_len + b_len
}
}

View File

@ -0,0 +1,272 @@
use crate::{
bitcoin::{secp256k1::Secp256k1, ScriptBuf},
miniscript::{Descriptor, DescriptorPublicKey},
Indexed,
};
use core::{borrow::Borrow, ops::Bound, ops::RangeBounds};
/// Maximum [BIP32](https://bips.xyz/32) derivation index.
pub const BIP32_MAX_INDEX: u32 = (1 << 31) - 1;
/// An iterator for derived script pubkeys.
///
/// [`SpkIterator`] is an implementation of the [`Iterator`] trait which possesses its own `next()`
/// and `nth()` functions, both of which circumvent the unnecessary intermediate derivations required
/// when using their default implementations.
///
/// ## Examples
///
/// ```
/// use bdk_chain::SpkIterator;
/// # use miniscript::{Descriptor, DescriptorPublicKey};
/// # use bitcoin::{secp256k1::Secp256k1};
/// # use std::str::FromStr;
/// # let secp = bitcoin::secp256k1::Secp256k1::signing_only();
/// # let (descriptor, _) = Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, "wpkh([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/0)").unwrap();
/// # let external_spk_0 = descriptor.at_derivation_index(0).unwrap().script_pubkey();
/// # let external_spk_3 = descriptor.at_derivation_index(3).unwrap().script_pubkey();
/// # let external_spk_4 = descriptor.at_derivation_index(4).unwrap().script_pubkey();
///
/// // Creates a new script pubkey iterator starting at 0 from a descriptor.
/// let mut spk_iter = SpkIterator::new(&descriptor);
/// assert_eq!(spk_iter.next(), Some((0, external_spk_0)));
/// assert_eq!(spk_iter.next(), None);
/// ```
#[derive(Clone)]
pub struct SpkIterator<D> {
next_index: u32,
end: u32,
descriptor: D,
secp: Secp256k1<bitcoin::secp256k1::VerifyOnly>,
}
impl<D> SpkIterator<D>
where
D: Borrow<Descriptor<DescriptorPublicKey>>,
{
/// Create a new script pubkey iterator from `descriptor`.
///
/// This iterates from derivation index 0 and stops at index 0x7FFFFFFF (as specified in
/// BIP-32). Non-wildcard descriptors will only return one script pubkey at derivation index 0.
///
/// Use [`new_with_range`](SpkIterator::new_with_range) to create an iterator with a specified
/// derivation index range.
pub fn new(descriptor: D) -> Self {
SpkIterator::new_with_range(descriptor, 0..=BIP32_MAX_INDEX)
}
/// Create a new script pubkey iterator from `descriptor` and a given `range`.
///
/// Non-wildcard descriptors will only emit a single script pubkey (at derivation index 0).
/// Wildcard descriptors have an end-bound of 0x7FFFFFFF (inclusive).
///
/// Refer to [`new`](SpkIterator::new) for more.
pub fn new_with_range<R>(descriptor: D, range: R) -> Self
where
R: RangeBounds<u32>,
{
let start = match range.start_bound() {
Bound::Included(start) => *start,
Bound::Excluded(start) => *start + 1,
Bound::Unbounded => u32::MIN,
};
let mut end = match range.end_bound() {
Bound::Included(end) => *end + 1,
Bound::Excluded(end) => *end,
Bound::Unbounded => u32::MAX,
};
// Because `end` is exclusive, we want the maximum value to be BIP32_MAX_INDEX + 1.
end = end.min(BIP32_MAX_INDEX + 1);
Self {
next_index: start,
end,
descriptor,
secp: Secp256k1::verification_only(),
}
}
/// Get a reference to the internal descriptor.
pub fn descriptor(&self) -> &D {
&self.descriptor
}
}
impl<D> Iterator for SpkIterator<D>
where
D: Borrow<Descriptor<DescriptorPublicKey>>,
{
type Item = Indexed<ScriptBuf>;
fn next(&mut self) -> Option<Self::Item> {
// For non-wildcard descriptors, we expect the first element to be Some((0, spk)), then None after.
// For wildcard descriptors, we expect it to keep iterating until exhausted.
if self.next_index >= self.end {
return None;
}
// If the descriptor is non-wildcard, only index 0 will return an spk.
if !self.descriptor.borrow().has_wildcard() && self.next_index != 0 {
return None;
}
let script = self
.descriptor
.borrow()
.derived_descriptor(&self.secp, self.next_index)
.expect("the descriptor cannot need hardened derivation")
.script_pubkey();
let output = (self.next_index, script);
self.next_index += 1;
Some(output)
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.next_index = self
.next_index
.saturating_add(u32::try_from(n).unwrap_or(u32::MAX));
self.next()
}
}
#[cfg(test)]
mod test {
use crate::{
bitcoin::secp256k1::Secp256k1,
indexer::keychain_txout::KeychainTxOutIndex,
miniscript::{Descriptor, DescriptorPublicKey},
spk_iter::{SpkIterator, BIP32_MAX_INDEX},
};
#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
enum TestKeychain {
External,
Internal,
}
fn init_txout_index() -> (
KeychainTxOutIndex<TestKeychain>,
Descriptor<DescriptorPublicKey>,
Descriptor<DescriptorPublicKey>,
) {
let mut txout_index = KeychainTxOutIndex::<TestKeychain>::new(0);
let secp = Secp256k1::signing_only();
let (external_descriptor,_) = Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, "tr([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/0/*)").unwrap();
let (internal_descriptor,_) = Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, "tr([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/*)").unwrap();
let _ = txout_index
.insert_descriptor(TestKeychain::External, external_descriptor.clone())
.unwrap();
let _ = txout_index
.insert_descriptor(TestKeychain::Internal, internal_descriptor.clone())
.unwrap();
(txout_index, external_descriptor, internal_descriptor)
}
#[test]
#[allow(clippy::iter_nth_zero)]
#[rustfmt::skip]
fn test_spkiterator_wildcard() {
let (_, external_desc, _) = init_txout_index();
let external_spk_0 = external_desc.at_derivation_index(0).unwrap().script_pubkey();
let external_spk_16 = external_desc.at_derivation_index(16).unwrap().script_pubkey();
let external_spk_20 = external_desc.at_derivation_index(20).unwrap().script_pubkey();
let external_spk_21 = external_desc.at_derivation_index(21).unwrap().script_pubkey();
let external_spk_max = external_desc.at_derivation_index(BIP32_MAX_INDEX).unwrap().script_pubkey();
let mut external_spk = SpkIterator::new(&external_desc);
let max_index = BIP32_MAX_INDEX - 22;
assert_eq!(external_spk.next(), Some((0, external_spk_0)));
assert_eq!(external_spk.nth(15), Some((16, external_spk_16)));
assert_eq!(external_spk.nth(3), Some((20, external_spk_20.clone())));
assert_eq!(external_spk.next(), Some((21, external_spk_21)));
assert_eq!(
external_spk.nth(max_index as usize),
Some((BIP32_MAX_INDEX, external_spk_max))
);
assert_eq!(external_spk.nth(0), None);
let mut external_spk = SpkIterator::new_with_range(&external_desc, 0..21);
assert_eq!(external_spk.nth(20), Some((20, external_spk_20)));
assert_eq!(external_spk.next(), None);
let mut external_spk = SpkIterator::new_with_range(&external_desc, 0..21);
assert_eq!(external_spk.nth(21), None);
}
#[test]
#[allow(clippy::iter_nth_zero)]
fn test_spkiterator_non_wildcard() {
let secp = bitcoin::secp256k1::Secp256k1::signing_only();
let (no_wildcard_descriptor, _) = Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, "wpkh([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/0)").unwrap();
let external_spk_0 = no_wildcard_descriptor
.at_derivation_index(0)
.unwrap()
.script_pubkey();
let mut external_spk = SpkIterator::new(&no_wildcard_descriptor);
assert_eq!(external_spk.next(), Some((0, external_spk_0.clone())));
assert_eq!(external_spk.next(), None);
let mut external_spk = SpkIterator::new(&no_wildcard_descriptor);
assert_eq!(external_spk.nth(0), Some((0, external_spk_0.clone())));
assert_eq!(external_spk.nth(0), None);
let mut external_spk = SpkIterator::new_with_range(&no_wildcard_descriptor, 0..0);
assert_eq!(external_spk.next(), None);
let mut external_spk = SpkIterator::new_with_range(&no_wildcard_descriptor, 0..1);
assert_eq!(external_spk.nth(0), Some((0, external_spk_0.clone())));
assert_eq!(external_spk.next(), None);
// We test that using new_with_range with range_len > 1 gives back an iterator with
// range_len = 1
let mut external_spk = SpkIterator::new_with_range(&no_wildcard_descriptor, 0..10);
assert_eq!(external_spk.nth(0), Some((0, external_spk_0)));
assert_eq!(external_spk.nth(0), None);
// non index-0 should NOT return an spk
assert_eq!(
SpkIterator::new_with_range(&no_wildcard_descriptor, 1..1).next(),
None
);
assert_eq!(
SpkIterator::new_with_range(&no_wildcard_descriptor, 1..=1).next(),
None
);
assert_eq!(
SpkIterator::new_with_range(&no_wildcard_descriptor, 1..2).next(),
None
);
assert_eq!(
SpkIterator::new_with_range(&no_wildcard_descriptor, 1..=2).next(),
None
);
assert_eq!(
SpkIterator::new_with_range(&no_wildcard_descriptor, 10..11).next(),
None
);
assert_eq!(
SpkIterator::new_with_range(&no_wildcard_descriptor, 10..=10).next(),
None
);
}
}
#[test]
fn spk_iterator_is_send_and_static() {
fn is_send_and_static<A: Send + 'static>() {}
is_send_and_static::<SpkIterator<Descriptor<DescriptorPublicKey>>>()
}

View File

@ -0,0 +1,173 @@
use crate::collections::BTreeMap;
use crate::collections::BTreeSet;
use crate::BlockId;
use alloc::vec::Vec;
/// Trait that "anchors" blockchain data to a specific block of height and hash.
///
/// If transaction A is anchored in block B, and block B is in the best chain, we can
/// assume that transaction A is also confirmed in the best chain. This does not necessarily mean
/// that transaction A is confirmed in block B. It could also mean transaction A is confirmed in a
/// parent block of B.
///
/// Every [`Anchor`] implementation must contain a [`BlockId`] parameter, and must implement
/// [`Ord`]. When implementing [`Ord`], the anchors' [`BlockId`]s should take precedence
/// over other elements inside the [`Anchor`]s for comparison purposes, i.e., you should first
/// compare the anchors' [`BlockId`]s and then care about the rest.
///
/// The example shows different types of anchors:
/// ```
/// # use bdk_chain::local_chain::LocalChain;
/// # use bdk_chain::tx_graph::TxGraph;
/// # use bdk_chain::BlockId;
/// # use bdk_chain::ConfirmationBlockTime;
/// # use bdk_chain::example_utils::*;
/// # use bitcoin::hashes::Hash;
/// // Initialize the local chain with two blocks.
/// let chain = LocalChain::from_blocks(
/// [
/// (1, Hash::hash("first".as_bytes())),
/// (2, Hash::hash("second".as_bytes())),
/// ]
/// .into_iter()
/// .collect(),
/// );
///
/// // Transaction to be inserted into `TxGraph`s with different anchor types.
/// let tx = tx_from_hex(RAW_TX_1);
///
/// // Insert `tx` into a `TxGraph` that uses `BlockId` as the anchor type.
/// // When a transaction is anchored with `BlockId`, the anchor block and the confirmation block of
/// // the transaction is the same block.
/// let mut graph_a = TxGraph::<BlockId>::default();
/// let _ = graph_a.insert_tx(tx.clone());
/// graph_a.insert_anchor(
/// tx.compute_txid(),
/// BlockId {
/// height: 1,
/// hash: Hash::hash("first".as_bytes()),
/// },
/// );
///
/// // Insert `tx` into a `TxGraph` that uses `ConfirmationBlockTime` as the anchor type.
/// // This anchor records the anchor block and the confirmation time of the transaction. When a
/// // transaction is anchored with `ConfirmationBlockTime`, the anchor block and confirmation block
/// // of the transaction is the same block.
/// let mut graph_c = TxGraph::<ConfirmationBlockTime>::default();
/// let _ = graph_c.insert_tx(tx.clone());
/// graph_c.insert_anchor(
/// tx.compute_txid(),
/// ConfirmationBlockTime {
/// block_id: BlockId {
/// height: 2,
/// hash: Hash::hash("third".as_bytes()),
/// },
/// confirmation_time: 123,
/// },
/// );
/// ```
pub trait Anchor: core::fmt::Debug + Clone + Eq + PartialOrd + Ord + core::hash::Hash {
/// Returns the [`BlockId`] that the associated blockchain data is "anchored" in.
fn anchor_block(&self) -> BlockId;
/// Get the upper bound of the chain data's confirmation height.
///
/// The default definition gives a pessimistic answer. This can be overridden by the `Anchor`
/// implementation for a more accurate value.
fn confirmation_height_upper_bound(&self) -> u32 {
self.anchor_block().height
}
}
impl<'a, A: Anchor> Anchor for &'a A {
fn anchor_block(&self) -> BlockId {
<A as Anchor>::anchor_block(self)
}
}
/// An [`Anchor`] that can be constructed from a given block, block height and transaction position
/// within the block.
pub trait AnchorFromBlockPosition: Anchor {
/// Construct the anchor from a given `block`, block height and `tx_pos` within the block.
fn from_block_position(block: &bitcoin::Block, block_id: BlockId, tx_pos: usize) -> Self;
}
/// Trait that makes an object mergeable.
pub trait Merge: Default {
/// Merge another object of the same type onto `self`.
fn merge(&mut self, other: Self);
/// Returns whether the structure is considered empty.
fn is_empty(&self) -> bool;
/// Take the value, replacing it with the default value.
fn take(&mut self) -> Option<Self> {
if self.is_empty() {
None
} else {
Some(core::mem::take(self))
}
}
}
impl<K: Ord, V> Merge for BTreeMap<K, V> {
fn merge(&mut self, other: Self) {
// We use `extend` instead of `BTreeMap::append` due to performance issues with `append`.
// Refer to https://github.com/rust-lang/rust/issues/34666#issuecomment-675658420
BTreeMap::extend(self, other)
}
fn is_empty(&self) -> bool {
BTreeMap::is_empty(self)
}
}
impl<T: Ord> Merge for BTreeSet<T> {
fn merge(&mut self, other: Self) {
// We use `extend` instead of `BTreeMap::append` due to performance issues with `append`.
// Refer to https://github.com/rust-lang/rust/issues/34666#issuecomment-675658420
BTreeSet::extend(self, other)
}
fn is_empty(&self) -> bool {
BTreeSet::is_empty(self)
}
}
impl<T> Merge for Vec<T> {
fn merge(&mut self, mut other: Self) {
Vec::append(self, &mut other)
}
fn is_empty(&self) -> bool {
Vec::is_empty(self)
}
}
macro_rules! impl_merge_for_tuple {
($($a:ident $b:tt)*) => {
impl<$($a),*> Merge for ($($a,)*) where $($a: Merge),* {
fn merge(&mut self, _other: Self) {
$(Merge::merge(&mut self.$b, _other.$b) );*
}
fn is_empty(&self) -> bool {
$(Merge::is_empty(&self.$b) && )* true
}
}
}
}
impl_merge_for_tuple!();
impl_merge_for_tuple!(T0 0);
impl_merge_for_tuple!(T0 0 T1 1);
impl_merge_for_tuple!(T0 0 T1 1 T2 2);
impl_merge_for_tuple!(T0 0 T1 1 T2 2 T3 3);
impl_merge_for_tuple!(T0 0 T1 1 T2 2 T3 3 T4 4);
impl_merge_for_tuple!(T0 0 T1 1 T2 2 T3 3 T4 4 T5 5);
impl_merge_for_tuple!(T0 0 T1 1 T2 2 T3 3 T4 4 T5 5 T6 6);
impl_merge_for_tuple!(T0 0 T1 1 T2 2 T3 3 T4 4 T5 5 T6 6 T7 7);
impl_merge_for_tuple!(T0 0 T1 1 T2 2 T3 3 T4 4 T5 5 T6 6 T7 7 T8 8);
impl_merge_for_tuple!(T0 0 T1 1 T2 2 T3 3 T4 4 T5 5 T6 6 T7 7 T8 8 T9 9);
impl_merge_for_tuple!(T0 0 T1 1 T2 2 T3 3 T4 4 T5 5 T6 6 T7 7 T8 8 T9 9 T10 10);

1586
crates/chain/src/tx_graph.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,89 @@
#![cfg(feature = "miniscript")]
mod tx_template;
#[allow(unused_imports)]
pub use tx_template::*;
#[allow(unused_macros)]
macro_rules! block_id {
($height:expr, $hash:literal) => {{
bdk_chain::BlockId {
height: $height,
hash: bitcoin::hashes::Hash::hash($hash.as_bytes()),
}
}};
}
#[allow(unused_macros)]
macro_rules! h {
($index:literal) => {{
bitcoin::hashes::Hash::hash($index.as_bytes())
}};
}
#[allow(unused_macros)]
macro_rules! local_chain {
[ $(($height:expr, $block_hash:expr)), * ] => {{
#[allow(unused_mut)]
bdk_chain::local_chain::LocalChain::from_blocks([$(($height, $block_hash).into()),*].into_iter().collect())
.expect("chain must have genesis block")
}};
}
#[allow(unused_macros)]
macro_rules! chain_update {
[ $(($height:expr, $hash:expr)), * ] => {{
#[allow(unused_mut)]
bdk_chain::local_chain::LocalChain::from_blocks([$(($height, $hash).into()),*].into_iter().collect())
.expect("chain must have genesis block")
.tip()
}};
}
#[allow(unused_macros)]
macro_rules! changeset {
(checkpoints: $($tail:tt)*) => { changeset!(index: TxHeight, checkpoints: $($tail)*) };
(
index: $ind:ty,
checkpoints: [ $(( $height:expr, $cp_to:expr )),* ]
$(,txids: [ $(( $txid:expr, $tx_to:expr )),* ])?
) => {{
use bdk_chain::collections::BTreeMap;
#[allow(unused_mut)]
bdk_chain::sparse_chain::ChangeSet::<$ind> {
checkpoints: {
let mut changes = BTreeMap::default();
$(changes.insert($height, $cp_to);)*
changes
},
txids: {
let mut changes = BTreeMap::default();
$($(changes.insert($txid, $tx_to.map(|h: TxHeight| h.into()));)*)?
changes
}
}
}};
}
#[allow(unused)]
pub fn new_tx(lt: u32) -> bitcoin::Transaction {
bitcoin::Transaction {
version: bitcoin::transaction::Version::non_standard(0x00),
lock_time: bitcoin::absolute::LockTime::from_consensus(lt),
input: vec![],
output: vec![],
}
}
#[allow(unused)]
pub const DESCRIPTORS: [&str; 7] = [
"tr([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/0/*)",
"tr([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/*)",
"wpkh([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/0/*)",
"tr(tprv8ZgxMBicQKsPd3krDUsBAmtnRsK3rb8u5yi1zhQgMhF1tR8MW7xfE4rnrbbsrbPR52e7rKapu6ztw1jXveJSCGHEriUGZV7mCe88duLp5pj/86'/1'/0'/0/*)",
"tr(tprv8ZgxMBicQKsPd3krDUsBAmtnRsK3rb8u5yi1zhQgMhF1tR8MW7xfE4rnrbbsrbPR52e7rKapu6ztw1jXveJSCGHEriUGZV7mCe88duLp5pj/86'/1'/0'/1/*)",
"wpkh(xprv9s21ZrQH143K4EXURwMHuLS469fFzZyXk7UUpdKfQwhoHcAiYTakpe8pMU2RiEdvrU9McyuE7YDoKcXkoAwEGoK53WBDnKKv2zZbb9BzttX/1/0/*)",
// non-wildcard
"wpkh([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/0)",
];

View File

@ -0,0 +1,137 @@
#![cfg(feature = "miniscript")]
use rand::distributions::{Alphanumeric, DistString};
use std::collections::HashMap;
use bdk_chain::{spk_txout::SpkTxOutIndex, tx_graph::TxGraph, Anchor};
use bitcoin::{
locktime::absolute::LockTime, secp256k1::Secp256k1, transaction, Amount, OutPoint, ScriptBuf,
Sequence, Transaction, TxIn, TxOut, Txid, Witness,
};
use miniscript::Descriptor;
/// Template for creating a transaction in `TxGraph`.
///
/// The incentive for transaction templates is to create a transaction history in a simple manner to
/// avoid having to explicitly hash previous transactions to form previous outpoints of later
/// transactions.
#[derive(Clone, Copy, Default)]
pub struct TxTemplate<'a, A> {
/// Uniquely identifies the transaction, before it can have a txid.
pub tx_name: &'a str,
pub inputs: &'a [TxInTemplate<'a>],
pub outputs: &'a [TxOutTemplate],
pub anchors: &'a [A],
pub last_seen: Option<u64>,
}
#[allow(dead_code)]
pub enum TxInTemplate<'a> {
/// This will give a random txid and vout.
Bogus,
/// This is used for coinbase transactions because they do not have previous outputs.
Coinbase,
/// Contains the `tx_name` and `vout` that we are spending. The rule is that we must only spend
/// from tx of a previous `TxTemplate`.
PrevTx(&'a str, usize),
}
pub struct TxOutTemplate {
pub value: u64,
pub spk_index: Option<u32>, // some = get spk from SpkTxOutIndex, none = random spk
}
#[allow(unused)]
impl TxOutTemplate {
pub fn new(value: u64, spk_index: Option<u32>) -> Self {
TxOutTemplate { value, spk_index }
}
}
#[allow(dead_code)]
pub fn init_graph<'a, A: Anchor + Clone + 'a>(
tx_templates: impl IntoIterator<Item = &'a TxTemplate<'a, A>>,
) -> (TxGraph<A>, SpkTxOutIndex<u32>, HashMap<&'a str, Txid>) {
let (descriptor, _) =
Descriptor::parse_descriptor(&Secp256k1::signing_only(), super::DESCRIPTORS[2]).unwrap();
let mut graph = TxGraph::<A>::default();
let mut spk_index = SpkTxOutIndex::default();
(0..10).for_each(|index| {
spk_index.insert_spk(
index,
descriptor
.at_derivation_index(index)
.unwrap()
.script_pubkey(),
);
});
let mut tx_ids = HashMap::<&'a str, Txid>::new();
for (bogus_txin_vout, tx_tmp) in tx_templates.into_iter().enumerate() {
let tx = Transaction {
version: transaction::Version::non_standard(0),
lock_time: LockTime::ZERO,
input: tx_tmp
.inputs
.iter()
.map(|input| match input {
TxInTemplate::Bogus => TxIn {
previous_output: OutPoint::new(
bitcoin::hashes::Hash::hash(
Alphanumeric
.sample_string(&mut rand::thread_rng(), 20)
.as_bytes(),
),
bogus_txin_vout as u32,
),
script_sig: ScriptBuf::new(),
sequence: Sequence::default(),
witness: Witness::new(),
},
TxInTemplate::Coinbase => TxIn {
previous_output: OutPoint::null(),
script_sig: ScriptBuf::new(),
sequence: Sequence::MAX,
witness: Witness::new(),
},
TxInTemplate::PrevTx(prev_name, prev_vout) => {
let prev_txid = tx_ids.get(prev_name).expect(
"txin template must spend from tx of template that comes before",
);
TxIn {
previous_output: OutPoint::new(*prev_txid, *prev_vout as _),
script_sig: ScriptBuf::new(),
sequence: Sequence::default(),
witness: Witness::new(),
}
}
})
.collect(),
output: tx_tmp
.outputs
.iter()
.map(|output| match &output.spk_index {
None => TxOut {
value: Amount::from_sat(output.value),
script_pubkey: ScriptBuf::new(),
},
Some(index) => TxOut {
value: Amount::from_sat(output.value),
script_pubkey: spk_index.spk_at_index(index).unwrap(),
},
})
.collect(),
};
tx_ids.insert(tx_tmp.tx_name, tx.compute_txid());
spk_index.scan(&tx);
let _ = graph.insert_tx(tx.clone());
for anchor in tx_tmp.anchors.iter() {
let _ = graph.insert_anchor(tx.compute_txid(), anchor.clone());
}
let _ = graph.insert_seen_at(tx.compute_txid(), tx_tmp.last_seen.unwrap_or(0));
}
(graph, spk_index, tx_ids)
}

View File

@ -0,0 +1,660 @@
#![cfg(feature = "miniscript")]
#[macro_use]
mod common;
use std::{collections::BTreeSet, sync::Arc};
use crate::common::DESCRIPTORS;
use bdk_chain::{
indexed_tx_graph::{self, IndexedTxGraph},
indexer::keychain_txout::KeychainTxOutIndex,
local_chain::LocalChain,
tx_graph, Balance, ChainPosition, ConfirmationBlockTime, DescriptorExt,
};
use bitcoin::{secp256k1::Secp256k1, Amount, OutPoint, ScriptBuf, Transaction, TxIn, TxOut};
use miniscript::Descriptor;
/// Ensure [`IndexedTxGraph::insert_relevant_txs`] can successfully index transactions NOT presented
/// in topological order.
///
/// Given 3 transactions (A, B, C), where A has 2 owned outputs. B and C spends an output each of A.
/// Typically, we would only know whether B and C are relevant if we have indexed A (A's outpoints
/// are associated with owned spks in the index). Ensure insertion and indexing is topological-
/// agnostic.
#[test]
fn insert_relevant_txs() {
use bdk_chain::indexer::keychain_txout;
let (descriptor, _) = Descriptor::parse_descriptor(&Secp256k1::signing_only(), DESCRIPTORS[0])
.expect("must be valid");
let spk_0 = descriptor.at_derivation_index(0).unwrap().script_pubkey();
let spk_1 = descriptor.at_derivation_index(9).unwrap().script_pubkey();
let mut graph = IndexedTxGraph::<ConfirmationBlockTime, KeychainTxOutIndex<()>>::new(
KeychainTxOutIndex::new(10),
);
let _ = graph
.index
.insert_descriptor((), descriptor.clone())
.unwrap();
let tx_a = Transaction {
output: vec![
TxOut {
value: Amount::from_sat(10_000),
script_pubkey: spk_0,
},
TxOut {
value: Amount::from_sat(20_000),
script_pubkey: spk_1,
},
],
..common::new_tx(0)
};
let tx_b = Transaction {
input: vec![TxIn {
previous_output: OutPoint::new(tx_a.compute_txid(), 0),
..Default::default()
}],
..common::new_tx(1)
};
let tx_c = Transaction {
input: vec![TxIn {
previous_output: OutPoint::new(tx_a.compute_txid(), 1),
..Default::default()
}],
..common::new_tx(2)
};
let txs = [tx_c, tx_b, tx_a];
let changeset = indexed_tx_graph::ChangeSet {
tx_graph: tx_graph::ChangeSet {
txs: txs.iter().cloned().map(Arc::new).collect(),
..Default::default()
},
indexer: keychain_txout::ChangeSet {
last_revealed: [(descriptor.descriptor_id(), 9_u32)].into(),
},
};
assert_eq!(
graph.batch_insert_relevant(txs.iter().map(|tx| (tx, None))),
changeset,
);
// The initial changeset will also contain info about the keychain we added
let initial_changeset = indexed_tx_graph::ChangeSet {
tx_graph: changeset.tx_graph,
indexer: keychain_txout::ChangeSet {
last_revealed: changeset.indexer.last_revealed,
},
};
assert_eq!(graph.initial_changeset(), initial_changeset);
}
/// Ensure consistency IndexedTxGraph list_* and balance methods. These methods lists
/// relevant txouts and utxos from the information fetched from a ChainOracle (here a LocalChain).
///
/// Test Setup:
///
/// Local Chain => <0> ----- <1> ----- <2> ----- <3> ---- ... ---- <150>
///
/// Keychains:
///
/// keychain_1: Trusted
/// keychain_2: Untrusted
///
/// Transactions:
///
/// tx1: A Coinbase, sending 70000 sats to "trusted" address. [Block 0]
/// tx2: A external Receive, sending 30000 sats to "untrusted" address. [Block 1]
/// tx3: Internal Spend. Spends tx2 and returns change of 10000 to "trusted" address. [Block 2]
/// tx4: Mempool tx, sending 20000 sats to "untrusted" address.
/// tx5: Mempool tx, sending 15000 sats to "trusted" address.
/// tx6: Complete unrelated tx. [Block 3]
///
/// Different transactions are added via `insert_relevant_txs`.
/// `list_owned_txout`, `list_owned_utxos` and `balance` method is asserted
/// with expected values at Block height 0, 1, and 2.
///
/// Finally Add more blocks to local chain until tx1 coinbase maturity hits.
/// Assert maturity at coinbase maturity inflection height. Block height 98 and 99.
#[test]
fn test_list_owned_txouts() {
// Create Local chains
let local_chain = LocalChain::from_blocks((0..150).map(|i| (i as u32, h!("random"))).collect())
.expect("must have genesis hash");
// Initiate IndexedTxGraph
let (desc_1, _) =
Descriptor::parse_descriptor(&Secp256k1::signing_only(), common::DESCRIPTORS[2]).unwrap();
let (desc_2, _) =
Descriptor::parse_descriptor(&Secp256k1::signing_only(), common::DESCRIPTORS[3]).unwrap();
let mut graph = IndexedTxGraph::<ConfirmationBlockTime, KeychainTxOutIndex<String>>::new(
KeychainTxOutIndex::new(10),
);
assert!(graph
.index
.insert_descriptor("keychain_1".into(), desc_1)
.unwrap());
assert!(graph
.index
.insert_descriptor("keychain_2".into(), desc_2)
.unwrap());
// Get trusted and untrusted addresses
let mut trusted_spks: Vec<ScriptBuf> = Vec::new();
let mut untrusted_spks: Vec<ScriptBuf> = Vec::new();
{
// we need to scope here to take immutable reference of the graph
for _ in 0..10 {
let ((_, script), _) = graph
.index
.reveal_next_spk("keychain_1".to_string())
.unwrap();
// TODO Assert indexes
trusted_spks.push(script.to_owned());
}
}
{
for _ in 0..10 {
let ((_, script), _) = graph
.index
.reveal_next_spk("keychain_2".to_string())
.unwrap();
untrusted_spks.push(script.to_owned());
}
}
// Create test transactions
// tx1 is the genesis coinbase
let tx1 = Transaction {
input: vec![TxIn {
previous_output: OutPoint::null(),
..Default::default()
}],
output: vec![TxOut {
value: Amount::from_sat(70000),
script_pubkey: trusted_spks[0].to_owned(),
}],
..common::new_tx(0)
};
// tx2 is an incoming transaction received at untrusted keychain at block 1.
let tx2 = Transaction {
output: vec![TxOut {
value: Amount::from_sat(30000),
script_pubkey: untrusted_spks[0].to_owned(),
}],
..common::new_tx(0)
};
// tx3 spends tx2 and gives a change back in trusted keychain. Confirmed at Block 2.
let tx3 = Transaction {
input: vec![TxIn {
previous_output: OutPoint::new(tx2.compute_txid(), 0),
..Default::default()
}],
output: vec![TxOut {
value: Amount::from_sat(10000),
script_pubkey: trusted_spks[1].to_owned(),
}],
..common::new_tx(0)
};
// tx4 is an external transaction receiving at untrusted keychain, unconfirmed.
let tx4 = Transaction {
output: vec![TxOut {
value: Amount::from_sat(20000),
script_pubkey: untrusted_spks[1].to_owned(),
}],
..common::new_tx(0)
};
// tx5 is an external transaction receiving at trusted keychain, unconfirmed.
let tx5 = Transaction {
output: vec![TxOut {
value: Amount::from_sat(15000),
script_pubkey: trusted_spks[2].to_owned(),
}],
..common::new_tx(0)
};
// tx6 is an unrelated transaction confirmed at 3.
let tx6 = common::new_tx(0);
// Insert transactions into graph with respective anchors
// Insert unconfirmed txs with a last_seen timestamp
let _ =
graph.batch_insert_relevant([&tx1, &tx2, &tx3, &tx6].iter().enumerate().map(|(i, tx)| {
let height = i as u32;
(
*tx,
local_chain
.get(height)
.map(|cp| cp.block_id())
.map(|block_id| ConfirmationBlockTime {
block_id,
confirmation_time: 100,
}),
)
}));
let _ = graph.batch_insert_relevant_unconfirmed([&tx4, &tx5].iter().map(|tx| (*tx, 100)));
// A helper lambda to extract and filter data from the graph.
let fetch =
|height: u32, graph: &IndexedTxGraph<ConfirmationBlockTime, KeychainTxOutIndex<String>>| {
let chain_tip = local_chain
.get(height)
.map(|cp| cp.block_id())
.unwrap_or_else(|| panic!("block must exist at {}", height));
let txouts = graph
.graph()
.filter_chain_txouts(
&local_chain,
chain_tip,
graph.index.outpoints().iter().cloned(),
)
.collect::<Vec<_>>();
let utxos = graph
.graph()
.filter_chain_unspents(
&local_chain,
chain_tip,
graph.index.outpoints().iter().cloned(),
)
.collect::<Vec<_>>();
let balance = graph.graph().balance(
&local_chain,
chain_tip,
graph.index.outpoints().iter().cloned(),
|_, spk: ScriptBuf| trusted_spks.contains(&spk),
);
let confirmed_txouts_txid = txouts
.iter()
.filter_map(|(_, full_txout)| {
if matches!(full_txout.chain_position, ChainPosition::Confirmed(_)) {
Some(full_txout.outpoint.txid)
} else {
None
}
})
.collect::<BTreeSet<_>>();
let unconfirmed_txouts_txid = txouts
.iter()
.filter_map(|(_, full_txout)| {
if matches!(full_txout.chain_position, ChainPosition::Unconfirmed(_)) {
Some(full_txout.outpoint.txid)
} else {
None
}
})
.collect::<BTreeSet<_>>();
let confirmed_utxos_txid = utxos
.iter()
.filter_map(|(_, full_txout)| {
if matches!(full_txout.chain_position, ChainPosition::Confirmed(_)) {
Some(full_txout.outpoint.txid)
} else {
None
}
})
.collect::<BTreeSet<_>>();
let unconfirmed_utxos_txid = utxos
.iter()
.filter_map(|(_, full_txout)| {
if matches!(full_txout.chain_position, ChainPosition::Unconfirmed(_)) {
Some(full_txout.outpoint.txid)
} else {
None
}
})
.collect::<BTreeSet<_>>();
(
confirmed_txouts_txid,
unconfirmed_txouts_txid,
confirmed_utxos_txid,
unconfirmed_utxos_txid,
balance,
)
};
// ----- TEST BLOCK -----
// AT Block 0
{
let (
confirmed_txouts_txid,
unconfirmed_txouts_txid,
confirmed_utxos_txid,
unconfirmed_utxos_txid,
balance,
) = fetch(0, &graph);
// tx1 is a confirmed txout and is unspent
// tx4, tx5 are unconfirmed
assert_eq!(confirmed_txouts_txid, [tx1.compute_txid()].into());
assert_eq!(
unconfirmed_txouts_txid,
[tx4.compute_txid(), tx5.compute_txid()].into()
);
assert_eq!(confirmed_utxos_txid, [tx1.compute_txid()].into());
assert_eq!(
unconfirmed_utxos_txid,
[tx4.compute_txid(), tx5.compute_txid()].into()
);
assert_eq!(
balance,
Balance {
immature: Amount::from_sat(70000), // immature coinbase
trusted_pending: Amount::from_sat(15000), // tx5
untrusted_pending: Amount::from_sat(20000), // tx4
confirmed: Amount::ZERO // Nothing is confirmed yet
}
);
}
// AT Block 1
{
let (
confirmed_txouts_txid,
unconfirmed_txouts_txid,
confirmed_utxos_txid,
unconfirmed_utxos_txid,
balance,
) = fetch(1, &graph);
// tx2 gets into confirmed txout set
assert_eq!(
confirmed_txouts_txid,
[tx1.compute_txid(), tx2.compute_txid()].into()
);
assert_eq!(
unconfirmed_txouts_txid,
[tx4.compute_txid(), tx5.compute_txid()].into()
);
// tx2 gets into confirmed utxos set
assert_eq!(
confirmed_utxos_txid,
[tx1.compute_txid(), tx2.compute_txid()].into()
);
assert_eq!(
unconfirmed_utxos_txid,
[tx4.compute_txid(), tx5.compute_txid()].into()
);
assert_eq!(
balance,
Balance {
immature: Amount::from_sat(70000), // immature coinbase
trusted_pending: Amount::from_sat(15000), // tx5
untrusted_pending: Amount::from_sat(20000), // tx4
confirmed: Amount::from_sat(30_000) // tx2 got confirmed
}
);
}
// AT Block 2
{
let (
confirmed_txouts_txid,
unconfirmed_txouts_txid,
confirmed_utxos_txid,
unconfirmed_utxos_txid,
balance,
) = fetch(2, &graph);
// tx3 now gets into the confirmed txout set
assert_eq!(
confirmed_txouts_txid,
[tx1.compute_txid(), tx2.compute_txid(), tx3.compute_txid()].into()
);
assert_eq!(
unconfirmed_txouts_txid,
[tx4.compute_txid(), tx5.compute_txid()].into()
);
// tx3 also gets into confirmed utxo set
assert_eq!(
confirmed_utxos_txid,
[tx1.compute_txid(), tx3.compute_txid()].into()
);
assert_eq!(
unconfirmed_utxos_txid,
[tx4.compute_txid(), tx5.compute_txid()].into()
);
assert_eq!(
balance,
Balance {
immature: Amount::from_sat(70000), // immature coinbase
trusted_pending: Amount::from_sat(15000), // tx5
untrusted_pending: Amount::from_sat(20000), // tx4
confirmed: Amount::from_sat(10000) // tx3 got confirmed
}
);
}
// AT Block 98
{
let (
confirmed_txouts_txid,
unconfirmed_txouts_txid,
confirmed_utxos_txid,
unconfirmed_utxos_txid,
balance,
) = fetch(98, &graph);
// no change compared to block 2
assert_eq!(
confirmed_txouts_txid,
[tx1.compute_txid(), tx2.compute_txid(), tx3.compute_txid()].into()
);
assert_eq!(
unconfirmed_txouts_txid,
[tx4.compute_txid(), tx5.compute_txid()].into()
);
assert_eq!(
confirmed_utxos_txid,
[tx1.compute_txid(), tx3.compute_txid()].into()
);
assert_eq!(
unconfirmed_utxos_txid,
[tx4.compute_txid(), tx5.compute_txid()].into()
);
// Coinbase is still immature
assert_eq!(
balance,
Balance {
immature: Amount::from_sat(70000), // immature coinbase
trusted_pending: Amount::from_sat(15000), // tx5
untrusted_pending: Amount::from_sat(20000), // tx4
confirmed: Amount::from_sat(10000) // tx3 is confirmed
}
);
}
// AT Block 99
{
let (_, _, _, _, balance) = fetch(99, &graph);
// Coinbase maturity hits
assert_eq!(
balance,
Balance {
immature: Amount::ZERO, // coinbase matured
trusted_pending: Amount::from_sat(15000), // tx5
untrusted_pending: Amount::from_sat(20000), // tx4
confirmed: Amount::from_sat(80000) // tx1 + tx3
}
);
}
}
/// Given a `LocalChain`, `IndexedTxGraph`, and a `Transaction`, when we insert some anchor
/// (possibly non-canonical) and/or a last-seen timestamp into the graph, we expect the
/// result of `get_chain_position` in these cases:
///
/// - tx with no anchors or last_seen has no `ChainPosition`
/// - tx with any last_seen will be `Unconfirmed`
/// - tx with an anchor in best chain will be `Confirmed`
/// - tx with an anchor not in best chain (no last_seen) has no `ChainPosition`
#[test]
fn test_get_chain_position() {
use bdk_chain::local_chain::CheckPoint;
use bdk_chain::spk_txout::SpkTxOutIndex;
use bdk_chain::BlockId;
struct TestCase<A> {
name: &'static str,
tx: Transaction,
anchor: Option<A>,
last_seen: Option<u64>,
exp_pos: Option<ChainPosition<A>>,
}
// addr: bcrt1qc6fweuf4xjvz4x3gx3t9e0fh4hvqyu2qw4wvxm
let spk = ScriptBuf::from_hex("0014c692ecf13534982a9a2834565cbd37add8027140").unwrap();
let mut graph = IndexedTxGraph::new({
let mut index = SpkTxOutIndex::default();
let _ = index.insert_spk(0u32, spk.clone());
index
});
// Anchors to test
let blocks = vec![block_id!(0, "g"), block_id!(1, "A"), block_id!(2, "B")];
let cp = CheckPoint::from_block_ids(blocks.clone()).unwrap();
let chain = LocalChain::from_tip(cp).unwrap();
// The test will insert a transaction into the indexed tx graph
// along with any anchors and timestamps, then check the value
// returned by `get_chain_position`.
fn run(
chain: &LocalChain,
graph: &mut IndexedTxGraph<BlockId, SpkTxOutIndex<u32>>,
test: TestCase<BlockId>,
) {
let TestCase {
name,
tx,
anchor,
last_seen,
exp_pos,
} = test;
// add data to graph
let txid = tx.compute_txid();
let _ = graph.insert_tx(tx);
if let Some(anchor) = anchor {
let _ = graph.insert_anchor(txid, anchor);
}
if let Some(seen_at) = last_seen {
let _ = graph.insert_seen_at(txid, seen_at);
}
// check chain position
let res = graph
.graph()
.get_chain_position(chain, chain.tip().block_id(), txid);
assert_eq!(
res.map(ChainPosition::cloned),
exp_pos,
"failed test case: {name}"
);
}
[
TestCase {
name: "tx no anchors or last_seen - no chain pos",
tx: Transaction {
output: vec![TxOut {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(0)
},
anchor: None,
last_seen: None,
exp_pos: None,
},
TestCase {
name: "tx last_seen - unconfirmed",
tx: Transaction {
output: vec![TxOut {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(1)
},
anchor: None,
last_seen: Some(2),
exp_pos: Some(ChainPosition::Unconfirmed(2)),
},
TestCase {
name: "tx anchor in best chain - confirmed",
tx: Transaction {
output: vec![TxOut {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(2)
},
anchor: Some(blocks[1]),
last_seen: None,
exp_pos: Some(ChainPosition::Confirmed(blocks[1])),
},
TestCase {
name: "tx unknown anchor with last_seen - unconfirmed",
tx: Transaction {
output: vec![TxOut {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(3)
},
anchor: Some(block_id!(2, "B'")),
last_seen: Some(2),
exp_pos: Some(ChainPosition::Unconfirmed(2)),
},
TestCase {
name: "tx unknown anchor - no chain pos",
tx: Transaction {
output: vec![TxOut {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(4)
},
anchor: Some(block_id!(2, "B'")),
last_seen: None,
exp_pos: None,
},
]
.into_iter()
.for_each(|t| run(&chain, &mut graph, t));
}

View File

@ -0,0 +1,689 @@
#![cfg(feature = "miniscript")]
#[macro_use]
mod common;
use bdk_chain::{
collections::BTreeMap,
indexer::keychain_txout::{ChangeSet, KeychainTxOutIndex},
DescriptorExt, DescriptorId, Indexer, Merge,
};
use bitcoin::{secp256k1::Secp256k1, Amount, OutPoint, ScriptBuf, Transaction, TxOut};
use miniscript::{Descriptor, DescriptorPublicKey};
use crate::common::DESCRIPTORS;
#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
enum TestKeychain {
External,
Internal,
}
fn parse_descriptor(descriptor: &str) -> Descriptor<DescriptorPublicKey> {
let secp = bdk_chain::bitcoin::secp256k1::Secp256k1::signing_only();
Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, descriptor)
.unwrap()
.0
}
fn init_txout_index(
external_descriptor: Descriptor<DescriptorPublicKey>,
internal_descriptor: Descriptor<DescriptorPublicKey>,
lookahead: u32,
) -> KeychainTxOutIndex<TestKeychain> {
let mut txout_index = KeychainTxOutIndex::<TestKeychain>::new(lookahead);
let _ = txout_index
.insert_descriptor(TestKeychain::External, external_descriptor)
.unwrap();
let _ = txout_index
.insert_descriptor(TestKeychain::Internal, internal_descriptor)
.unwrap();
txout_index
}
fn spk_at_index(descriptor: &Descriptor<DescriptorPublicKey>, index: u32) -> ScriptBuf {
descriptor
.derived_descriptor(&Secp256k1::verification_only(), index)
.expect("must derive")
.script_pubkey()
}
// We create two empty changesets lhs and rhs, we then insert various descriptors with various
// last_revealed, merge rhs to lhs, and check that the result is consistent with these rules:
// - Existing index doesn't update if the new index in `other` is lower than `self`.
// - Existing index updates if the new index in `other` is higher than `self`.
// - Existing index is unchanged if keychain doesn't exist in `other`.
// - New keychain gets added if the keychain is in `other` but not in `self`.
#[test]
fn merge_changesets_check_last_revealed() {
let secp = bitcoin::secp256k1::Secp256k1::signing_only();
let descriptor_ids: Vec<_> = DESCRIPTORS
.iter()
.take(4)
.map(|d| {
Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, d)
.unwrap()
.0
.descriptor_id()
})
.collect();
let mut lhs_di = BTreeMap::<DescriptorId, u32>::default();
let mut rhs_di = BTreeMap::<DescriptorId, u32>::default();
lhs_di.insert(descriptor_ids[0], 7);
lhs_di.insert(descriptor_ids[1], 0);
lhs_di.insert(descriptor_ids[2], 3);
rhs_di.insert(descriptor_ids[0], 3); // value less than lhs desc 0
rhs_di.insert(descriptor_ids[1], 5); // value more than lhs desc 1
lhs_di.insert(descriptor_ids[3], 4); // key doesn't exist in lhs
let mut lhs = ChangeSet {
last_revealed: lhs_di,
};
let rhs = ChangeSet {
last_revealed: rhs_di,
};
lhs.merge(rhs);
// Existing index doesn't update if the new index in `other` is lower than `self`.
assert_eq!(lhs.last_revealed.get(&descriptor_ids[0]), Some(&7));
// Existing index updates if the new index in `other` is higher than `self`.
assert_eq!(lhs.last_revealed.get(&descriptor_ids[1]), Some(&5));
// Existing index is unchanged if keychain doesn't exist in `other`.
assert_eq!(lhs.last_revealed.get(&descriptor_ids[2]), Some(&3));
// New keychain gets added if the keychain is in `other` but not in `self`.
assert_eq!(lhs.last_revealed.get(&descriptor_ids[3]), Some(&4));
}
#[test]
fn test_set_all_derivation_indices() {
let external_descriptor = parse_descriptor(DESCRIPTORS[0]);
let internal_descriptor = parse_descriptor(DESCRIPTORS[1]);
let mut txout_index =
init_txout_index(external_descriptor.clone(), internal_descriptor.clone(), 0);
let derive_to: BTreeMap<_, _> =
[(TestKeychain::External, 12), (TestKeychain::Internal, 24)].into();
let last_revealed: BTreeMap<_, _> = [
(external_descriptor.descriptor_id(), 12),
(internal_descriptor.descriptor_id(), 24),
]
.into();
assert_eq!(
txout_index.reveal_to_target_multi(&derive_to),
ChangeSet {
last_revealed: last_revealed.clone()
}
);
assert_eq!(txout_index.last_revealed_indices(), derive_to);
assert_eq!(
txout_index.reveal_to_target_multi(&derive_to),
ChangeSet::default(),
"no changes if we set to the same thing"
);
assert_eq!(txout_index.initial_changeset().last_revealed, last_revealed);
}
#[test]
fn test_lookahead() {
let external_descriptor = parse_descriptor(DESCRIPTORS[0]);
let internal_descriptor = parse_descriptor(DESCRIPTORS[1]);
let mut txout_index =
init_txout_index(external_descriptor.clone(), internal_descriptor.clone(), 10);
// given:
// - external lookahead set to 10
// when:
// - set external derivation index to value higher than last, but within the lookahead value
// expect:
// - scripts cached in spk_txout_index should increase correctly
// - stored scripts of external keychain should be of expected counts
for index in (0..20).skip_while(|i| i % 2 == 1) {
let (revealed_spks, revealed_changeset) = txout_index
.reveal_to_target(TestKeychain::External, index)
.unwrap();
assert_eq!(
revealed_spks,
vec![(index, spk_at_index(&external_descriptor, index))],
);
assert_eq!(
&revealed_changeset.last_revealed,
&[(external_descriptor.descriptor_id(), index)].into()
);
assert_eq!(
txout_index.inner().all_spks().len(),
10 /* external lookahead */ +
10 /* internal lookahead */ +
index as usize + 1 /* `derived` count */
);
assert_eq!(
txout_index
.revealed_keychain_spks(TestKeychain::External)
.count(),
index as usize + 1,
);
assert_eq!(
txout_index
.revealed_keychain_spks(TestKeychain::Internal)
.count(),
0,
);
assert_eq!(
txout_index
.unused_keychain_spks(TestKeychain::External)
.count(),
index as usize + 1,
);
assert_eq!(
txout_index
.unused_keychain_spks(TestKeychain::Internal)
.count(),
0,
);
}
// given:
// - internal lookahead is 10
// - internal derivation index is `None`
// when:
// - derivation index is set ahead of current derivation index + lookahead
// expect:
// - scripts cached in spk_txout_index should increase correctly, a.k.a. no scripts are skipped
let (revealed_spks, revealed_changeset) = txout_index
.reveal_to_target(TestKeychain::Internal, 24)
.unwrap();
assert_eq!(
revealed_spks,
(0..=24)
.map(|index| (index, spk_at_index(&internal_descriptor, index)))
.collect::<Vec<_>>(),
);
assert_eq!(
&revealed_changeset.last_revealed,
&[(internal_descriptor.descriptor_id(), 24)].into()
);
assert_eq!(
txout_index.inner().all_spks().len(),
10 /* external lookahead */ +
10 /* internal lookahead */ +
20 /* external stored index count */ +
25 /* internal stored index count */
);
assert_eq!(
txout_index
.revealed_keychain_spks(TestKeychain::Internal)
.count(),
25,
);
// ensure derivation indices are expected for each keychain
let last_external_index = txout_index
.last_revealed_index(TestKeychain::External)
.expect("already derived");
let last_internal_index = txout_index
.last_revealed_index(TestKeychain::Internal)
.expect("already derived");
assert_eq!(last_external_index, 19);
assert_eq!(last_internal_index, 24);
// when:
// - scanning txouts with spks within stored indexes
// expect:
// - no changes to stored index counts
let external_iter = 0..=last_external_index;
let internal_iter = last_internal_index - last_external_index..=last_internal_index;
for (external_index, internal_index) in external_iter.zip(internal_iter) {
let tx = Transaction {
output: vec![
TxOut {
script_pubkey: external_descriptor
.at_derivation_index(external_index)
.unwrap()
.script_pubkey(),
value: Amount::from_sat(10_000),
},
TxOut {
script_pubkey: internal_descriptor
.at_derivation_index(internal_index)
.unwrap()
.script_pubkey(),
value: Amount::from_sat(10_000),
},
],
..common::new_tx(external_index)
};
assert_eq!(txout_index.index_tx(&tx), ChangeSet::default());
assert_eq!(
txout_index.last_revealed_index(TestKeychain::External),
Some(last_external_index)
);
assert_eq!(
txout_index.last_revealed_index(TestKeychain::Internal),
Some(last_internal_index)
);
assert_eq!(
txout_index
.revealed_keychain_spks(TestKeychain::External)
.count(),
last_external_index as usize + 1,
);
assert_eq!(
txout_index
.revealed_keychain_spks(TestKeychain::Internal)
.count(),
last_internal_index as usize + 1,
);
}
}
// when:
// - scanning txouts with spks above last stored index
// expect:
// - last revealed index should increase as expected
// - last used index should change as expected
#[test]
fn test_scan_with_lookahead() {
let external_descriptor = parse_descriptor(DESCRIPTORS[0]);
let internal_descriptor = parse_descriptor(DESCRIPTORS[1]);
let mut txout_index =
init_txout_index(external_descriptor.clone(), internal_descriptor.clone(), 10);
let spks: BTreeMap<u32, ScriptBuf> = [0, 10, 20, 30]
.into_iter()
.map(|i| {
(
i,
external_descriptor
.at_derivation_index(i)
.unwrap()
.script_pubkey(),
)
})
.collect();
for (&spk_i, spk) in &spks {
let op = OutPoint::new(h!("fake tx"), spk_i);
let txout = TxOut {
script_pubkey: spk.clone(),
value: Amount::ZERO,
};
let changeset = txout_index.index_txout(op, &txout);
assert_eq!(
&changeset.last_revealed,
&[(external_descriptor.descriptor_id(), spk_i)].into()
);
assert_eq!(
txout_index.last_revealed_index(TestKeychain::External),
Some(spk_i)
);
assert_eq!(
txout_index.last_used_index(TestKeychain::External),
Some(spk_i)
);
}
// now try with index 41 (lookahead surpassed), we expect that the txout to not be indexed
let spk_41 = external_descriptor
.at_derivation_index(41)
.unwrap()
.script_pubkey();
let op = OutPoint::new(h!("fake tx"), 41);
let txout = TxOut {
script_pubkey: spk_41,
value: Amount::ZERO,
};
let changeset = txout_index.index_txout(op, &txout);
assert!(changeset.is_empty());
}
#[test]
#[rustfmt::skip]
fn test_wildcard_derivations() {
let external_descriptor = parse_descriptor(DESCRIPTORS[0]);
let internal_descriptor = parse_descriptor(DESCRIPTORS[1]);
let mut txout_index = init_txout_index(external_descriptor.clone(), internal_descriptor.clone(), 0);
let external_spk_0 = external_descriptor.at_derivation_index(0).unwrap().script_pubkey();
let external_spk_16 = external_descriptor.at_derivation_index(16).unwrap().script_pubkey();
let external_spk_26 = external_descriptor.at_derivation_index(26).unwrap().script_pubkey();
let external_spk_27 = external_descriptor.at_derivation_index(27).unwrap().script_pubkey();
// - nothing is derived
// - unused list is also empty
//
// - next_derivation_index() == (0, true)
// - derive_new() == ((0, <spk>), keychain::ChangeSet)
// - next_unused() == ((0, <spk>), keychain::ChangeSet:is_empty())
assert_eq!(txout_index.next_index(TestKeychain::External).unwrap(), (0, true));
let (spk, changeset) = txout_index.reveal_next_spk(TestKeychain::External).unwrap();
assert_eq!(spk, (0_u32, external_spk_0.clone()));
assert_eq!(&changeset.last_revealed, &[(external_descriptor.descriptor_id(), 0)].into());
let (spk, changeset) = txout_index.next_unused_spk(TestKeychain::External).unwrap();
assert_eq!(spk, (0_u32, external_spk_0.clone()));
assert_eq!(&changeset.last_revealed, &[].into());
// - derived till 25
// - used all spks till 15.
// - used list : [0..=15, 17, 20, 23]
// - unused list: [16, 18, 19, 21, 22, 24, 25]
// - next_derivation_index() = (26, true)
// - derive_new() = ((26, <spk>), keychain::ChangeSet)
// - next_unused() == ((16, <spk>), keychain::ChangeSet::is_empty())
let _ = txout_index.reveal_to_target(TestKeychain::External, 25);
(0..=15)
.chain([17, 20, 23])
.for_each(|index| assert!(txout_index.mark_used(TestKeychain::External, index)));
assert_eq!(txout_index.next_index(TestKeychain::External).unwrap(), (26, true));
let (spk, changeset) = txout_index.reveal_next_spk(TestKeychain::External).unwrap();
assert_eq!(spk, (26, external_spk_26));
assert_eq!(&changeset.last_revealed, &[(external_descriptor.descriptor_id(), 26)].into());
let (spk, changeset) = txout_index.next_unused_spk(TestKeychain::External).unwrap();
assert_eq!(spk, (16, external_spk_16));
assert_eq!(&changeset.last_revealed, &[].into());
// - Use all the derived till 26.
// - next_unused() = ((27, <spk>), keychain::ChangeSet)
(0..=26).for_each(|index| {
txout_index.mark_used(TestKeychain::External, index);
});
let (spk, changeset) = txout_index.next_unused_spk(TestKeychain::External).unwrap();
assert_eq!(spk, (27, external_spk_27));
assert_eq!(&changeset.last_revealed, &[(external_descriptor.descriptor_id(), 27)].into());
}
#[test]
fn test_non_wildcard_derivations() {
let mut txout_index = KeychainTxOutIndex::<TestKeychain>::new(0);
let secp = bitcoin::secp256k1::Secp256k1::signing_only();
let (no_wildcard_descriptor, _) =
Descriptor::<DescriptorPublicKey>::parse_descriptor(&secp, DESCRIPTORS[6]).unwrap();
let external_spk = no_wildcard_descriptor
.at_derivation_index(0)
.unwrap()
.script_pubkey();
let _ = txout_index
.insert_descriptor(TestKeychain::External, no_wildcard_descriptor.clone())
.unwrap();
// given:
// - `txout_index` with no stored scripts
// expect:
// - next derivation index should be new
// - when we derive a new script, script @ index 0
// - when we get the next unused script, script @ index 0
assert_eq!(
txout_index.next_index(TestKeychain::External).unwrap(),
(0, true)
);
let (spk, changeset) = txout_index.reveal_next_spk(TestKeychain::External).unwrap();
assert_eq!(spk, (0, external_spk.clone()));
assert_eq!(
&changeset.last_revealed,
&[(no_wildcard_descriptor.descriptor_id(), 0)].into()
);
let (spk, changeset) = txout_index.next_unused_spk(TestKeychain::External).unwrap();
assert_eq!(spk, (0, external_spk.clone()));
assert_eq!(&changeset.last_revealed, &[].into());
// given:
// - the non-wildcard descriptor already has a stored and used script
// expect:
// - next derivation index should not be new
// - derive new and next unused should return the old script
// - store_up_to should not panic and return empty changeset
assert_eq!(
txout_index.next_index(TestKeychain::External).unwrap(),
(0, false)
);
txout_index.mark_used(TestKeychain::External, 0);
let (spk, changeset) = txout_index.reveal_next_spk(TestKeychain::External).unwrap();
assert_eq!(spk, (0, external_spk.clone()));
assert_eq!(&changeset.last_revealed, &[].into());
let (spk, changeset) = txout_index.next_unused_spk(TestKeychain::External).unwrap();
assert_eq!(spk, (0, external_spk.clone()));
assert_eq!(&changeset.last_revealed, &[].into());
let (revealed_spks, revealed_changeset) = txout_index
.reveal_to_target(TestKeychain::External, 200)
.unwrap();
assert_eq!(revealed_spks.len(), 0);
assert!(revealed_changeset.is_empty());
// we check that spks_of_keychain returns a SpkIterator with just one element
assert_eq!(
txout_index
.revealed_keychain_spks(TestKeychain::External)
.count(),
1,
);
}
/// Check that calling `lookahead_to_target` stores the expected spks.
#[test]
fn lookahead_to_target() {
#[derive(Default)]
struct TestCase {
/// Global lookahead value.
lookahead: u32,
/// Last revealed index for external keychain.
external_last_revealed: Option<u32>,
/// Last revealed index for internal keychain.
internal_last_revealed: Option<u32>,
/// Call `lookahead_to_target(External, u32)`.
external_target: Option<u32>,
/// Call `lookahead_to_target(Internal, u32)`.
internal_target: Option<u32>,
}
let test_cases = &[
TestCase {
lookahead: 0,
external_target: Some(100),
..Default::default()
},
TestCase {
lookahead: 10,
internal_target: Some(99),
..Default::default()
},
TestCase {
lookahead: 100,
internal_target: Some(9),
external_target: Some(10),
..Default::default()
},
TestCase {
lookahead: 12,
external_last_revealed: Some(2),
internal_last_revealed: Some(2),
internal_target: Some(15),
external_target: Some(13),
},
TestCase {
lookahead: 13,
external_last_revealed: Some(100),
internal_last_revealed: Some(21),
internal_target: Some(120),
external_target: Some(130),
},
];
for t in test_cases {
let external_descriptor = parse_descriptor(DESCRIPTORS[0]);
let internal_descriptor = parse_descriptor(DESCRIPTORS[1]);
let mut index = init_txout_index(
external_descriptor.clone(),
internal_descriptor.clone(),
t.lookahead,
);
if let Some(last_revealed) = t.external_last_revealed {
let _ = index.reveal_to_target(TestKeychain::External, last_revealed);
}
if let Some(last_revealed) = t.internal_last_revealed {
let _ = index.reveal_to_target(TestKeychain::Internal, last_revealed);
}
let keychain_test_cases = [
(
TestKeychain::External,
t.external_last_revealed,
t.external_target,
),
(
TestKeychain::Internal,
t.internal_last_revealed,
t.internal_target,
),
];
for (keychain, last_revealed, target) in keychain_test_cases {
if let Some(target) = target {
let original_last_stored_index = match last_revealed {
Some(last_revealed) => Some(last_revealed + t.lookahead),
None => t.lookahead.checked_sub(1),
};
let exp_last_stored_index = match original_last_stored_index {
Some(original_last_stored_index) => {
Ord::max(target, original_last_stored_index)
}
None => target,
};
index.lookahead_to_target(keychain.clone(), target);
let keys = index
.inner()
.all_spks()
.range((keychain.clone(), 0)..=(keychain.clone(), u32::MAX))
.map(|(k, _)| k.clone())
.collect::<Vec<_>>();
let exp_keys = core::iter::repeat(keychain)
.zip(0_u32..=exp_last_stored_index)
.collect::<Vec<_>>();
assert_eq!(keys, exp_keys);
}
}
}
}
#[test]
fn applying_changesets_one_by_one_vs_aggregate_must_have_same_result() {
let desc = parse_descriptor(DESCRIPTORS[0]);
let changesets: &[ChangeSet] = &[
ChangeSet {
last_revealed: [(desc.descriptor_id(), 10)].into(),
},
ChangeSet {
last_revealed: [(desc.descriptor_id(), 12)].into(),
},
];
let mut indexer_a = KeychainTxOutIndex::<TestKeychain>::new(0);
indexer_a
.insert_descriptor(TestKeychain::External, desc.clone())
.expect("must insert keychain");
for changeset in changesets {
indexer_a.apply_changeset(changeset.clone());
}
let mut indexer_b = KeychainTxOutIndex::<TestKeychain>::new(0);
indexer_b
.insert_descriptor(TestKeychain::External, desc.clone())
.expect("must insert keychain");
let aggregate_changesets = changesets
.iter()
.cloned()
.reduce(|mut agg, cs| {
agg.merge(cs);
agg
})
.expect("must aggregate changesets");
indexer_b.apply_changeset(aggregate_changesets);
assert_eq!(
indexer_a.keychains().collect::<Vec<_>>(),
indexer_b.keychains().collect::<Vec<_>>()
);
assert_eq!(
indexer_a.spk_at_index(TestKeychain::External, 0),
indexer_b.spk_at_index(TestKeychain::External, 0)
);
assert_eq!(
indexer_a.spk_at_index(TestKeychain::Internal, 0),
indexer_b.spk_at_index(TestKeychain::Internal, 0)
);
assert_eq!(
indexer_a.last_revealed_indices(),
indexer_b.last_revealed_indices()
);
}
#[test]
fn assigning_same_descriptor_to_multiple_keychains_should_error() {
let desc = parse_descriptor(DESCRIPTORS[0]);
let mut indexer = KeychainTxOutIndex::<TestKeychain>::new(0);
let _ = indexer
.insert_descriptor(TestKeychain::Internal, desc.clone())
.unwrap();
assert!(indexer
.insert_descriptor(TestKeychain::External, desc)
.is_err())
}
#[test]
fn reassigning_keychain_to_a_new_descriptor_should_error() {
let desc1 = parse_descriptor(DESCRIPTORS[0]);
let desc2 = parse_descriptor(DESCRIPTORS[1]);
let mut indexer = KeychainTxOutIndex::<TestKeychain>::new(0);
let _ = indexer.insert_descriptor(TestKeychain::Internal, desc1);
assert!(indexer
.insert_descriptor(TestKeychain::Internal, desc2)
.is_err());
}
#[test]
fn when_querying_over_a_range_of_keychains_the_utxos_should_show_up() {
let mut indexer = KeychainTxOutIndex::<usize>::new(0);
let mut tx = common::new_tx(0);
for (i, descriptor) in DESCRIPTORS.iter().enumerate() {
let descriptor = parse_descriptor(descriptor);
let _ = indexer.insert_descriptor(i, descriptor.clone()).unwrap();
if i != 4 {
// skip one in the middle to see if uncovers any bugs
indexer.reveal_next_spk(i);
}
tx.output.push(TxOut {
script_pubkey: descriptor.at_derivation_index(0).unwrap().script_pubkey(),
value: Amount::from_sat(10_000),
});
}
let n_spks = DESCRIPTORS.len() - /*we skipped one*/ 1;
let _ = indexer.index_tx(&tx);
assert_eq!(indexer.outpoints().len(), n_spks);
assert_eq!(indexer.revealed_spks(0..DESCRIPTORS.len()).count(), n_spks);
assert_eq!(indexer.revealed_spks(1..4).count(), 4 - 1);
assert_eq!(
indexer.net_value(&tx, 0..DESCRIPTORS.len()).to_sat(),
(10_000 * n_spks) as i64
);
assert_eq!(
indexer.net_value(&tx, 3..6).to_sat(),
(10_000 * (6 - 3 - /*the skipped one*/ 1)) as i64
);
}

View File

@ -0,0 +1,848 @@
#![cfg(feature = "miniscript")]
use std::ops::{Bound, RangeBounds};
use bdk_chain::{
local_chain::{
AlterCheckPointError, ApplyHeaderError, CannotConnectError, ChangeSet, CheckPoint,
LocalChain, MissingGenesisError,
},
BlockId,
};
use bitcoin::{block::Header, hashes::Hash, BlockHash};
use proptest::prelude::*;
#[macro_use]
mod common;
#[derive(Debug)]
struct TestLocalChain<'a> {
name: &'static str,
chain: LocalChain,
update: CheckPoint,
exp: ExpectedResult<'a>,
}
#[derive(Debug, PartialEq)]
enum ExpectedResult<'a> {
Ok {
changeset: &'a [(u32, Option<BlockHash>)],
init_changeset: &'a [(u32, Option<BlockHash>)],
},
Err(CannotConnectError),
}
impl<'a> TestLocalChain<'a> {
fn run(mut self) {
println!("[TestLocalChain] test: {}", self.name);
let got_changeset = match self.chain.apply_update(self.update) {
Ok(changeset) => changeset,
Err(got_err) => {
assert_eq!(
ExpectedResult::Err(got_err),
self.exp,
"{}: unexpected error",
self.name
);
return;
}
};
match self.exp {
ExpectedResult::Ok {
changeset,
init_changeset,
} => {
assert_eq!(
got_changeset,
changeset.iter().cloned().collect(),
"{}: unexpected changeset",
self.name
);
assert_eq!(
self.chain.initial_changeset(),
init_changeset.iter().cloned().collect(),
"{}: unexpected initial changeset",
self.name
);
}
ExpectedResult::Err(err) => panic!(
"{}: expected error ({}), got non-error result: {:?}",
self.name, err, got_changeset
),
}
}
}
#[test]
fn update_local_chain() {
[
TestLocalChain {
name: "add first tip",
chain: local_chain![(0, h!("A"))],
update: chain_update![(0, h!("A"))],
exp: ExpectedResult::Ok {
changeset: &[],
init_changeset: &[(0, Some(h!("A")))],
},
},
TestLocalChain {
name: "add second tip",
chain: local_chain![(0, h!("A"))],
update: chain_update![(0, h!("A")), (1, h!("B"))],
exp: ExpectedResult::Ok {
changeset: &[(1, Some(h!("B")))],
init_changeset: &[(0, Some(h!("A"))), (1, Some(h!("B")))],
},
},
TestLocalChain {
name: "two disjoint chains cannot merge",
chain: local_chain![(0, h!("_")), (1, h!("A"))],
update: chain_update![(0, h!("_")), (2, h!("B"))],
exp: ExpectedResult::Err(CannotConnectError {
try_include_height: 1,
}),
},
TestLocalChain {
name: "two disjoint chains cannot merge (existing chain longer)",
chain: local_chain![(0, h!("_")), (2, h!("A"))],
update: chain_update![(0, h!("_")), (1, h!("B"))],
exp: ExpectedResult::Err(CannotConnectError {
try_include_height: 2,
}),
},
TestLocalChain {
name: "duplicate chains should merge",
chain: local_chain![(0, h!("A"))],
update: chain_update![(0, h!("A"))],
exp: ExpectedResult::Ok {
changeset: &[],
init_changeset: &[(0, Some(h!("A")))],
},
},
// Introduce an older checkpoint (B)
// | 0 | 1 | 2 | 3
// chain | _ C D
// update | _ B C
TestLocalChain {
name: "can introduce older checkpoint",
chain: local_chain![(0, h!("_")), (2, h!("C")), (3, h!("D"))],
update: chain_update![(0, h!("_")), (1, h!("B")), (2, h!("C"))],
exp: ExpectedResult::Ok {
changeset: &[(1, Some(h!("B")))],
init_changeset: &[(0, Some(h!("_"))), (1, Some(h!("B"))), (2, Some(h!("C"))), (3, Some(h!("D")))],
},
},
// Introduce an older checkpoint (A) that is not directly behind PoA
// | 0 | 2 | 3 | 4
// chain | _ B C
// update | _ A C
TestLocalChain {
name: "can introduce older checkpoint 2",
chain: local_chain![(0, h!("_")), (3, h!("B")), (4, h!("C"))],
update: chain_update![(0, h!("_")), (2, h!("A")), (4, h!("C"))],
exp: ExpectedResult::Ok {
changeset: &[(2, Some(h!("A")))],
init_changeset: &[(0, Some(h!("_"))), (2, Some(h!("A"))), (3, Some(h!("B"))), (4, Some(h!("C")))],
}
},
// Introduce an older checkpoint (B) that is not the oldest checkpoint
// | 0 | 1 | 2 | 3
// chain | _ A C
// update | _ B C
TestLocalChain {
name: "can introduce older checkpoint 3",
chain: local_chain![(0, h!("_")), (1, h!("A")), (3, h!("C"))],
update: chain_update![(0, h!("_")), (2, h!("B")), (3, h!("C"))],
exp: ExpectedResult::Ok {
changeset: &[(2, Some(h!("B")))],
init_changeset: &[(0, Some(h!("_"))), (1, Some(h!("A"))), (2, Some(h!("B"))), (3, Some(h!("C")))],
}
},
// Introduce two older checkpoints below the PoA
// | 0 | 1 | 2 | 3
// chain | _ C
// update | _ A B C
TestLocalChain {
name: "introduce two older checkpoints below PoA",
chain: local_chain![(0, h!("_")), (3, h!("C"))],
update: chain_update![(0, h!("_")), (1, h!("A")), (2, h!("B")), (3, h!("C"))],
exp: ExpectedResult::Ok {
changeset: &[(1, Some(h!("A"))), (2, Some(h!("B")))],
init_changeset: &[(0, Some(h!("_"))), (1, Some(h!("A"))), (2, Some(h!("B"))), (3, Some(h!("C")))],
},
},
TestLocalChain {
name: "fix blockhash before agreement point",
chain: local_chain![(0, h!("im-wrong")), (1, h!("we-agree"))],
update: chain_update![(0, h!("fix")), (1, h!("we-agree"))],
exp: ExpectedResult::Ok {
changeset: &[(0, Some(h!("fix")))],
init_changeset: &[(0, Some(h!("fix"))), (1, Some(h!("we-agree")))],
},
},
// B and C are in both chain and update
// | 0 | 1 | 2 | 3 | 4
// chain | _ B C
// update | _ A B C D
// This should succeed with the point of agreement being C and A should be added in addition.
TestLocalChain {
name: "two points of agreement",
chain: local_chain![(0, h!("_")), (2, h!("B")), (3, h!("C"))],
update: chain_update![(0, h!("_")), (1, h!("A")), (2, h!("B")), (3, h!("C")), (4, h!("D"))],
exp: ExpectedResult::Ok {
changeset: &[(1, Some(h!("A"))), (4, Some(h!("D")))],
init_changeset: &[
(0, Some(h!("_"))),
(1, Some(h!("A"))),
(2, Some(h!("B"))),
(3, Some(h!("C"))),
(4, Some(h!("D"))),
],
},
},
// Update and chain does not connect:
// | 0 | 1 | 2 | 3 | 4
// chain | _ B C
// update | _ A B D
// This should fail as we cannot figure out whether C & D are on the same chain
TestLocalChain {
name: "update and chain does not connect",
chain: local_chain![(0, h!("_")), (2, h!("B")), (3, h!("C"))],
update: chain_update![(0, h!("_")), (1, h!("A")), (2, h!("B")), (4, h!("D"))],
exp: ExpectedResult::Err(CannotConnectError {
try_include_height: 3,
}),
},
// Transient invalidation:
// | 0 | 1 | 2 | 3 | 4 | 5
// chain | _ B C E
// update | _ B' C' D
// This should succeed and invalidate B,C and E with point of agreement being A.
TestLocalChain {
name: "transitive invalidation applies to checkpoints higher than invalidation",
chain: local_chain![(0, h!("_")), (2, h!("B")), (3, h!("C")), (5, h!("E"))],
update: chain_update![(0, h!("_")), (2, h!("B'")), (3, h!("C'")), (4, h!("D"))],
exp: ExpectedResult::Ok {
changeset: &[
(2, Some(h!("B'"))),
(3, Some(h!("C'"))),
(4, Some(h!("D"))),
(5, None),
],
init_changeset: &[
(0, Some(h!("_"))),
(2, Some(h!("B'"))),
(3, Some(h!("C'"))),
(4, Some(h!("D"))),
],
},
},
// Transient invalidation:
// | 0 | 1 | 2 | 3 | 4
// chain | _ B C E
// update | _ B' C' D
// This should succeed and invalidate B, C and E with no point of agreement
TestLocalChain {
name: "transitive invalidation applies to checkpoints higher than invalidation no point of agreement",
chain: local_chain![(0, h!("_")), (1, h!("B")), (2, h!("C")), (4, h!("E"))],
update: chain_update![(0, h!("_")), (1, h!("B'")), (2, h!("C'")), (3, h!("D"))],
exp: ExpectedResult::Ok {
changeset: &[
(1, Some(h!("B'"))),
(2, Some(h!("C'"))),
(3, Some(h!("D"))),
(4, None)
],
init_changeset: &[
(0, Some(h!("_"))),
(1, Some(h!("B'"))),
(2, Some(h!("C'"))),
(3, Some(h!("D"))),
],
},
},
// Transient invalidation:
// | 0 | 1 | 2 | 3 | 4 | 5
// chain | _ A B C E
// update | _ B' C' D
// This should fail since although it tells us that B and C are invalid it doesn't tell us whether
// A was invalid.
TestLocalChain {
name: "invalidation but no connection",
chain: local_chain![(0, h!("_")), (1, h!("A")), (2, h!("B")), (3, h!("C")), (5, h!("E"))],
update: chain_update![(0, h!("_")), (2, h!("B'")), (3, h!("C'")), (4, h!("D"))],
exp: ExpectedResult::Err(CannotConnectError { try_include_height: 1 }),
},
// Introduce blocks between two points of agreement
// | 0 | 1 | 2 | 3 | 4 | 5
// chain | A B D E
// update | A C E F
TestLocalChain {
name: "introduce blocks between two points of agreement",
chain: local_chain![(0, h!("A")), (1, h!("B")), (3, h!("D")), (4, h!("E"))],
update: chain_update![(0, h!("A")), (2, h!("C")), (4, h!("E")), (5, h!("F"))],
exp: ExpectedResult::Ok {
changeset: &[
(2, Some(h!("C"))),
(5, Some(h!("F"))),
],
init_changeset: &[
(0, Some(h!("A"))),
(1, Some(h!("B"))),
(2, Some(h!("C"))),
(3, Some(h!("D"))),
(4, Some(h!("E"))),
(5, Some(h!("F"))),
],
},
},
// Allow update that is shorter than original chain
// | 0 | 1 | 2 | 3 | 4 | 5
// chain | A C D E F
// update | A C D'
TestLocalChain {
name: "allow update that is shorter than original chain",
chain: local_chain![(0, h!("_")), (2, h!("C")), (3, h!("D")), (4, h!("E")), (5, h!("F"))],
update: chain_update![(0, h!("_")), (2, h!("C")), (3, h!("D'"))],
exp: ExpectedResult::Ok {
changeset: &[
(3, Some(h!("D'"))),
(4, None),
(5, None),
],
init_changeset: &[
(0, Some(h!("_"))),
(2, Some(h!("C"))),
(3, Some(h!("D'"))),
],
},
},
]
.into_iter()
.for_each(TestLocalChain::run);
}
#[test]
fn local_chain_insert_block() {
struct TestCase {
original: LocalChain,
insert: (u32, BlockHash),
expected_result: Result<ChangeSet, AlterCheckPointError>,
expected_final: LocalChain,
}
let test_cases = [
TestCase {
original: local_chain![(0, h!("_"))],
insert: (5, h!("block5")),
expected_result: Ok([(5, Some(h!("block5")))].into()),
expected_final: local_chain![(0, h!("_")), (5, h!("block5"))],
},
TestCase {
original: local_chain![(0, h!("_")), (3, h!("A"))],
insert: (4, h!("B")),
expected_result: Ok([(4, Some(h!("B")))].into()),
expected_final: local_chain![(0, h!("_")), (3, h!("A")), (4, h!("B"))],
},
TestCase {
original: local_chain![(0, h!("_")), (4, h!("B"))],
insert: (3, h!("A")),
expected_result: Ok([(3, Some(h!("A")))].into()),
expected_final: local_chain![(0, h!("_")), (3, h!("A")), (4, h!("B"))],
},
TestCase {
original: local_chain![(0, h!("_")), (2, h!("K"))],
insert: (2, h!("K")),
expected_result: Ok([].into()),
expected_final: local_chain![(0, h!("_")), (2, h!("K"))],
},
TestCase {
original: local_chain![(0, h!("_")), (2, h!("K"))],
insert: (2, h!("J")),
expected_result: Err(AlterCheckPointError {
height: 2,
original_hash: h!("K"),
update_hash: Some(h!("J")),
}),
expected_final: local_chain![(0, h!("_")), (2, h!("K"))],
},
];
for (i, t) in test_cases.into_iter().enumerate() {
let mut chain = t.original;
assert_eq!(
chain.insert_block(t.insert.into()),
t.expected_result,
"[{}] unexpected result when inserting block",
i,
);
assert_eq!(chain, t.expected_final, "[{}] unexpected final chain", i,);
}
}
#[test]
fn local_chain_disconnect_from() {
struct TestCase {
name: &'static str,
original: LocalChain,
disconnect_from: (u32, BlockHash),
exp_result: Result<ChangeSet, MissingGenesisError>,
exp_final: LocalChain,
}
let test_cases = [
TestCase {
name: "try_replace_genesis_should_fail",
original: local_chain![(0, h!("_"))],
disconnect_from: (0, h!("_")),
exp_result: Err(MissingGenesisError),
exp_final: local_chain![(0, h!("_"))],
},
TestCase {
name: "try_replace_genesis_should_fail_2",
original: local_chain![(0, h!("_")), (2, h!("B")), (3, h!("C"))],
disconnect_from: (0, h!("_")),
exp_result: Err(MissingGenesisError),
exp_final: local_chain![(0, h!("_")), (2, h!("B")), (3, h!("C"))],
},
TestCase {
name: "from_does_not_exist",
original: local_chain![(0, h!("_")), (3, h!("C"))],
disconnect_from: (2, h!("B")),
exp_result: Ok(ChangeSet::default()),
exp_final: local_chain![(0, h!("_")), (3, h!("C"))],
},
TestCase {
name: "from_has_different_blockhash",
original: local_chain![(0, h!("_")), (2, h!("B"))],
disconnect_from: (2, h!("not_B")),
exp_result: Ok(ChangeSet::default()),
exp_final: local_chain![(0, h!("_")), (2, h!("B"))],
},
TestCase {
name: "disconnect_one",
original: local_chain![(0, h!("_")), (2, h!("B"))],
disconnect_from: (2, h!("B")),
exp_result: Ok(ChangeSet::from_iter([(2, None)])),
exp_final: local_chain![(0, h!("_"))],
},
TestCase {
name: "disconnect_three",
original: local_chain![(0, h!("_")), (2, h!("B")), (3, h!("C")), (4, h!("D"))],
disconnect_from: (2, h!("B")),
exp_result: Ok(ChangeSet::from_iter([(2, None), (3, None), (4, None)])),
exp_final: local_chain![(0, h!("_"))],
},
];
for (i, t) in test_cases.into_iter().enumerate() {
println!("Case {}: {}", i, t.name);
let mut chain = t.original;
let result = chain.disconnect_from(t.disconnect_from.into());
assert_eq!(
result, t.exp_result,
"[{}:{}] unexpected changeset result",
i, t.name
);
assert_eq!(
chain, t.exp_final,
"[{}:{}] unexpected final chain",
i, t.name
);
}
}
#[test]
fn checkpoint_from_block_ids() {
struct TestCase<'a> {
name: &'a str,
blocks: &'a [(u32, BlockHash)],
exp_result: Result<(), Option<(u32, BlockHash)>>,
}
let test_cases = [
TestCase {
name: "in_order",
blocks: &[(0, h!("A")), (1, h!("B")), (3, h!("D"))],
exp_result: Ok(()),
},
TestCase {
name: "with_duplicates",
blocks: &[(1, h!("B")), (2, h!("C")), (2, h!("C'"))],
exp_result: Err(Some((2, h!("C")))),
},
TestCase {
name: "not_in_order",
blocks: &[(1, h!("B")), (3, h!("D")), (2, h!("C"))],
exp_result: Err(Some((3, h!("D")))),
},
TestCase {
name: "empty",
blocks: &[],
exp_result: Err(None),
},
TestCase {
name: "single",
blocks: &[(21, h!("million"))],
exp_result: Ok(()),
},
];
for (i, t) in test_cases.into_iter().enumerate() {
println!("running test case {}: '{}'", i, t.name);
let result = CheckPoint::from_block_ids(
t.blocks
.iter()
.map(|&(height, hash)| BlockId { height, hash }),
);
match t.exp_result {
Ok(_) => {
assert!(result.is_ok(), "[{}:{}] should be Ok", i, t.name);
let result_vec = {
let mut v = result
.unwrap()
.into_iter()
.map(|cp| (cp.height(), cp.hash()))
.collect::<Vec<_>>();
v.reverse();
v
};
assert_eq!(
&result_vec, t.blocks,
"[{}:{}] not equal to original block ids",
i, t.name
);
}
Err(exp_last) => {
assert!(result.is_err(), "[{}:{}] should be Err", i, t.name);
let err = result.unwrap_err();
assert_eq!(
err.as_ref()
.map(|last_cp| (last_cp.height(), last_cp.hash())),
exp_last,
"[{}:{}] error's last cp height should be {:?}, got {:?}",
i,
t.name,
exp_last,
err
);
}
}
}
}
#[test]
fn checkpoint_query() {
struct TestCase {
chain: LocalChain,
/// The heights we want to call [`CheckPoint::query`] with, represented as an inclusive
/// range.
///
/// If a [`CheckPoint`] exists at that height, we expect [`CheckPoint::query`] to return
/// it. If not, [`CheckPoint::query`] should return `None`.
query_range: (u32, u32),
}
let test_cases = [
TestCase {
chain: local_chain![(0, h!("_")), (1, h!("A"))],
query_range: (0, 2),
},
TestCase {
chain: local_chain![(0, h!("_")), (2, h!("B")), (3, h!("C"))],
query_range: (0, 3),
},
];
for t in test_cases.into_iter() {
let tip = t.chain.tip();
for h in t.query_range.0..=t.query_range.1 {
let query_result = tip.get(h);
// perform an exhausitive search for the checkpoint at height `h`
let exp_hash = t
.chain
.iter_checkpoints()
.find(|cp| cp.height() == h)
.map(|cp| cp.hash());
match query_result {
Some(cp) => {
assert_eq!(Some(cp.hash()), exp_hash);
assert_eq!(cp.height(), h);
}
None => assert!(exp_hash.is_none()),
}
}
}
}
#[test]
fn checkpoint_insert() {
struct TestCase<'a> {
/// The name of the test.
name: &'a str,
/// The original checkpoint chain to call [`CheckPoint::insert`] on.
chain: &'a [(u32, BlockHash)],
/// The `block_id` to insert.
to_insert: (u32, BlockHash),
/// The expected final checkpoint chain after calling [`CheckPoint::insert`].
exp_final_chain: &'a [(u32, BlockHash)],
}
let test_cases = [
TestCase {
name: "insert_above_tip",
chain: &[(1, h!("a")), (2, h!("b"))],
to_insert: (4, h!("d")),
exp_final_chain: &[(1, h!("a")), (2, h!("b")), (4, h!("d"))],
},
TestCase {
name: "insert_already_exists_expect_no_change",
chain: &[(1, h!("a")), (2, h!("b")), (3, h!("c"))],
to_insert: (2, h!("b")),
exp_final_chain: &[(1, h!("a")), (2, h!("b")), (3, h!("c"))],
},
TestCase {
name: "insert_in_middle",
chain: &[(2, h!("b")), (4, h!("d")), (5, h!("e"))],
to_insert: (3, h!("c")),
exp_final_chain: &[(2, h!("b")), (3, h!("c")), (4, h!("d")), (5, h!("e"))],
},
TestCase {
name: "replace_one",
chain: &[(3, h!("c")), (4, h!("d")), (5, h!("e"))],
to_insert: (5, h!("E")),
exp_final_chain: &[(3, h!("c")), (4, h!("d")), (5, h!("E"))],
},
TestCase {
name: "insert_conflict_should_evict",
chain: &[(3, h!("c")), (4, h!("d")), (5, h!("e")), (6, h!("f"))],
to_insert: (4, h!("D")),
exp_final_chain: &[(3, h!("c")), (4, h!("D"))],
},
];
fn genesis_block() -> impl Iterator<Item = BlockId> {
core::iter::once((0, h!("_"))).map(BlockId::from)
}
for (i, t) in test_cases.into_iter().enumerate() {
println!("Running [{}] '{}'", i, t.name);
let chain = CheckPoint::from_block_ids(
genesis_block().chain(t.chain.iter().copied().map(BlockId::from)),
)
.expect("test formed incorrectly, must construct checkpoint chain");
let exp_final_chain = CheckPoint::from_block_ids(
genesis_block().chain(t.exp_final_chain.iter().copied().map(BlockId::from)),
)
.expect("test formed incorrectly, must construct checkpoint chain");
assert_eq!(
chain.insert(t.to_insert.into()),
exp_final_chain,
"unexpected final chain"
);
}
}
#[test]
fn local_chain_apply_header_connected_to() {
fn header_from_prev_blockhash(prev_blockhash: BlockHash) -> Header {
Header {
version: bitcoin::block::Version::default(),
prev_blockhash,
merkle_root: bitcoin::hash_types::TxMerkleNode::all_zeros(),
time: 0,
bits: bitcoin::CompactTarget::default(),
nonce: 0,
}
}
struct TestCase {
name: &'static str,
chain: LocalChain,
header: Header,
height: u32,
connected_to: BlockId,
exp_result: Result<Vec<(u32, Option<BlockHash>)>, ApplyHeaderError>,
}
let test_cases = [
{
let header = header_from_prev_blockhash(h!("_"));
let hash = header.block_hash();
let height = 1;
let connected_to = BlockId { height, hash };
TestCase {
name: "connected_to_self_header_applied_to_self",
chain: local_chain![(0, h!("_")), (height, hash)],
header,
height,
connected_to,
exp_result: Ok(vec![]),
}
},
{
let prev_hash = h!("A");
let prev_height = 1;
let header = header_from_prev_blockhash(prev_hash);
let hash = header.block_hash();
let height = prev_height + 1;
let connected_to = BlockId {
height: prev_height,
hash: prev_hash,
};
TestCase {
name: "connected_to_prev_header_applied_to_self",
chain: local_chain![(0, h!("_")), (prev_height, prev_hash)],
header,
height,
connected_to,
exp_result: Ok(vec![(height, Some(hash))]),
}
},
{
let header = header_from_prev_blockhash(BlockHash::all_zeros());
let hash = header.block_hash();
let height = 0;
let connected_to = BlockId { height, hash };
TestCase {
name: "genesis_applied_to_self",
chain: local_chain![(0, hash)],
header,
height,
connected_to,
exp_result: Ok(vec![]),
}
},
{
let header = header_from_prev_blockhash(h!("Z"));
let height = 10;
let hash = header.block_hash();
let prev_height = height - 1;
let prev_hash = header.prev_blockhash;
TestCase {
name: "connect_at_connected_to",
chain: local_chain![(0, h!("_")), (2, h!("B")), (3, h!("C"))],
header,
height: 10,
connected_to: BlockId {
height: 3,
hash: h!("C"),
},
exp_result: Ok(vec![(prev_height, Some(prev_hash)), (height, Some(hash))]),
}
},
{
let prev_hash = h!("A");
let prev_height = 1;
let header = header_from_prev_blockhash(prev_hash);
let connected_to = BlockId {
height: prev_height,
hash: h!("not_prev_hash"),
};
TestCase {
name: "inconsistent_prev_hash",
chain: local_chain![(0, h!("_")), (prev_height, h!("not_prev_hash"))],
header,
height: prev_height + 1,
connected_to,
exp_result: Err(ApplyHeaderError::InconsistentBlocks),
}
},
{
let prev_hash = h!("A");
let prev_height = 1;
let header = header_from_prev_blockhash(prev_hash);
let height = prev_height + 1;
let connected_to = BlockId {
height,
hash: h!("not_current_hash"),
};
TestCase {
name: "inconsistent_current_block",
chain: local_chain![(0, h!("_")), (height, h!("not_current_hash"))],
header,
height,
connected_to,
exp_result: Err(ApplyHeaderError::InconsistentBlocks),
}
},
{
let header = header_from_prev_blockhash(h!("B"));
let height = 3;
let connected_to = BlockId {
height: 4,
hash: h!("D"),
};
TestCase {
name: "connected_to_is_greater",
chain: local_chain![(0, h!("_")), (2, h!("B"))],
header,
height,
connected_to,
exp_result: Err(ApplyHeaderError::InconsistentBlocks),
}
},
];
for (i, t) in test_cases.into_iter().enumerate() {
println!("running test case {}: '{}'", i, t.name);
let mut chain = t.chain;
let result = chain.apply_header_connected_to(&t.header, t.height, t.connected_to);
let exp_result = t
.exp_result
.map(|cs| cs.iter().cloned().collect::<ChangeSet>());
assert_eq!(result, exp_result, "[{}:{}] unexpected result", i, t.name);
}
}
fn generate_height_range_bounds(
height_upper_bound: u32,
) -> impl Strategy<Value = (Bound<u32>, Bound<u32>)> {
fn generate_height_bound(height_upper_bound: u32) -> impl Strategy<Value = Bound<u32>> {
prop_oneof![
(0..height_upper_bound).prop_map(Bound::Included),
(0..height_upper_bound).prop_map(Bound::Excluded),
Just(Bound::Unbounded),
]
}
(
generate_height_bound(height_upper_bound),
generate_height_bound(height_upper_bound),
)
}
fn generate_checkpoints(max_height: u32, max_count: usize) -> impl Strategy<Value = CheckPoint> {
proptest::collection::btree_set(1..max_height, 0..max_count).prop_map(|mut heights| {
heights.insert(0); // must have genesis
CheckPoint::from_block_ids(heights.into_iter().map(|height| {
let hash = bitcoin::hashes::Hash::hash(height.to_le_bytes().as_slice());
BlockId { height, hash }
}))
.expect("blocks must be in order as it comes from btreeset")
})
}
proptest! {
#![proptest_config(ProptestConfig {
..Default::default()
})]
/// Ensure that [`CheckPoint::range`] returns the expected checkpoint heights by comparing it
/// against a more primitive approach.
#[test]
fn checkpoint_range(
range in generate_height_range_bounds(21_000),
cp in generate_checkpoints(21_000, 2100)
) {
let exp_heights = cp.iter().map(|cp| cp.height()).filter(|h| range.contains(h)).collect::<Vec<u32>>();
let heights = cp.range(range).map(|cp| cp.height()).collect::<Vec<u32>>();
prop_assert_eq!(heights, exp_heights);
}
}

View File

@ -0,0 +1,124 @@
use bdk_chain::{spk_txout::SpkTxOutIndex, Indexer};
use bitcoin::{
absolute, transaction, Amount, OutPoint, ScriptBuf, SignedAmount, Transaction, TxIn, TxOut,
};
#[test]
fn spk_txout_sent_and_received() {
let spk1 = ScriptBuf::from_hex("001404f1e52ce2bab3423c6a8c63b7cd730d8f12542c").unwrap();
let spk2 = ScriptBuf::from_hex("00142b57404ae14f08c3a0c903feb2af7830605eb00f").unwrap();
let mut index = SpkTxOutIndex::default();
index.insert_spk(0, spk1.clone());
index.insert_spk(1, spk2.clone());
let tx1 = Transaction {
version: transaction::Version::TWO,
lock_time: absolute::LockTime::ZERO,
input: vec![],
output: vec![TxOut {
value: Amount::from_sat(42_000),
script_pubkey: spk1.clone(),
}],
};
assert_eq!(
index.sent_and_received(&tx1, ..),
(Amount::from_sat(0), Amount::from_sat(42_000))
);
assert_eq!(
index.sent_and_received(&tx1, ..1),
(Amount::from_sat(0), Amount::from_sat(42_000))
);
assert_eq!(
index.sent_and_received(&tx1, 1..),
(Amount::from_sat(0), Amount::from_sat(0))
);
assert_eq!(index.net_value(&tx1, ..), SignedAmount::from_sat(42_000));
index.index_tx(&tx1);
assert_eq!(
index.sent_and_received(&tx1, ..),
(Amount::from_sat(0), Amount::from_sat(42_000)),
"shouldn't change after scanning"
);
let tx2 = Transaction {
version: transaction::Version::ONE,
lock_time: absolute::LockTime::ZERO,
input: vec![TxIn {
previous_output: OutPoint {
txid: tx1.compute_txid(),
vout: 0,
},
..Default::default()
}],
output: vec![
TxOut {
value: Amount::from_sat(20_000),
script_pubkey: spk2,
},
TxOut {
script_pubkey: spk1,
value: Amount::from_sat(30_000),
},
],
};
assert_eq!(
index.sent_and_received(&tx2, ..),
(Amount::from_sat(42_000), Amount::from_sat(50_000))
);
assert_eq!(
index.sent_and_received(&tx2, ..1),
(Amount::from_sat(42_000), Amount::from_sat(30_000))
);
assert_eq!(
index.sent_and_received(&tx2, 1..),
(Amount::from_sat(0), Amount::from_sat(20_000))
);
assert_eq!(index.net_value(&tx2, ..), SignedAmount::from_sat(8_000));
}
#[test]
fn mark_used() {
let spk1 = ScriptBuf::from_hex("001404f1e52ce2bab3423c6a8c63b7cd730d8f12542c").unwrap();
let spk2 = ScriptBuf::from_hex("00142b57404ae14f08c3a0c903feb2af7830605eb00f").unwrap();
let mut spk_index = SpkTxOutIndex::default();
spk_index.insert_spk(1, spk1.clone());
spk_index.insert_spk(2, spk2);
assert!(!spk_index.is_used(&1));
spk_index.mark_used(&1);
assert!(spk_index.is_used(&1));
spk_index.unmark_used(&1);
assert!(!spk_index.is_used(&1));
spk_index.mark_used(&1);
assert!(spk_index.is_used(&1));
let tx1 = Transaction {
version: transaction::Version::TWO,
lock_time: absolute::LockTime::ZERO,
input: vec![],
output: vec![TxOut {
value: Amount::from_sat(42_000),
script_pubkey: spk1,
}],
};
spk_index.index_tx(&tx1);
spk_index.unmark_used(&1);
assert!(
spk_index.is_used(&1),
"even though we unmark_used it doesn't matter because there was a tx scanned that used it"
);
}
#[test]
fn unmark_used_does_not_result_in_invalid_representation() {
let mut spk_index = SpkTxOutIndex::default();
assert!(!spk_index.unmark_used(&0));
assert!(!spk_index.unmark_used(&1));
assert!(!spk_index.unmark_used(&2));
assert!(spk_index.unused_spks(..).collect::<Vec<_>>().is_empty());
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,670 @@
#![cfg(feature = "miniscript")]
#[macro_use]
mod common;
use std::collections::{BTreeSet, HashSet};
use bdk_chain::{Balance, BlockId};
use bitcoin::{Amount, OutPoint, ScriptBuf};
use common::*;
#[allow(dead_code)]
struct Scenario<'a> {
/// Name of the test scenario
name: &'a str,
/// Transaction templates
tx_templates: &'a [TxTemplate<'a, BlockId>],
/// Names of txs that must exist in the output of `list_canonical_txs`
exp_chain_txs: HashSet<&'a str>,
/// Outpoints that must exist in the output of `filter_chain_txouts`
exp_chain_txouts: HashSet<(&'a str, u32)>,
/// Outpoints of UTXOs that must exist in the output of `filter_chain_unspents`
exp_unspents: HashSet<(&'a str, u32)>,
/// Expected balances
exp_balance: Balance,
}
/// This test ensures that [`TxGraph`] will reliably filter out irrelevant transactions when
/// presented with multiple conflicting transaction scenarios using the [`TxTemplate`] structure.
/// This test also checks that [`TxGraph::list_canonical_txs`], [`TxGraph::filter_chain_txouts`],
/// [`TxGraph::filter_chain_unspents`], and [`TxGraph::balance`] return correct data.
#[test]
fn test_tx_conflict_handling() {
// Create Local chains
let local_chain = local_chain!(
(0, h!("A")),
(1, h!("B")),
(2, h!("C")),
(3, h!("D")),
(4, h!("E")),
(5, h!("F")),
(6, h!("G"))
);
let chain_tip = local_chain.tip().block_id();
let scenarios = [
Scenario {
name: "coinbase tx cannot be in mempool and be unconfirmed",
tx_templates: &[
TxTemplate {
tx_name: "unconfirmed_coinbase",
inputs: &[TxInTemplate::Coinbase],
outputs: &[TxOutTemplate::new(5000, Some(0))],
..Default::default()
},
TxTemplate {
tx_name: "confirmed_genesis",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(1))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "unconfirmed_conflict",
inputs: &[
TxInTemplate::PrevTx("confirmed_genesis", 0),
TxInTemplate::PrevTx("unconfirmed_coinbase", 0)
],
outputs: &[TxOutTemplate::new(20000, Some(2))],
..Default::default()
},
TxTemplate {
tx_name: "confirmed_conflict",
inputs: &[TxInTemplate::PrevTx("confirmed_genesis", 0)],
outputs: &[TxOutTemplate::new(20000, Some(3))],
anchors: &[block_id!(4, "E")],
..Default::default()
},
],
exp_chain_txs: HashSet::from(["confirmed_genesis", "confirmed_conflict"]),
exp_chain_txouts: HashSet::from([("confirmed_genesis", 0), ("confirmed_conflict", 0)]),
exp_unspents: HashSet::from([("confirmed_conflict", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::ZERO,
untrusted_pending: Amount::ZERO,
confirmed: Amount::from_sat(20000),
},
},
Scenario {
name: "2 unconfirmed txs with same last_seens conflict",
tx_templates: &[
TxTemplate {
tx_name: "tx1",
outputs: &[TxOutTemplate::new(40000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
..Default::default()
},
TxTemplate {
tx_name: "tx_conflict_1",
inputs: &[TxInTemplate::PrevTx("tx1", 0)],
outputs: &[TxOutTemplate::new(20000, Some(2))],
last_seen: Some(300),
..Default::default()
},
TxTemplate {
tx_name: "tx_conflict_2",
inputs: &[TxInTemplate::PrevTx("tx1", 0)],
outputs: &[TxOutTemplate::new(30000, Some(3))],
last_seen: Some(300),
..Default::default()
},
],
// the txgraph is going to pick tx_conflict_2 because of higher lexicographical txid
exp_chain_txs: HashSet::from(["tx1", "tx_conflict_2"]),
exp_chain_txouts: HashSet::from([("tx1", 0), ("tx_conflict_2", 0)]),
exp_unspents: HashSet::from([("tx_conflict_2", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::from_sat(30000),
untrusted_pending: Amount::ZERO,
confirmed: Amount::ZERO,
},
},
Scenario {
name: "2 unconfirmed txs with different last_seens conflict",
tx_templates: &[
TxTemplate {
tx_name: "tx1",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0)), TxOutTemplate::new(10000, Some(1))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "tx_conflict_1",
inputs: &[TxInTemplate::PrevTx("tx1", 0), TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(20000, Some(2))],
last_seen: Some(200),
..Default::default()
},
TxTemplate {
tx_name: "tx_conflict_2",
inputs: &[TxInTemplate::PrevTx("tx1", 0), TxInTemplate::PrevTx("tx1", 1)],
outputs: &[TxOutTemplate::new(30000, Some(3))],
last_seen: Some(300),
..Default::default()
},
],
exp_chain_txs: HashSet::from(["tx1", "tx_conflict_2"]),
exp_chain_txouts: HashSet::from([("tx1", 0), ("tx1", 1), ("tx_conflict_2", 0)]),
exp_unspents: HashSet::from([("tx_conflict_2", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::from_sat(30000),
untrusted_pending: Amount::ZERO,
confirmed: Amount::ZERO,
},
},
Scenario {
name: "3 unconfirmed txs with different last_seens conflict",
tx_templates: &[
TxTemplate {
tx_name: "tx1",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "tx_conflict_1",
inputs: &[TxInTemplate::PrevTx("tx1", 0), TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(20000, Some(1))],
last_seen: Some(200),
..Default::default()
},
TxTemplate {
tx_name: "tx_conflict_2",
inputs: &[TxInTemplate::PrevTx("tx1", 0)],
outputs: &[TxOutTemplate::new(30000, Some(2))],
last_seen: Some(300),
..Default::default()
},
TxTemplate {
tx_name: "tx_conflict_3",
inputs: &[TxInTemplate::PrevTx("tx1", 0)],
outputs: &[TxOutTemplate::new(40000, Some(3))],
last_seen: Some(400),
..Default::default()
},
],
exp_chain_txs: HashSet::from(["tx1", "tx_conflict_3"]),
exp_chain_txouts: HashSet::from([("tx1", 0), ("tx_conflict_3", 0)]),
exp_unspents: HashSet::from([("tx_conflict_3", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::from_sat(40000),
untrusted_pending: Amount::ZERO,
confirmed: Amount::ZERO,
},
},
Scenario {
name: "unconfirmed tx conflicts with tx in orphaned block, orphaned higher last_seen",
tx_templates: &[
TxTemplate {
tx_name: "tx1",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "tx_conflict_1",
inputs: &[TxInTemplate::PrevTx("tx1", 0), TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(20000, Some(1))],
last_seen: Some(200),
..Default::default()
},
TxTemplate {
tx_name: "tx_orphaned_conflict",
inputs: &[TxInTemplate::PrevTx("tx1", 0)],
outputs: &[TxOutTemplate::new(30000, Some(2))],
anchors: &[block_id!(4, "Orphaned Block")],
last_seen: Some(300),
},
],
exp_chain_txs: HashSet::from(["tx1", "tx_orphaned_conflict"]),
exp_chain_txouts: HashSet::from([("tx1", 0), ("tx_orphaned_conflict", 0)]),
exp_unspents: HashSet::from([("tx_orphaned_conflict", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::from_sat(30000),
untrusted_pending: Amount::ZERO,
confirmed: Amount::ZERO,
},
},
Scenario {
name: "unconfirmed tx conflicts with tx in orphaned block, orphaned lower last_seen",
tx_templates: &[
TxTemplate {
tx_name: "tx1",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "tx_conflict_1",
inputs: &[TxInTemplate::PrevTx("tx1", 0), TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(20000, Some(1))],
last_seen: Some(200),
..Default::default()
},
TxTemplate {
tx_name: "tx_orphaned_conflict",
inputs: &[TxInTemplate::PrevTx("tx1", 0)],
outputs: &[TxOutTemplate::new(30000, Some(2))],
anchors: &[block_id!(4, "Orphaned Block")],
last_seen: Some(100),
},
],
exp_chain_txs: HashSet::from(["tx1", "tx_conflict_1"]),
exp_chain_txouts: HashSet::from([("tx1", 0), ("tx_conflict_1", 0)]),
exp_unspents: HashSet::from([("tx_conflict_1", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::from_sat(20000),
untrusted_pending: Amount::ZERO,
confirmed: Amount::ZERO,
},
},
Scenario {
name: "multiple unconfirmed txs conflict with a confirmed tx",
tx_templates: &[
TxTemplate {
tx_name: "tx1",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "tx_conflict_1",
inputs: &[TxInTemplate::PrevTx("tx1", 0), TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(20000, Some(1))],
last_seen: Some(200),
..Default::default()
},
TxTemplate {
tx_name: "tx_conflict_2",
inputs: &[TxInTemplate::PrevTx("tx1", 0)],
outputs: &[TxOutTemplate::new(30000, Some(2))],
last_seen: Some(300),
..Default::default()
},
TxTemplate {
tx_name: "tx_conflict_3",
inputs: &[TxInTemplate::PrevTx("tx1", 0)],
outputs: &[TxOutTemplate::new(40000, Some(3))],
last_seen: Some(400),
..Default::default()
},
TxTemplate {
tx_name: "tx_confirmed_conflict",
inputs: &[TxInTemplate::PrevTx("tx1", 0)],
outputs: &[TxOutTemplate::new(50000, Some(4))],
anchors: &[block_id!(1, "B")],
..Default::default()
},
],
exp_chain_txs: HashSet::from(["tx1", "tx_confirmed_conflict"]),
exp_chain_txouts: HashSet::from([("tx1", 0), ("tx_confirmed_conflict", 0)]),
exp_unspents: HashSet::from([("tx_confirmed_conflict", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::ZERO,
untrusted_pending: Amount::ZERO,
confirmed: Amount::from_sat(50000),
},
},
Scenario {
name: "B and B' spend A and conflict, C spends B, all the transactions are unconfirmed, B' has higher last_seen than B",
tx_templates: &[
TxTemplate {
tx_name: "A",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
last_seen: Some(22),
..Default::default()
},
TxTemplate {
tx_name: "B",
inputs: &[TxInTemplate::PrevTx("A", 0)],
outputs: &[TxOutTemplate::new(20000, Some(1))],
last_seen: Some(23),
..Default::default()
},
TxTemplate {
tx_name: "B'",
inputs: &[TxInTemplate::PrevTx("A", 0)],
outputs: &[TxOutTemplate::new(20000, Some(2))],
last_seen: Some(24),
..Default::default()
},
TxTemplate {
tx_name: "C",
inputs: &[TxInTemplate::PrevTx("B", 0)],
outputs: &[TxOutTemplate::new(30000, Some(3))],
last_seen: Some(25),
..Default::default()
},
],
// A, B, C will appear in the list methods
// This is because B' has a higher last seen than B, but C has a higher
// last seen than B', so B and C are considered canonical
exp_chain_txs: HashSet::from(["A", "B", "C"]),
exp_chain_txouts: HashSet::from([("A", 0), ("B", 0), ("C", 0)]),
exp_unspents: HashSet::from([("C", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::from_sat(30000),
untrusted_pending: Amount::ZERO,
confirmed: Amount::ZERO,
},
},
Scenario {
name: "B and B' spend A and conflict, C spends B, A and B' are in best chain",
tx_templates: &[
TxTemplate {
tx_name: "A",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "B",
inputs: &[TxInTemplate::PrevTx("A", 0)],
outputs: &[TxOutTemplate::new(20000, Some(1))],
..Default::default()
},
TxTemplate {
tx_name: "B'",
inputs: &[TxInTemplate::PrevTx("A", 0)],
outputs: &[TxOutTemplate::new(20000, Some(2))],
anchors: &[block_id!(4, "E")],
..Default::default()
},
TxTemplate {
tx_name: "C",
inputs: &[TxInTemplate::PrevTx("B", 0)],
outputs: &[TxOutTemplate::new(30000, Some(3))],
..Default::default()
},
],
// B and C should not appear in the list methods
exp_chain_txs: HashSet::from(["A", "B'"]),
exp_chain_txouts: HashSet::from([("A", 0), ("B'", 0)]),
exp_unspents: HashSet::from([("B'", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::ZERO,
untrusted_pending: Amount::ZERO,
confirmed: Amount::from_sat(20000),
},
},
Scenario {
name: "B and B' spend A and conflict, C spends B', A and B' are in best chain",
tx_templates: &[
TxTemplate {
tx_name: "A",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "B",
inputs: &[TxInTemplate::PrevTx("A", 0)],
outputs: &[TxOutTemplate::new(20000, Some(1))],
..Default::default()
},
TxTemplate {
tx_name: "B'",
inputs: &[TxInTemplate::PrevTx("A", 0)],
outputs: &[TxOutTemplate::new(20000, Some(2))],
anchors: &[block_id!(4, "E")],
..Default::default()
},
TxTemplate {
tx_name: "C",
inputs: &[TxInTemplate::PrevTx("B'", 0)],
outputs: &[TxOutTemplate::new(30000, Some(3))],
..Default::default()
},
],
// B should not appear in the list methods
exp_chain_txs: HashSet::from(["A", "B'", "C"]),
exp_chain_txouts: HashSet::from([
("A", 0),
("B'", 0),
("C", 0),
]),
exp_unspents: HashSet::from([("C", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::from_sat(30000),
untrusted_pending: Amount::ZERO,
confirmed: Amount::ZERO,
},
},
Scenario {
name: "B and B' spend A and conflict, C spends both B and B', A is in best chain",
tx_templates: &[
TxTemplate {
tx_name: "A",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "B",
inputs: &[TxInTemplate::PrevTx("A", 0), TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(20000, Some(1))],
last_seen: Some(200),
..Default::default()
},
TxTemplate {
tx_name: "B'",
inputs: &[TxInTemplate::PrevTx("A", 0)],
outputs: &[TxOutTemplate::new(30000, Some(2))],
last_seen: Some(300),
..Default::default()
},
TxTemplate {
tx_name: "C",
inputs: &[
TxInTemplate::PrevTx("B", 0),
TxInTemplate::PrevTx("B'", 0),
],
outputs: &[TxOutTemplate::new(20000, Some(3))],
..Default::default()
},
],
// C should not appear in the list methods
exp_chain_txs: HashSet::from(["A", "B'"]),
exp_chain_txouts: HashSet::from([("A", 0), ("B'", 0)]),
exp_unspents: HashSet::from([("B'", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::from_sat(30000),
untrusted_pending: Amount::ZERO,
confirmed: Amount::ZERO,
},
},
Scenario {
name: "B and B' spend A and conflict, B' is confirmed, C spends both B and B', A is in best chain",
tx_templates: &[
TxTemplate {
tx_name: "A",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "B",
inputs: &[TxInTemplate::PrevTx("A", 0), TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(20000, Some(1))],
last_seen: Some(200),
..Default::default()
},
TxTemplate {
tx_name: "B'",
inputs: &[TxInTemplate::PrevTx("A", 0)],
outputs: &[TxOutTemplate::new(50000, Some(4))],
anchors: &[block_id!(1, "B")],
..Default::default()
},
TxTemplate {
tx_name: "C",
inputs: &[
TxInTemplate::PrevTx("B", 0),
TxInTemplate::PrevTx("B'", 0),
],
outputs: &[TxOutTemplate::new(20000, Some(5))],
..Default::default()
},
],
// C should not appear in the list methods
exp_chain_txs: HashSet::from(["A", "B'"]),
exp_chain_txouts: HashSet::from([("A", 0), ("B'", 0)]),
exp_unspents: HashSet::from([("B'", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::ZERO,
untrusted_pending: Amount::ZERO,
confirmed: Amount::from_sat(50000),
},
},
Scenario {
name: "B and B' spend A and conflict, B' is confirmed, C spends both B and B', D spends C, A is in best chain",
tx_templates: &[
TxTemplate {
tx_name: "A",
inputs: &[TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(10000, Some(0))],
anchors: &[block_id!(1, "B")],
last_seen: None,
},
TxTemplate {
tx_name: "B",
inputs: &[TxInTemplate::PrevTx("A", 0), TxInTemplate::Bogus],
outputs: &[TxOutTemplate::new(20000, Some(1))],
last_seen: Some(200),
..Default::default()
},
TxTemplate {
tx_name: "B'",
inputs: &[TxInTemplate::PrevTx("A", 0)],
outputs: &[TxOutTemplate::new(50000, Some(4))],
anchors: &[block_id!(1, "B")],
..Default::default()
},
TxTemplate {
tx_name: "C",
inputs: &[
TxInTemplate::PrevTx("B", 0),
TxInTemplate::PrevTx("B'", 0),
],
outputs: &[TxOutTemplate::new(20000, Some(5))],
..Default::default()
},
TxTemplate {
tx_name: "D",
inputs: &[TxInTemplate::PrevTx("C", 0)],
outputs: &[TxOutTemplate::new(20000, Some(6))],
..Default::default()
},
],
// D should not appear in the list methods
exp_chain_txs: HashSet::from(["A", "B'"]),
exp_chain_txouts: HashSet::from([("A", 0), ("B'", 0)]),
exp_unspents: HashSet::from([("B'", 0)]),
exp_balance: Balance {
immature: Amount::ZERO,
trusted_pending: Amount::ZERO,
untrusted_pending: Amount::ZERO,
confirmed: Amount::from_sat(50000),
},
},
];
for scenario in scenarios {
let (tx_graph, spk_index, exp_tx_ids) = init_graph(scenario.tx_templates.iter());
let txs = tx_graph
.list_canonical_txs(&local_chain, chain_tip)
.map(|tx| tx.tx_node.txid)
.collect::<BTreeSet<_>>();
let exp_txs = scenario
.exp_chain_txs
.iter()
.map(|txid| *exp_tx_ids.get(txid).expect("txid must exist"))
.collect::<BTreeSet<_>>();
assert_eq!(
txs, exp_txs,
"\n[{}] 'list_canonical_txs' failed",
scenario.name
);
let txouts = tx_graph
.filter_chain_txouts(
&local_chain,
chain_tip,
spk_index.outpoints().iter().cloned(),
)
.map(|(_, full_txout)| full_txout.outpoint)
.collect::<BTreeSet<_>>();
let exp_txouts = scenario
.exp_chain_txouts
.iter()
.map(|(txid, vout)| OutPoint {
txid: *exp_tx_ids.get(txid).expect("txid must exist"),
vout: *vout,
})
.collect::<BTreeSet<_>>();
assert_eq!(
txouts, exp_txouts,
"\n[{}] 'filter_chain_txouts' failed",
scenario.name
);
let utxos = tx_graph
.filter_chain_unspents(
&local_chain,
chain_tip,
spk_index.outpoints().iter().cloned(),
)
.map(|(_, full_txout)| full_txout.outpoint)
.collect::<BTreeSet<_>>();
let exp_utxos = scenario
.exp_unspents
.iter()
.map(|(txid, vout)| OutPoint {
txid: *exp_tx_ids.get(txid).expect("txid must exist"),
vout: *vout,
})
.collect::<BTreeSet<_>>();
assert_eq!(
utxos, exp_utxos,
"\n[{}] 'filter_chain_unspents' failed",
scenario.name
);
let balance = tx_graph.balance(
&local_chain,
chain_tip,
spk_index.outpoints().iter().cloned(),
|_, spk: ScriptBuf| spk_index.index_of_spk(spk).is_some(),
);
assert_eq!(
balance, scenario.exp_balance,
"\n[{}] 'balance' failed",
scenario.name
);
}
}

View File

@ -0,0 +1,20 @@
[package]
name = "bdk_electrum"
version = "0.16.0"
edition = "2021"
homepage = "https://bitcoindevkit.org"
repository = "https://github.com/bitcoindevkit/bdk"
documentation = "https://docs.rs/bdk_electrum"
description = "Fetch data from electrum in the form BDK accepts"
license = "MIT OR Apache-2.0"
readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bdk_chain = { path = "../chain", version = "0.17.0" }
electrum-client = { version = "0.20" }
#rustls = { version = "=0.21.1", optional = true, features = ["dangerous_configuration"] }
[dev-dependencies]
bdk_testenv = { path = "../testenv", default-features = false }

View File

@ -0,0 +1,7 @@
# BDK Electrum
BDK Electrum extends [`electrum-client`] to update [`bdk_chain`] structures
from an Electrum server.
[`electrum-client`]: https://docs.rs/electrum-client/
[`bdk_chain`]: https://docs.rs/bdk-chain/

View File

@ -0,0 +1,491 @@
use bdk_chain::{
bitcoin::{block::Header, BlockHash, OutPoint, ScriptBuf, Transaction, Txid},
collections::{BTreeMap, HashMap},
local_chain::CheckPoint,
spk_client::{FullScanRequest, FullScanResult, SyncRequest, SyncResult},
tx_graph::TxGraph,
Anchor, BlockId, ConfirmationBlockTime,
};
use electrum_client::{ElectrumApi, Error, HeaderNotification};
use std::{
collections::BTreeSet,
sync::{Arc, Mutex},
};
/// We include a chain suffix of a certain length for the purpose of robustness.
const CHAIN_SUFFIX_LENGTH: u32 = 8;
/// Wrapper around an [`electrum_client::ElectrumApi`] which includes an internal in-memory
/// transaction cache to avoid re-fetching already downloaded transactions.
#[derive(Debug)]
pub struct BdkElectrumClient<E> {
/// The internal [`electrum_client::ElectrumApi`]
pub inner: E,
/// The transaction cache
tx_cache: Mutex<HashMap<Txid, Arc<Transaction>>>,
/// The header cache
block_header_cache: Mutex<HashMap<u32, Header>>,
}
impl<E: ElectrumApi> BdkElectrumClient<E> {
/// Creates a new bdk client from a [`electrum_client::ElectrumApi`]
pub fn new(client: E) -> Self {
Self {
inner: client,
tx_cache: Default::default(),
block_header_cache: Default::default(),
}
}
/// Inserts transactions into the transaction cache so that the client will not fetch these
/// transactions.
pub fn populate_tx_cache<A>(&self, tx_graph: impl AsRef<TxGraph<A>>) {
let txs = tx_graph
.as_ref()
.full_txs()
.map(|tx_node| (tx_node.txid, tx_node.tx));
let mut tx_cache = self.tx_cache.lock().unwrap();
for (txid, tx) in txs {
tx_cache.insert(txid, tx);
}
}
/// Fetch transaction of given `txid`.
///
/// If it hits the cache it will return the cached version and avoid making the request.
pub fn fetch_tx(&self, txid: Txid) -> Result<Arc<Transaction>, Error> {
let tx_cache = self.tx_cache.lock().unwrap();
if let Some(tx) = tx_cache.get(&txid) {
return Ok(Arc::clone(tx));
}
drop(tx_cache);
let tx = Arc::new(self.inner.transaction_get(&txid)?);
self.tx_cache.lock().unwrap().insert(txid, Arc::clone(&tx));
Ok(tx)
}
/// Fetch block header of given `height`.
///
/// If it hits the cache it will return the cached version and avoid making the request.
fn fetch_header(&self, height: u32) -> Result<Header, Error> {
let block_header_cache = self.block_header_cache.lock().unwrap();
if let Some(header) = block_header_cache.get(&height) {
return Ok(*header);
}
drop(block_header_cache);
self.update_header(height)
}
/// Update a block header at given `height`. Returns the updated header.
fn update_header(&self, height: u32) -> Result<Header, Error> {
let header = self.inner.block_header(height as usize)?;
self.block_header_cache
.lock()
.unwrap()
.insert(height, header);
Ok(header)
}
/// Broadcasts a transaction to the network.
///
/// This is a re-export of [`ElectrumApi::transaction_broadcast`].
pub fn transaction_broadcast(&self, tx: &Transaction) -> Result<Txid, Error> {
self.inner.transaction_broadcast(tx)
}
/// Full scan the keychain scripts specified with the blockchain (via an Electrum client) and
/// returns updates for [`bdk_chain`] data structures.
///
/// - `request`: struct with data required to perform a spk-based blockchain client full scan,
/// see [`FullScanRequest`]
/// - `stop_gap`: the full scan for each keychain stops after a gap of script pubkeys with no
/// associated transactions
/// - `batch_size`: specifies the max number of script pubkeys to request for in a single batch
/// request
/// - `fetch_prev_txouts`: specifies whether or not we want previous `TxOut`s for fee
pub fn full_scan<K: Ord + Clone>(
&self,
request: FullScanRequest<K>,
stop_gap: usize,
batch_size: usize,
fetch_prev_txouts: bool,
) -> Result<FullScanResult<K>, Error> {
let (tip, latest_blocks) =
fetch_tip_and_latest_blocks(&self.inner, request.chain_tip.clone())?;
let mut graph_update = TxGraph::<ConfirmationBlockTime>::default();
let mut last_active_indices = BTreeMap::<K, u32>::new();
for (keychain, spks) in request.spks_by_keychain {
if let Some(last_active_index) =
self.populate_with_spks(&mut graph_update, spks, stop_gap, batch_size)?
{
last_active_indices.insert(keychain, last_active_index);
}
}
let chain_update = chain_update(tip, &latest_blocks, graph_update.all_anchors())?;
// Fetch previous `TxOut`s for fee calculation if flag is enabled.
if fetch_prev_txouts {
self.fetch_prev_txout(&mut graph_update)?;
}
Ok(FullScanResult {
graph_update,
chain_update,
last_active_indices,
})
}
/// Sync a set of scripts with the blockchain (via an Electrum client) for the data specified
/// and returns updates for [`bdk_chain`] data structures.
///
/// - `request`: struct with data required to perform a spk-based blockchain client sync,
/// see [`SyncRequest`]
/// - `batch_size`: specifies the max number of script pubkeys to request for in a single batch
/// request
/// - `fetch_prev_txouts`: specifies whether or not we want previous `TxOut`s for fee
/// calculation
///
/// If the scripts to sync are unknown, such as when restoring or importing a keychain that
/// may include scripts that have been used, use [`full_scan`] with the keychain.
///
/// [`full_scan`]: Self::full_scan
pub fn sync(
&self,
request: SyncRequest,
batch_size: usize,
fetch_prev_txouts: bool,
) -> Result<SyncResult, Error> {
let full_scan_req = FullScanRequest::from_chain_tip(request.chain_tip.clone())
.set_spks_for_keychain((), request.spks.enumerate().map(|(i, spk)| (i as u32, spk)));
let mut full_scan_res = self.full_scan(full_scan_req, usize::MAX, batch_size, false)?;
let (tip, latest_blocks) =
fetch_tip_and_latest_blocks(&self.inner, request.chain_tip.clone())?;
self.populate_with_txids(&mut full_scan_res.graph_update, request.txids)?;
self.populate_with_outpoints(&mut full_scan_res.graph_update, request.outpoints)?;
let chain_update = chain_update(
tip,
&latest_blocks,
full_scan_res.graph_update.all_anchors(),
)?;
// Fetch previous `TxOut`s for fee calculation if flag is enabled.
if fetch_prev_txouts {
self.fetch_prev_txout(&mut full_scan_res.graph_update)?;
}
Ok(SyncResult {
chain_update,
graph_update: full_scan_res.graph_update,
})
}
/// Populate the `graph_update` with transactions/anchors associated with the given `spks`.
///
/// Transactions that contains an output with requested spk, or spends form an output with
/// requested spk will be added to `graph_update`. Anchors of the aforementioned transactions are
/// also included.
fn populate_with_spks(
&self,
graph_update: &mut TxGraph<ConfirmationBlockTime>,
mut spks: impl Iterator<Item = (u32, ScriptBuf)>,
stop_gap: usize,
batch_size: usize,
) -> Result<Option<u32>, Error> {
let mut unused_spk_count = 0_usize;
let mut last_active_index = Option::<u32>::None;
loop {
let spks = (0..batch_size)
.map_while(|_| spks.next())
.collect::<Vec<_>>();
if spks.is_empty() {
return Ok(last_active_index);
}
let spk_histories = self
.inner
.batch_script_get_history(spks.iter().map(|(_, s)| s.as_script()))?;
for ((spk_index, _spk), spk_history) in spks.into_iter().zip(spk_histories) {
if spk_history.is_empty() {
unused_spk_count = unused_spk_count.saturating_add(1);
if unused_spk_count >= stop_gap {
return Ok(last_active_index);
}
continue;
} else {
last_active_index = Some(spk_index);
unused_spk_count = 0;
}
for tx_res in spk_history {
let _ = graph_update.insert_tx(self.fetch_tx(tx_res.tx_hash)?);
self.validate_merkle_for_anchor(graph_update, tx_res.tx_hash, tx_res.height)?;
}
}
}
}
/// Populate the `graph_update` with associated transactions/anchors of `outpoints`.
///
/// Transactions in which the outpoint resides, and transactions that spend from the outpoint are
/// included. Anchors of the aforementioned transactions are included.
fn populate_with_outpoints(
&self,
graph_update: &mut TxGraph<ConfirmationBlockTime>,
outpoints: impl IntoIterator<Item = OutPoint>,
) -> Result<(), Error> {
for outpoint in outpoints {
let op_txid = outpoint.txid;
let op_tx = self.fetch_tx(op_txid)?;
let op_txout = match op_tx.output.get(outpoint.vout as usize) {
Some(txout) => txout,
None => continue,
};
debug_assert_eq!(op_tx.compute_txid(), op_txid);
// attempt to find the following transactions (alongside their chain positions), and
// add to our sparsechain `update`:
let mut has_residing = false; // tx in which the outpoint resides
let mut has_spending = false; // tx that spends the outpoint
for res in self.inner.script_get_history(&op_txout.script_pubkey)? {
if has_residing && has_spending {
break;
}
if !has_residing && res.tx_hash == op_txid {
has_residing = true;
let _ = graph_update.insert_tx(Arc::clone(&op_tx));
self.validate_merkle_for_anchor(graph_update, res.tx_hash, res.height)?;
}
if !has_spending && res.tx_hash != op_txid {
let res_tx = self.fetch_tx(res.tx_hash)?;
// we exclude txs/anchors that do not spend our specified outpoint(s)
has_spending = res_tx
.input
.iter()
.any(|txin| txin.previous_output == outpoint);
if !has_spending {
continue;
}
let _ = graph_update.insert_tx(Arc::clone(&res_tx));
self.validate_merkle_for_anchor(graph_update, res.tx_hash, res.height)?;
}
}
}
Ok(())
}
/// Populate the `graph_update` with transactions/anchors of the provided `txids`.
fn populate_with_txids(
&self,
graph_update: &mut TxGraph<ConfirmationBlockTime>,
txids: impl IntoIterator<Item = Txid>,
) -> Result<(), Error> {
for txid in txids {
let tx = match self.fetch_tx(txid) {
Ok(tx) => tx,
Err(electrum_client::Error::Protocol(_)) => continue,
Err(other_err) => return Err(other_err),
};
let spk = tx
.output
.first()
.map(|txo| &txo.script_pubkey)
.expect("tx must have an output");
// because of restrictions of the Electrum API, we have to use the `script_get_history`
// call to get confirmation status of our transaction
if let Some(r) = self
.inner
.script_get_history(spk)?
.into_iter()
.find(|r| r.tx_hash == txid)
{
self.validate_merkle_for_anchor(graph_update, txid, r.height)?;
}
let _ = graph_update.insert_tx(tx);
}
Ok(())
}
// Helper function which checks if a transaction is confirmed by validating the merkle proof.
// An anchor is inserted if the transaction is validated to be in a confirmed block.
fn validate_merkle_for_anchor(
&self,
graph_update: &mut TxGraph<ConfirmationBlockTime>,
txid: Txid,
confirmation_height: i32,
) -> Result<(), Error> {
if let Ok(merkle_res) = self
.inner
.transaction_get_merkle(&txid, confirmation_height as usize)
{
let mut header = self.fetch_header(merkle_res.block_height as u32)?;
let mut is_confirmed_tx = electrum_client::utils::validate_merkle_proof(
&txid,
&header.merkle_root,
&merkle_res,
);
// Merkle validation will fail if the header in `block_header_cache` is outdated, so we
// want to check if there is a new header and validate against the new one.
if !is_confirmed_tx {
header = self.update_header(merkle_res.block_height as u32)?;
is_confirmed_tx = electrum_client::utils::validate_merkle_proof(
&txid,
&header.merkle_root,
&merkle_res,
);
}
if is_confirmed_tx {
let _ = graph_update.insert_anchor(
txid,
ConfirmationBlockTime {
confirmation_time: header.time as u64,
block_id: BlockId {
height: merkle_res.block_height as u32,
hash: header.block_hash(),
},
},
);
}
}
Ok(())
}
// Helper function which fetches the `TxOut`s of our relevant transactions' previous transactions,
// which we do not have by default. This data is needed to calculate the transaction fee.
fn fetch_prev_txout(
&self,
graph_update: &mut TxGraph<ConfirmationBlockTime>,
) -> Result<(), Error> {
let full_txs: Vec<Arc<Transaction>> =
graph_update.full_txs().map(|tx_node| tx_node.tx).collect();
for tx in full_txs {
for vin in &tx.input {
let outpoint = vin.previous_output;
let vout = outpoint.vout;
let prev_tx = self.fetch_tx(outpoint.txid)?;
let txout = prev_tx.output[vout as usize].clone();
let _ = graph_update.insert_txout(outpoint, txout);
}
}
Ok(())
}
}
/// Return a [`CheckPoint`] of the latest tip, that connects with `prev_tip`. The latest blocks are
/// fetched to construct checkpoint updates with the proper [`BlockHash`] in case of re-org.
fn fetch_tip_and_latest_blocks(
client: &impl ElectrumApi,
prev_tip: CheckPoint,
) -> Result<(CheckPoint, BTreeMap<u32, BlockHash>), Error> {
let HeaderNotification { height, .. } = client.block_headers_subscribe()?;
let new_tip_height = height as u32;
// If electrum returns a tip height that is lower than our previous tip, then checkpoints do
// not need updating. We just return the previous tip and use that as the point of agreement.
if new_tip_height < prev_tip.height() {
return Ok((prev_tip, BTreeMap::new()));
}
// Atomically fetch the latest `CHAIN_SUFFIX_LENGTH` count of blocks from Electrum. We use this
// to construct our checkpoint update.
let mut new_blocks = {
let start_height = new_tip_height.saturating_sub(CHAIN_SUFFIX_LENGTH - 1);
let hashes = client
.block_headers(start_height as _, CHAIN_SUFFIX_LENGTH as _)?
.headers
.into_iter()
.map(|h| h.block_hash());
(start_height..).zip(hashes).collect::<BTreeMap<u32, _>>()
};
// Find the "point of agreement" (if any).
let agreement_cp = {
let mut agreement_cp = Option::<CheckPoint>::None;
for cp in prev_tip.iter() {
let cp_block = cp.block_id();
let hash = match new_blocks.get(&cp_block.height) {
Some(&hash) => hash,
None => {
assert!(
new_tip_height >= cp_block.height,
"already checked that electrum's tip cannot be smaller"
);
let hash = client.block_header(cp_block.height as _)?.block_hash();
new_blocks.insert(cp_block.height, hash);
hash
}
};
if hash == cp_block.hash {
agreement_cp = Some(cp);
break;
}
}
agreement_cp
};
let agreement_height = agreement_cp.as_ref().map(CheckPoint::height);
let new_tip = new_blocks
.iter()
// Prune `new_blocks` to only include blocks that are actually new.
.filter(|(height, _)| Some(*<&u32>::clone(height)) > agreement_height)
.map(|(height, hash)| BlockId {
height: *height,
hash: *hash,
})
.fold(agreement_cp, |prev_cp, block| {
Some(match prev_cp {
Some(cp) => cp.push(block).expect("must extend checkpoint"),
None => CheckPoint::new(block),
})
})
.expect("must have at least one checkpoint");
Ok((new_tip, new_blocks))
}
// Add a corresponding checkpoint per anchor height if it does not yet exist. Checkpoints should not
// surpass `latest_blocks`.
fn chain_update<A: Anchor>(
mut tip: CheckPoint,
latest_blocks: &BTreeMap<u32, BlockHash>,
anchors: &BTreeSet<(A, Txid)>,
) -> Result<CheckPoint, Error> {
for anchor in anchors {
let height = anchor.0.anchor_block().height;
// Checkpoint uses the `BlockHash` from `latest_blocks` so that the hash will be consistent
// in case of a re-org.
if tip.get(height).is_none() && height <= tip.height() {
let hash = match latest_blocks.get(&height) {
Some(&hash) => hash,
None => anchor.0.anchor_block().hash,
};
tip = tip.insert(BlockId { hash, height });
}
}
Ok(tip)
}

View File

@ -0,0 +1,22 @@
//! This crate is used for updating structures of [`bdk_chain`] with data from an Electrum server.
//!
//! The two primary methods are [`BdkElectrumClient::sync`] and [`BdkElectrumClient::full_scan`]. In most cases
//! [`BdkElectrumClient::sync`] is used to sync the transaction histories of scripts that the application
//! cares about, for example the scripts for all the receive addresses of a Wallet's keychain that it
//! has shown a user. [`BdkElectrumClient::full_scan`] is meant to be used when importing or restoring a
//! keychain where the range of possibly used scripts is not known. In this case it is necessary to
//! scan all keychain scripts until a number (the "stop gap") of unused scripts is discovered. For a
//! sync or full scan the user receives relevant blockchain data and output updates for
//! [`bdk_chain`].
//!
//! Refer to [`example_electrum`] for a complete example.
//!
//! [`example_electrum`]: https://github.com/bitcoindevkit/bdk/tree/master/example-crates/example_electrum
#![warn(missing_docs)]
mod bdk_electrum_client;
pub use bdk_electrum_client::*;
pub use bdk_chain;
pub use electrum_client;

View File

@ -0,0 +1,437 @@
use bdk_chain::{
bitcoin::{hashes::Hash, Address, Amount, ScriptBuf, Txid, WScriptHash},
local_chain::LocalChain,
spk_client::{FullScanRequest, SyncRequest},
spk_txout::SpkTxOutIndex,
Balance, ConfirmationBlockTime, IndexedTxGraph,
};
use bdk_electrum::BdkElectrumClient;
use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv};
use std::collections::{BTreeSet, HashSet};
use std::str::FromStr;
fn get_balance(
recv_chain: &LocalChain,
recv_graph: &IndexedTxGraph<ConfirmationBlockTime, SpkTxOutIndex<()>>,
) -> anyhow::Result<Balance> {
let chain_tip = recv_chain.tip().block_id();
let outpoints = recv_graph.index.outpoints().clone();
let balance = recv_graph
.graph()
.balance(recv_chain, chain_tip, outpoints, |_, _| true);
Ok(balance)
}
#[test]
pub fn test_update_tx_graph_without_keychain() -> anyhow::Result<()> {
let env = TestEnv::new()?;
let electrum_client = electrum_client::Client::new(env.electrsd.electrum_url.as_str())?;
let client = BdkElectrumClient::new(electrum_client);
let receive_address0 =
Address::from_str("bcrt1qc6fweuf4xjvz4x3gx3t9e0fh4hvqyu2qw4wvxm")?.assume_checked();
let receive_address1 =
Address::from_str("bcrt1qfjg5lv3dvc9az8patec8fjddrs4aqtauadnagr")?.assume_checked();
let misc_spks = [
receive_address0.script_pubkey(),
receive_address1.script_pubkey(),
];
let _block_hashes = env.mine_blocks(101, None)?;
let txid1 = env.bitcoind.client.send_to_address(
&receive_address1,
Amount::from_sat(10000),
None,
None,
None,
None,
Some(1),
None,
)?;
let txid2 = env.bitcoind.client.send_to_address(
&receive_address0,
Amount::from_sat(20000),
None,
None,
None,
None,
Some(1),
None,
)?;
env.mine_blocks(1, None)?;
env.wait_until_electrum_sees_block()?;
// use a full checkpoint linked list (since this is not what we are testing)
let cp_tip = env.make_checkpoint_tip();
let sync_update = {
let request = SyncRequest::from_chain_tip(cp_tip.clone()).set_spks(misc_spks);
client.sync(request, 1, true)?
};
assert!(
{
let update_cps = sync_update
.chain_update
.iter()
.map(|cp| cp.block_id())
.collect::<BTreeSet<_>>();
let superset_cps = cp_tip
.iter()
.map(|cp| cp.block_id())
.collect::<BTreeSet<_>>();
superset_cps.is_superset(&update_cps)
},
"update should not alter original checkpoint tip since we already started with all checkpoints",
);
let graph_update = sync_update.graph_update;
// Check to see if we have the floating txouts available from our two created transactions'
// previous outputs in order to calculate transaction fees.
for tx in graph_update.full_txs() {
// Retrieve the calculated fee from `TxGraph`, which will panic if we do not have the
// floating txouts available from the transactions' previous outputs.
let fee = graph_update.calculate_fee(&tx.tx).expect("Fee must exist");
// Retrieve the fee in the transaction data from `bitcoind`.
let tx_fee = env
.bitcoind
.client
.get_transaction(&tx.txid, None)
.expect("Tx must exist")
.fee
.expect("Fee must exist")
.abs()
.to_unsigned()
.expect("valid `Amount`");
// Check that the calculated fee matches the fee from the transaction data.
assert_eq!(fee, tx_fee);
}
let mut graph_update_txids: Vec<Txid> = graph_update.full_txs().map(|tx| tx.txid).collect();
graph_update_txids.sort();
let mut expected_txids = vec![txid1, txid2];
expected_txids.sort();
assert_eq!(graph_update_txids, expected_txids);
Ok(())
}
/// Test the bounds of the address scan depending on the `stop_gap`.
#[test]
pub fn test_update_tx_graph_stop_gap() -> anyhow::Result<()> {
let env = TestEnv::new()?;
let electrum_client = electrum_client::Client::new(env.electrsd.electrum_url.as_str())?;
let client = BdkElectrumClient::new(electrum_client);
let _block_hashes = env.mine_blocks(101, None)?;
// Now let's test the gap limit. First of all get a chain of 10 addresses.
let addresses = [
"bcrt1qj9f7r8r3p2y0sqf4r3r62qysmkuh0fzep473d2ar7rcz64wqvhssjgf0z4",
"bcrt1qmm5t0ch7vh2hryx9ctq3mswexcugqe4atkpkl2tetm8merqkthas3w7q30",
"bcrt1qut9p7ej7l7lhyvekj28xknn8gnugtym4d5qvnp5shrsr4nksmfqsmyn87g",
"bcrt1qqz0xtn3m235p2k96f5wa2dqukg6shxn9n3txe8arlrhjh5p744hsd957ww",
"bcrt1q9c0t62a8l6wfytmf2t9lfj35avadk3mm8g4p3l84tp6rl66m48sqrme7wu",
"bcrt1qkmh8yrk2v47cklt8dytk8f3ammcwa4q7dzattedzfhqzvfwwgyzsg59zrh",
"bcrt1qvgrsrzy07gjkkfr5luplt0azxtfwmwq5t62gum5jr7zwcvep2acs8hhnp2",
"bcrt1qw57edarcg50ansq8mk3guyrk78rk0fwvrds5xvqeupteu848zayq549av8",
"bcrt1qvtve5ekf6e5kzs68knvnt2phfw6a0yjqrlgat392m6zt9jsvyxhqfx67ef",
"bcrt1qw03ddumfs9z0kcu76ln7jrjfdwam20qtffmkcral3qtza90sp9kqm787uk",
];
let addresses: Vec<_> = addresses
.into_iter()
.map(|s| Address::from_str(s).unwrap().assume_checked())
.collect();
let spks: Vec<_> = addresses
.iter()
.enumerate()
.map(|(i, addr)| (i as u32, addr.script_pubkey()))
.collect();
// Then receive coins on the 4th address.
let txid_4th_addr = env.bitcoind.client.send_to_address(
&addresses[3],
Amount::from_sat(10000),
None,
None,
None,
None,
Some(1),
None,
)?;
env.mine_blocks(1, None)?;
env.wait_until_electrum_sees_block()?;
// use a full checkpoint linked list (since this is not what we are testing)
let cp_tip = env.make_checkpoint_tip();
// A scan with a stop_gap of 3 won't find the transaction, but a scan with a gap limit of 4
// will.
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 3, 1, false)?
};
assert!(full_scan_update.graph_update.full_txs().next().is_none());
assert!(full_scan_update.last_active_indices.is_empty());
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 4, 1, false)?
};
assert_eq!(
full_scan_update
.graph_update
.full_txs()
.next()
.unwrap()
.txid,
txid_4th_addr
);
assert_eq!(full_scan_update.last_active_indices[&0], 3);
// Now receive a coin on the last address.
let txid_last_addr = env.bitcoind.client.send_to_address(
&addresses[addresses.len() - 1],
Amount::from_sat(10000),
None,
None,
None,
None,
Some(1),
None,
)?;
env.mine_blocks(1, None)?;
env.wait_until_electrum_sees_block()?;
// A scan with gap limit 5 won't find the second transaction, but a scan with gap limit 6 will.
// The last active indice won't be updated in the first case but will in the second one.
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 5, 1, false)?
};
let txs: HashSet<_> = full_scan_update
.graph_update
.full_txs()
.map(|tx| tx.txid)
.collect();
assert_eq!(txs.len(), 1);
assert!(txs.contains(&txid_4th_addr));
assert_eq!(full_scan_update.last_active_indices[&0], 3);
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 6, 1, false)?
};
let txs: HashSet<_> = full_scan_update
.graph_update
.full_txs()
.map(|tx| tx.txid)
.collect();
assert_eq!(txs.len(), 2);
assert!(txs.contains(&txid_4th_addr) && txs.contains(&txid_last_addr));
assert_eq!(full_scan_update.last_active_indices[&0], 9);
Ok(())
}
/// Ensure that [`ElectrumExt`] can sync properly.
///
/// 1. Mine 101 blocks.
/// 2. Send a tx.
/// 3. Mine extra block to confirm sent tx.
/// 4. Check [`Balance`] to ensure tx is confirmed.
#[test]
fn scan_detects_confirmed_tx() -> anyhow::Result<()> {
const SEND_AMOUNT: Amount = Amount::from_sat(10_000);
let env = TestEnv::new()?;
let electrum_client = electrum_client::Client::new(env.electrsd.electrum_url.as_str())?;
let client = BdkElectrumClient::new(electrum_client);
// Setup addresses.
let addr_to_mine = env
.bitcoind
.client
.get_new_address(None, None)?
.assume_checked();
let spk_to_track = ScriptBuf::new_p2wsh(&WScriptHash::all_zeros());
let addr_to_track = Address::from_script(&spk_to_track, bdk_chain::bitcoin::Network::Regtest)?;
// Setup receiver.
let (mut recv_chain, _) = LocalChain::from_genesis_hash(env.bitcoind.client.get_block_hash(0)?);
let mut recv_graph = IndexedTxGraph::<ConfirmationBlockTime, _>::new({
let mut recv_index = SpkTxOutIndex::default();
recv_index.insert_spk((), spk_to_track.clone());
recv_index
});
// Mine some blocks.
env.mine_blocks(101, Some(addr_to_mine))?;
// Create transaction that is tracked by our receiver.
env.send(&addr_to_track, SEND_AMOUNT)?;
// Mine a block to confirm sent tx.
env.mine_blocks(1, None)?;
// Sync up to tip.
env.wait_until_electrum_sees_block()?;
let update = client.sync(
SyncRequest::from_chain_tip(recv_chain.tip()).chain_spks(core::iter::once(spk_to_track)),
5,
true,
)?;
let _ = recv_chain
.apply_update(update.chain_update)
.map_err(|err| anyhow::anyhow!("LocalChain update error: {:?}", err))?;
let _ = recv_graph.apply_update(update.graph_update);
// Check to see if tx is confirmed.
assert_eq!(
get_balance(&recv_chain, &recv_graph)?,
Balance {
confirmed: SEND_AMOUNT,
..Balance::default()
},
);
for tx in recv_graph.graph().full_txs() {
// Retrieve the calculated fee from `TxGraph`, which will panic if we do not have the
// floating txouts available from the transaction's previous outputs.
let fee = recv_graph
.graph()
.calculate_fee(&tx.tx)
.expect("fee must exist");
// Retrieve the fee in the transaction data from `bitcoind`.
let tx_fee = env
.bitcoind
.client
.get_transaction(&tx.txid, None)
.expect("Tx must exist")
.fee
.expect("Fee must exist")
.abs()
.to_unsigned()
.expect("valid `Amount`");
// Check that the calculated fee matches the fee from the transaction data.
assert_eq!(fee, tx_fee);
}
Ok(())
}
/// Ensure that confirmed txs that are reorged become unconfirmed.
///
/// 1. Mine 101 blocks.
/// 2. Mine 8 blocks with a confirmed tx in each.
/// 3. Perform 8 separate reorgs on each block with a confirmed tx.
/// 4. Check [`Balance`] after each reorg to ensure unconfirmed amount is correct.
#[test]
fn tx_can_become_unconfirmed_after_reorg() -> anyhow::Result<()> {
const REORG_COUNT: usize = 8;
const SEND_AMOUNT: Amount = Amount::from_sat(10_000);
let env = TestEnv::new()?;
let electrum_client = electrum_client::Client::new(env.electrsd.electrum_url.as_str())?;
let client = BdkElectrumClient::new(electrum_client);
// Setup addresses.
let addr_to_mine = env
.bitcoind
.client
.get_new_address(None, None)?
.assume_checked();
let spk_to_track = ScriptBuf::new_p2wsh(&WScriptHash::all_zeros());
let addr_to_track = Address::from_script(&spk_to_track, bdk_chain::bitcoin::Network::Regtest)?;
// Setup receiver.
let (mut recv_chain, _) = LocalChain::from_genesis_hash(env.bitcoind.client.get_block_hash(0)?);
let mut recv_graph = IndexedTxGraph::<ConfirmationBlockTime, _>::new({
let mut recv_index = SpkTxOutIndex::default();
recv_index.insert_spk((), spk_to_track.clone());
recv_index
});
// Mine some blocks.
env.mine_blocks(101, Some(addr_to_mine))?;
// Create transactions that are tracked by our receiver.
let mut txids = vec![];
let mut hashes = vec![];
for _ in 0..REORG_COUNT {
txids.push(env.send(&addr_to_track, SEND_AMOUNT)?);
hashes.extend(env.mine_blocks(1, None)?);
}
// Sync up to tip.
env.wait_until_electrum_sees_block()?;
let update = client.sync(
SyncRequest::from_chain_tip(recv_chain.tip()).chain_spks([spk_to_track.clone()]),
5,
false,
)?;
let _ = recv_chain
.apply_update(update.chain_update)
.map_err(|err| anyhow::anyhow!("LocalChain update error: {:?}", err))?;
let _ = recv_graph.apply_update(update.graph_update.clone());
// Retain a snapshot of all anchors before reorg process.
let initial_anchors = update.graph_update.all_anchors();
let anchors: Vec<_> = initial_anchors.iter().cloned().collect();
assert_eq!(anchors.len(), REORG_COUNT);
for i in 0..REORG_COUNT {
let (anchor, txid) = anchors[i];
assert_eq!(anchor.block_id.hash, hashes[i]);
assert_eq!(txid, txids[i]);
}
// Check if initial balance is correct.
assert_eq!(
get_balance(&recv_chain, &recv_graph)?,
Balance {
confirmed: SEND_AMOUNT * REORG_COUNT as u64,
..Balance::default()
},
"initial balance must be correct",
);
// Perform reorgs with different depths.
for depth in 1..=REORG_COUNT {
env.reorg_empty_blocks(depth)?;
env.wait_until_electrum_sees_block()?;
let update = client.sync(
SyncRequest::from_chain_tip(recv_chain.tip()).chain_spks([spk_to_track.clone()]),
5,
false,
)?;
let _ = recv_chain
.apply_update(update.chain_update)
.map_err(|err| anyhow::anyhow!("LocalChain update error: {:?}", err))?;
// Check that no new anchors are added during current reorg.
assert!(initial_anchors.is_superset(update.graph_update.all_anchors()));
let _ = recv_graph.apply_update(update.graph_update);
assert_eq!(
get_balance(&recv_chain, &recv_graph)?,
Balance {
confirmed: SEND_AMOUNT * (REORG_COUNT - depth) as u64,
..Balance::default()
},
"reorg_count: {}",
depth,
);
}
Ok(())
}

34
crates/esplora/Cargo.toml Normal file
View File

@ -0,0 +1,34 @@
[package]
name = "bdk_esplora"
version = "0.16.0"
edition = "2021"
homepage = "https://bitcoindevkit.org"
repository = "https://github.com/bitcoindevkit/bdk"
documentation = "https://docs.rs/bdk_esplora"
description = "Fetch data from esplora in the form that accepts"
license = "MIT OR Apache-2.0"
readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bdk_chain = { path = "../chain", version = "0.17.0", default-features = false }
esplora-client = { version = "0.8.0", default-features = false }
async-trait = { version = "0.1.66", optional = true }
futures = { version = "0.3.26", optional = true }
bitcoin = { version = "0.32.0", optional = true, default-features = false }
miniscript = { version = "12.0.0", optional = true, default-features = false }
[dev-dependencies]
bdk_testenv = { path = "../testenv", default-features = false }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros"] }
[features]
default = ["std", "async-https", "blocking-https-rustls"]
std = ["bdk_chain/std", "miniscript?/std"]
async = ["async-trait", "futures", "esplora-client/async"]
async-https = ["async", "esplora-client/async-https"]
async-https-rustls = ["async", "esplora-client/async-https-rustls"]
blocking = ["esplora-client/blocking"]
blocking-https-rustls = ["esplora-client/blocking-https-rustls"]

36
crates/esplora/README.md Normal file
View File

@ -0,0 +1,36 @@
# BDK Esplora
BDK Esplora extends [`esplora-client`] to update [`bdk_chain`] structures
from an Esplora server.
## Usage
There are two versions of the extension trait (blocking and async).
For blocking-only:
```toml
bdk_esplora = { version = "0.3", features = ["blocking"] }
```
For async-only:
```toml
bdk_esplora = { version = "0.3", features = ["async"] }
```
For async-only (with https):
```toml
bdk_esplora = { version = "0.3", features = ["async-https"] }
```
To use the extension traits:
```rust
// for blocking
use bdk_esplora::EsploraExt;
// for async
// use bdk_esplora::EsploraAsyncExt;
```
For full examples, refer to [`example-crates/wallet_esplora_blocking`](https://github.com/bitcoindevkit/bdk/tree/master/example-crates/wallet_esplora_blocking) and [`example-crates/wallet_esplora_async`](https://github.com/bitcoindevkit/bdk/tree/master/example-crates/wallet_esplora_async).
[`esplora-client`]: https://docs.rs/esplora-client/
[`bdk_chain`]: https://docs.rs/bdk-chain/

View File

@ -0,0 +1,590 @@
use std::collections::BTreeSet;
use async_trait::async_trait;
use bdk_chain::spk_client::{FullScanRequest, FullScanResult, SyncRequest, SyncResult};
use bdk_chain::{
bitcoin::{BlockHash, OutPoint, ScriptBuf, TxOut, Txid},
collections::BTreeMap,
local_chain::CheckPoint,
BlockId, ConfirmationBlockTime, TxGraph,
};
use bdk_chain::{Anchor, Indexed};
use esplora_client::{Amount, TxStatus};
use futures::{stream::FuturesOrdered, TryStreamExt};
use crate::anchor_from_status;
/// [`esplora_client::Error`]
type Error = Box<esplora_client::Error>;
/// Trait to extend the functionality of [`esplora_client::AsyncClient`].
///
/// Refer to [crate-level documentation] for more.
///
/// [crate-level documentation]: crate
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait EsploraAsyncExt {
/// Scan keychain scripts for transactions against Esplora, returning an update that can be
/// applied to the receiving structures.
///
/// - `request`: struct with data required to perform a spk-based blockchain client full scan,
/// see [`FullScanRequest`]
///
/// The full scan for each keychain stops after a gap of `stop_gap` script pubkeys with no
/// associated transactions. `parallel_requests` specifies the max number of HTTP requests to
/// make in parallel.
///
/// ## Note
///
/// `stop_gap` is defined as "the maximum number of consecutive unused addresses".
/// For example, with a `stop_gap` of 3, `full_scan` will keep scanning
/// until it encounters 3 consecutive script pubkeys with no associated transactions.
///
/// This follows the same approach as other Bitcoin-related software,
/// such as [Electrum](https://electrum.readthedocs.io/en/latest/faq.html#what-is-the-gap-limit),
/// [BTCPay Server](https://docs.btcpayserver.org/FAQ/Wallet/#the-gap-limit-problem),
/// and [Sparrow](https://www.sparrowwallet.com/docs/faq.html#ive-restored-my-wallet-but-some-of-my-funds-are-missing).
///
/// A `stop_gap` of 0 will be treated as a `stop_gap` of 1.
async fn full_scan<K: Ord + Clone + Send>(
&self,
request: FullScanRequest<K>,
stop_gap: usize,
parallel_requests: usize,
) -> Result<FullScanResult<K>, Error>;
/// Sync a set of scripts with the blockchain (via an Esplora client) for the data
/// specified and return a [`TxGraph`].
///
/// - `request`: struct with data required to perform a spk-based blockchain client sync, see
/// [`SyncRequest`]
///
/// If the scripts to sync are unknown, such as when restoring or importing a keychain that
/// may include scripts that have been used, use [`full_scan`] with the keychain.
///
/// [`full_scan`]: EsploraAsyncExt::full_scan
async fn sync(
&self,
request: SyncRequest,
parallel_requests: usize,
) -> Result<SyncResult, Error>;
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl EsploraAsyncExt for esplora_client::AsyncClient {
async fn full_scan<K: Ord + Clone + Send>(
&self,
request: FullScanRequest<K>,
stop_gap: usize,
parallel_requests: usize,
) -> Result<FullScanResult<K>, Error> {
let latest_blocks = fetch_latest_blocks(self).await?;
let (graph_update, last_active_indices) = full_scan_for_index_and_graph(
self,
request.spks_by_keychain,
stop_gap,
parallel_requests,
)
.await?;
let chain_update = chain_update(
self,
&latest_blocks,
&request.chain_tip,
graph_update.all_anchors(),
)
.await?;
Ok(FullScanResult {
chain_update,
graph_update,
last_active_indices,
})
}
async fn sync(
&self,
request: SyncRequest,
parallel_requests: usize,
) -> Result<SyncResult, Error> {
let latest_blocks = fetch_latest_blocks(self).await?;
let graph_update = sync_for_index_and_graph(
self,
request.spks,
request.txids,
request.outpoints,
parallel_requests,
)
.await?;
let chain_update = chain_update(
self,
&latest_blocks,
&request.chain_tip,
graph_update.all_anchors(),
)
.await?;
Ok(SyncResult {
chain_update,
graph_update,
})
}
}
/// Fetch latest blocks from Esplora in an atomic call.
///
/// We want to do this before fetching transactions and anchors as we cannot fetch latest blocks AND
/// transactions atomically, and the checkpoint tip is used to determine last-scanned block (for
/// block-based chain-sources). Therefore it's better to be conservative when setting the tip (use
/// an earlier tip rather than a later tip) otherwise the caller may accidentally skip blocks when
/// alternating between chain-sources.
async fn fetch_latest_blocks(
client: &esplora_client::AsyncClient,
) -> Result<BTreeMap<u32, BlockHash>, Error> {
Ok(client
.get_blocks(None)
.await?
.into_iter()
.map(|b| (b.time.height, b.id))
.collect())
}
/// Used instead of [`esplora_client::BlockingClient::get_block_hash`].
///
/// This first checks the previously fetched `latest_blocks` before fetching from Esplora again.
async fn fetch_block(
client: &esplora_client::AsyncClient,
latest_blocks: &BTreeMap<u32, BlockHash>,
height: u32,
) -> Result<Option<BlockHash>, Error> {
if let Some(&hash) = latest_blocks.get(&height) {
return Ok(Some(hash));
}
// We avoid fetching blocks higher than previously fetched `latest_blocks` as the local chain
// tip is used to signal for the last-synced-up-to-height.
let &tip_height = latest_blocks
.keys()
.last()
.expect("must have atleast one entry");
if height > tip_height {
return Ok(None);
}
Ok(Some(client.get_block_hash(height).await?))
}
/// Create the [`local_chain::Update`].
///
/// We want to have a corresponding checkpoint per anchor height. However, checkpoints fetched
/// should not surpass `latest_blocks`.
async fn chain_update<A: Anchor>(
client: &esplora_client::AsyncClient,
latest_blocks: &BTreeMap<u32, BlockHash>,
local_tip: &CheckPoint,
anchors: &BTreeSet<(A, Txid)>,
) -> Result<CheckPoint, Error> {
let mut point_of_agreement = None;
let mut conflicts = vec![];
for local_cp in local_tip.iter() {
let remote_hash = match fetch_block(client, latest_blocks, local_cp.height()).await? {
Some(hash) => hash,
None => continue,
};
if remote_hash == local_cp.hash() {
point_of_agreement = Some(local_cp.clone());
break;
} else {
// it is not strictly necessary to include all the conflicted heights (we do need the
// first one) but it seems prudent to make sure the updated chain's heights are a
// superset of the existing chain after update.
conflicts.push(BlockId {
height: local_cp.height(),
hash: remote_hash,
});
}
}
let mut tip = point_of_agreement.expect("remote esplora should have same genesis block");
tip = tip
.extend(conflicts.into_iter().rev())
.expect("evicted are in order");
for anchor in anchors {
let height = anchor.0.anchor_block().height;
if tip.get(height).is_none() {
let hash = match fetch_block(client, latest_blocks, height).await? {
Some(hash) => hash,
None => continue,
};
tip = tip.insert(BlockId { height, hash });
}
}
// insert the most recent blocks at the tip to make sure we update the tip and make the update
// robust.
for (&height, &hash) in latest_blocks.iter() {
tip = tip.insert(BlockId { height, hash });
}
Ok(tip)
}
/// This performs a full scan to get an update for the [`TxGraph`] and
/// [`KeychainTxOutIndex`](bdk_chain::indexer::keychain_txout::KeychainTxOutIndex).
async fn full_scan_for_index_and_graph<K: Ord + Clone + Send>(
client: &esplora_client::AsyncClient,
keychain_spks: BTreeMap<
K,
impl IntoIterator<IntoIter = impl Iterator<Item = Indexed<ScriptBuf>> + Send> + Send,
>,
stop_gap: usize,
parallel_requests: usize,
) -> Result<(TxGraph<ConfirmationBlockTime>, BTreeMap<K, u32>), Error> {
type TxsOfSpkIndex = (u32, Vec<esplora_client::Tx>);
let parallel_requests = Ord::max(parallel_requests, 1);
let mut graph = TxGraph::<ConfirmationBlockTime>::default();
let mut last_active_indexes = BTreeMap::<K, u32>::new();
for (keychain, spks) in keychain_spks {
let mut spks = spks.into_iter();
let mut last_index = Option::<u32>::None;
let mut last_active_index = Option::<u32>::None;
loop {
let handles = spks
.by_ref()
.take(parallel_requests)
.map(|(spk_index, spk)| {
let client = client.clone();
async move {
let mut last_seen = None;
let mut spk_txs = Vec::new();
loop {
let txs = client.scripthash_txs(&spk, last_seen).await?;
let tx_count = txs.len();
last_seen = txs.last().map(|tx| tx.txid);
spk_txs.extend(txs);
if tx_count < 25 {
break Result::<_, Error>::Ok((spk_index, spk_txs));
}
}
}
})
.collect::<FuturesOrdered<_>>();
if handles.is_empty() {
break;
}
for (index, txs) in handles.try_collect::<Vec<TxsOfSpkIndex>>().await? {
last_index = Some(index);
if !txs.is_empty() {
last_active_index = Some(index);
}
for tx in txs {
let _ = graph.insert_tx(tx.to_tx());
if let Some(anchor) = anchor_from_status(&tx.status) {
let _ = graph.insert_anchor(tx.txid, anchor);
}
let previous_outputs = tx.vin.iter().filter_map(|vin| {
let prevout = vin.prevout.as_ref()?;
Some((
OutPoint {
txid: vin.txid,
vout: vin.vout,
},
TxOut {
script_pubkey: prevout.scriptpubkey.clone(),
value: Amount::from_sat(prevout.value),
},
))
});
for (outpoint, txout) in previous_outputs {
let _ = graph.insert_txout(outpoint, txout);
}
}
}
let last_index = last_index.expect("Must be set since handles wasn't empty.");
let gap_limit_reached = if let Some(i) = last_active_index {
last_index >= i.saturating_add(stop_gap as u32)
} else {
last_index + 1 >= stop_gap as u32
};
if gap_limit_reached {
break;
}
}
if let Some(last_active_index) = last_active_index {
last_active_indexes.insert(keychain, last_active_index);
}
}
Ok((graph, last_active_indexes))
}
async fn sync_for_index_and_graph(
client: &esplora_client::AsyncClient,
misc_spks: impl IntoIterator<IntoIter = impl Iterator<Item = ScriptBuf> + Send> + Send,
txids: impl IntoIterator<IntoIter = impl Iterator<Item = Txid> + Send> + Send,
outpoints: impl IntoIterator<IntoIter = impl Iterator<Item = OutPoint> + Send> + Send,
parallel_requests: usize,
) -> Result<TxGraph<ConfirmationBlockTime>, Error> {
let mut graph = full_scan_for_index_and_graph(
client,
[(
(),
misc_spks
.into_iter()
.enumerate()
.map(|(i, spk)| (i as u32, spk)),
)]
.into(),
usize::MAX,
parallel_requests,
)
.await
.map(|(g, _)| g)?;
let mut txids = txids.into_iter();
loop {
let handles = txids
.by_ref()
.take(parallel_requests)
.filter(|&txid| graph.get_tx(txid).is_none())
.map(|txid| {
let client = client.clone();
async move { client.get_tx_status(&txid).await.map(|s| (txid, s)) }
})
.collect::<FuturesOrdered<_>>();
if handles.is_empty() {
break;
}
for (txid, status) in handles.try_collect::<Vec<(Txid, TxStatus)>>().await? {
if let Some(anchor) = anchor_from_status(&status) {
let _ = graph.insert_anchor(txid, anchor);
}
}
}
for op in outpoints.into_iter() {
if graph.get_tx(op.txid).is_none() {
if let Some(tx) = client.get_tx(&op.txid).await? {
let _ = graph.insert_tx(tx);
}
let status = client.get_tx_status(&op.txid).await?;
if let Some(anchor) = anchor_from_status(&status) {
let _ = graph.insert_anchor(op.txid, anchor);
}
}
if let Some(op_status) = client.get_output_status(&op.txid, op.vout as _).await? {
if let Some(txid) = op_status.txid {
if graph.get_tx(txid).is_none() {
if let Some(tx) = client.get_tx(&txid).await? {
let _ = graph.insert_tx(tx);
}
let status = client.get_tx_status(&txid).await?;
if let Some(anchor) = anchor_from_status(&status) {
let _ = graph.insert_anchor(txid, anchor);
}
}
}
}
}
Ok(graph)
}
#[cfg(test)]
mod test {
use std::{collections::BTreeSet, time::Duration};
use bdk_chain::{
bitcoin::{hashes::Hash, Txid},
local_chain::LocalChain,
BlockId,
};
use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv};
use esplora_client::Builder;
use crate::async_ext::{chain_update, fetch_latest_blocks};
macro_rules! h {
($index:literal) => {{
bdk_chain::bitcoin::hashes::Hash::hash($index.as_bytes())
}};
}
/// Ensure that update does not remove heights (from original), and all anchor heights are included.
#[tokio::test]
pub async fn test_finalize_chain_update() -> anyhow::Result<()> {
struct TestCase<'a> {
name: &'a str,
/// Initial blockchain height to start the env with.
initial_env_height: u32,
/// Initial checkpoint heights to start with.
initial_cps: &'a [u32],
/// The final blockchain height of the env.
final_env_height: u32,
/// The anchors to test with: `(height, txid)`. Only the height is provided as we can fetch
/// the blockhash from the env.
anchors: &'a [(u32, Txid)],
}
let test_cases = [
TestCase {
name: "chain_extends",
initial_env_height: 60,
initial_cps: &[59, 60],
final_env_height: 90,
anchors: &[],
},
TestCase {
name: "introduce_older_heights",
initial_env_height: 50,
initial_cps: &[10, 15],
final_env_height: 50,
anchors: &[(11, h!("A")), (14, h!("B"))],
},
TestCase {
name: "introduce_older_heights_after_chain_extends",
initial_env_height: 50,
initial_cps: &[10, 15],
final_env_height: 100,
anchors: &[(11, h!("A")), (14, h!("B"))],
},
];
for (i, t) in test_cases.into_iter().enumerate() {
println!("[{}] running test case: {}", i, t.name);
let env = TestEnv::new()?;
let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
let client = Builder::new(base_url.as_str()).build_async()?;
// set env to `initial_env_height`
if let Some(to_mine) = t
.initial_env_height
.checked_sub(env.make_checkpoint_tip().height())
{
env.mine_blocks(to_mine as _, None)?;
}
while client.get_height().await? < t.initial_env_height {
std::thread::sleep(Duration::from_millis(10));
}
// craft initial `local_chain`
let local_chain = {
let (mut chain, _) = LocalChain::from_genesis_hash(env.genesis_hash()?);
// force `chain_update_blocking` to add all checkpoints in `t.initial_cps`
let anchors = t
.initial_cps
.iter()
.map(|&height| -> anyhow::Result<_> {
Ok((
BlockId {
height,
hash: env.bitcoind.client.get_block_hash(height as _)?,
},
Txid::all_zeros(),
))
})
.collect::<anyhow::Result<BTreeSet<_>>>()?;
let update = chain_update(
&client,
&fetch_latest_blocks(&client).await?,
&chain.tip(),
&anchors,
)
.await?;
chain.apply_update(update)?;
chain
};
println!("local chain height: {}", local_chain.tip().height());
// extend env chain
if let Some(to_mine) = t
.final_env_height
.checked_sub(env.make_checkpoint_tip().height())
{
env.mine_blocks(to_mine as _, None)?;
}
while client.get_height().await? < t.final_env_height {
std::thread::sleep(Duration::from_millis(10));
}
// craft update
let update = {
let anchors = t
.anchors
.iter()
.map(|&(height, txid)| -> anyhow::Result<_> {
Ok((
BlockId {
height,
hash: env.bitcoind.client.get_block_hash(height as _)?,
},
txid,
))
})
.collect::<anyhow::Result<_>>()?;
chain_update(
&client,
&fetch_latest_blocks(&client).await?,
&local_chain.tip(),
&anchors,
)
.await?
};
// apply update
let mut updated_local_chain = local_chain.clone();
updated_local_chain.apply_update(update)?;
println!(
"updated local chain height: {}",
updated_local_chain.tip().height()
);
assert!(
{
let initial_heights = local_chain
.iter_checkpoints()
.map(|cp| cp.height())
.collect::<BTreeSet<_>>();
let updated_heights = updated_local_chain
.iter_checkpoints()
.map(|cp| cp.height())
.collect::<BTreeSet<_>>();
updated_heights.is_superset(&initial_heights)
},
"heights from the initial chain must all be in the updated chain",
);
assert!(
{
let exp_anchor_heights = t
.anchors
.iter()
.map(|(h, _)| *h)
.chain(t.initial_cps.iter().copied())
.collect::<BTreeSet<_>>();
let anchor_heights = updated_local_chain
.iter_checkpoints()
.map(|cp| cp.height())
.collect::<BTreeSet<_>>();
anchor_heights.is_superset(&exp_anchor_heights)
},
"anchor heights must all be in updated chain",
);
}
Ok(())
}
}

View File

@ -0,0 +1,785 @@
use std::collections::BTreeSet;
use std::thread::JoinHandle;
use bdk_chain::collections::BTreeMap;
use bdk_chain::spk_client::{FullScanRequest, FullScanResult, SyncRequest, SyncResult};
use bdk_chain::{
bitcoin::{Amount, BlockHash, OutPoint, ScriptBuf, TxOut, Txid},
local_chain::CheckPoint,
BlockId, ConfirmationBlockTime, TxGraph,
};
use bdk_chain::{Anchor, Indexed};
use esplora_client::TxStatus;
use crate::anchor_from_status;
/// [`esplora_client::Error`]
pub type Error = Box<esplora_client::Error>;
/// Trait to extend the functionality of [`esplora_client::BlockingClient`].
///
/// Refer to [crate-level documentation] for more.
///
/// [crate-level documentation]: crate
pub trait EsploraExt {
/// Scan keychain scripts for transactions against Esplora, returning an update that can be
/// applied to the receiving structures.
///
/// - `request`: struct with data required to perform a spk-based blockchain client full scan,
/// see [`FullScanRequest`]
///
/// The full scan for each keychain stops after a gap of `stop_gap` script pubkeys with no
/// associated transactions. `parallel_requests` specifies the max number of HTTP requests to
/// make in parallel.
///
/// ## Note
///
/// `stop_gap` is defined as "the maximum number of consecutive unused addresses".
/// For example, with a `stop_gap` of 3, `full_scan` will keep scanning
/// until it encounters 3 consecutive script pubkeys with no associated transactions.
///
/// This follows the same approach as other Bitcoin-related software,
/// such as [Electrum](https://electrum.readthedocs.io/en/latest/faq.html#what-is-the-gap-limit),
/// [BTCPay Server](https://docs.btcpayserver.org/FAQ/Wallet/#the-gap-limit-problem),
/// and [Sparrow](https://www.sparrowwallet.com/docs/faq.html#ive-restored-my-wallet-but-some-of-my-funds-are-missing).
///
/// A `stop_gap` of 0 will be treated as a `stop_gap` of 1.
fn full_scan<K: Ord + Clone>(
&self,
request: FullScanRequest<K>,
stop_gap: usize,
parallel_requests: usize,
) -> Result<FullScanResult<K>, Error>;
/// Sync a set of scripts with the blockchain (via an Esplora client) for the data
/// specified and return a [`TxGraph`].
///
/// - `request`: struct with data required to perform a spk-based blockchain client sync, see
/// [`SyncRequest`]
///
/// If the scripts to sync are unknown, such as when restoring or importing a keychain that
/// may include scripts that have been used, use [`full_scan`] with the keychain.
///
/// [`full_scan`]: EsploraExt::full_scan
fn sync(&self, request: SyncRequest, parallel_requests: usize) -> Result<SyncResult, Error>;
}
impl EsploraExt for esplora_client::BlockingClient {
fn full_scan<K: Ord + Clone>(
&self,
request: FullScanRequest<K>,
stop_gap: usize,
parallel_requests: usize,
) -> Result<FullScanResult<K>, Error> {
let latest_blocks = fetch_latest_blocks(self)?;
let (graph_update, last_active_indices) = full_scan_for_index_and_graph_blocking(
self,
request.spks_by_keychain,
stop_gap,
parallel_requests,
)?;
let chain_update = chain_update(
self,
&latest_blocks,
&request.chain_tip,
graph_update.all_anchors(),
)?;
Ok(FullScanResult {
chain_update,
graph_update,
last_active_indices,
})
}
fn sync(&self, request: SyncRequest, parallel_requests: usize) -> Result<SyncResult, Error> {
let latest_blocks = fetch_latest_blocks(self)?;
let graph_update = sync_for_index_and_graph_blocking(
self,
request.spks,
request.txids,
request.outpoints,
parallel_requests,
)?;
let chain_update = chain_update(
self,
&latest_blocks,
&request.chain_tip,
graph_update.all_anchors(),
)?;
Ok(SyncResult {
chain_update,
graph_update,
})
}
}
/// Fetch latest blocks from Esplora in an atomic call.
///
/// We want to do this before fetching transactions and anchors as we cannot fetch latest blocks AND
/// transactions atomically, and the checkpoint tip is used to determine last-scanned block (for
/// block-based chain-sources). Therefore it's better to be conservative when setting the tip (use
/// an earlier tip rather than a later tip) otherwise the caller may accidentally skip blocks when
/// alternating between chain-sources.
fn fetch_latest_blocks(
client: &esplora_client::BlockingClient,
) -> Result<BTreeMap<u32, BlockHash>, Error> {
Ok(client
.get_blocks(None)?
.into_iter()
.map(|b| (b.time.height, b.id))
.collect())
}
/// Used instead of [`esplora_client::BlockingClient::get_block_hash`].
///
/// This first checks the previously fetched `latest_blocks` before fetching from Esplora again.
fn fetch_block(
client: &esplora_client::BlockingClient,
latest_blocks: &BTreeMap<u32, BlockHash>,
height: u32,
) -> Result<Option<BlockHash>, Error> {
if let Some(&hash) = latest_blocks.get(&height) {
return Ok(Some(hash));
}
// We avoid fetching blocks higher than previously fetched `latest_blocks` as the local chain
// tip is used to signal for the last-synced-up-to-height.
let &tip_height = latest_blocks
.keys()
.last()
.expect("must have atleast one entry");
if height > tip_height {
return Ok(None);
}
Ok(Some(client.get_block_hash(height)?))
}
/// Create the [`local_chain::Update`].
///
/// We want to have a corresponding checkpoint per anchor height. However, checkpoints fetched
/// should not surpass `latest_blocks`.
fn chain_update<A: Anchor>(
client: &esplora_client::BlockingClient,
latest_blocks: &BTreeMap<u32, BlockHash>,
local_tip: &CheckPoint,
anchors: &BTreeSet<(A, Txid)>,
) -> Result<CheckPoint, Error> {
let mut point_of_agreement = None;
let mut conflicts = vec![];
for local_cp in local_tip.iter() {
let remote_hash = match fetch_block(client, latest_blocks, local_cp.height())? {
Some(hash) => hash,
None => continue,
};
if remote_hash == local_cp.hash() {
point_of_agreement = Some(local_cp.clone());
break;
} else {
// it is not strictly necessary to include all the conflicted heights (we do need the
// first one) but it seems prudent to make sure the updated chain's heights are a
// superset of the existing chain after update.
conflicts.push(BlockId {
height: local_cp.height(),
hash: remote_hash,
});
}
}
let mut tip = point_of_agreement.expect("remote esplora should have same genesis block");
tip = tip
.extend(conflicts.into_iter().rev())
.expect("evicted are in order");
for anchor in anchors {
let height = anchor.0.anchor_block().height;
if tip.get(height).is_none() {
let hash = match fetch_block(client, latest_blocks, height)? {
Some(hash) => hash,
None => continue,
};
tip = tip.insert(BlockId { height, hash });
}
}
// insert the most recent blocks at the tip to make sure we update the tip and make the update
// robust.
for (&height, &hash) in latest_blocks.iter() {
tip = tip.insert(BlockId { height, hash });
}
Ok(tip)
}
/// This performs a full scan to get an update for the [`TxGraph`] and
/// [`KeychainTxOutIndex`](bdk_chain::indexer::keychain_txout::KeychainTxOutIndex).
fn full_scan_for_index_and_graph_blocking<K: Ord + Clone>(
client: &esplora_client::BlockingClient,
keychain_spks: BTreeMap<K, impl IntoIterator<Item = Indexed<ScriptBuf>>>,
stop_gap: usize,
parallel_requests: usize,
) -> Result<(TxGraph<ConfirmationBlockTime>, BTreeMap<K, u32>), Error> {
type TxsOfSpkIndex = (u32, Vec<esplora_client::Tx>);
let parallel_requests = Ord::max(parallel_requests, 1);
let mut tx_graph = TxGraph::<ConfirmationBlockTime>::default();
let mut last_active_indices = BTreeMap::<K, u32>::new();
for (keychain, spks) in keychain_spks {
let mut spks = spks.into_iter();
let mut last_index = Option::<u32>::None;
let mut last_active_index = Option::<u32>::None;
loop {
let handles = spks
.by_ref()
.take(parallel_requests)
.map(|(spk_index, spk)| {
std::thread::spawn({
let client = client.clone();
move || -> Result<TxsOfSpkIndex, Error> {
let mut last_seen = None;
let mut spk_txs = Vec::new();
loop {
let txs = client.scripthash_txs(&spk, last_seen)?;
let tx_count = txs.len();
last_seen = txs.last().map(|tx| tx.txid);
spk_txs.extend(txs);
if tx_count < 25 {
break Ok((spk_index, spk_txs));
}
}
}
})
})
.collect::<Vec<JoinHandle<Result<TxsOfSpkIndex, Error>>>>();
if handles.is_empty() {
break;
}
for handle in handles {
let (index, txs) = handle.join().expect("thread must not panic")?;
last_index = Some(index);
if !txs.is_empty() {
last_active_index = Some(index);
}
for tx in txs {
let _ = tx_graph.insert_tx(tx.to_tx());
if let Some(anchor) = anchor_from_status(&tx.status) {
let _ = tx_graph.insert_anchor(tx.txid, anchor);
}
let previous_outputs = tx.vin.iter().filter_map(|vin| {
let prevout = vin.prevout.as_ref()?;
Some((
OutPoint {
txid: vin.txid,
vout: vin.vout,
},
TxOut {
script_pubkey: prevout.scriptpubkey.clone(),
value: Amount::from_sat(prevout.value),
},
))
});
for (outpoint, txout) in previous_outputs {
let _ = tx_graph.insert_txout(outpoint, txout);
}
}
}
let last_index = last_index.expect("Must be set since handles wasn't empty.");
let gap_limit_reached = if let Some(i) = last_active_index {
last_index >= i.saturating_add(stop_gap as u32)
} else {
last_index + 1 >= stop_gap as u32
};
if gap_limit_reached {
break;
}
}
if let Some(last_active_index) = last_active_index {
last_active_indices.insert(keychain, last_active_index);
}
}
Ok((tx_graph, last_active_indices))
}
fn sync_for_index_and_graph_blocking(
client: &esplora_client::BlockingClient,
misc_spks: impl IntoIterator<Item = ScriptBuf>,
txids: impl IntoIterator<Item = Txid>,
outpoints: impl IntoIterator<Item = OutPoint>,
parallel_requests: usize,
) -> Result<TxGraph<ConfirmationBlockTime>, Error> {
let (mut tx_graph, _) = full_scan_for_index_and_graph_blocking(
client,
{
let mut keychains = BTreeMap::new();
keychains.insert(
(),
misc_spks
.into_iter()
.enumerate()
.map(|(i, spk)| (i as u32, spk)),
);
keychains
},
usize::MAX,
parallel_requests,
)?;
let mut txids = txids.into_iter();
loop {
let handles = txids
.by_ref()
.take(parallel_requests)
.filter(|&txid| tx_graph.get_tx(txid).is_none())
.map(|txid| {
std::thread::spawn({
let client = client.clone();
move || {
client
.get_tx_status(&txid)
.map_err(Box::new)
.map(|s| (txid, s))
}
})
})
.collect::<Vec<JoinHandle<Result<(Txid, TxStatus), Error>>>>();
if handles.is_empty() {
break;
}
for handle in handles {
let (txid, status) = handle.join().expect("thread must not panic")?;
if let Some(anchor) = anchor_from_status(&status) {
let _ = tx_graph.insert_anchor(txid, anchor);
}
}
}
for op in outpoints {
if tx_graph.get_tx(op.txid).is_none() {
if let Some(tx) = client.get_tx(&op.txid)? {
let _ = tx_graph.insert_tx(tx);
}
let status = client.get_tx_status(&op.txid)?;
if let Some(anchor) = anchor_from_status(&status) {
let _ = tx_graph.insert_anchor(op.txid, anchor);
}
}
if let Some(op_status) = client.get_output_status(&op.txid, op.vout as _)? {
if let Some(txid) = op_status.txid {
if tx_graph.get_tx(txid).is_none() {
if let Some(tx) = client.get_tx(&txid)? {
let _ = tx_graph.insert_tx(tx);
}
let status = client.get_tx_status(&txid)?;
if let Some(anchor) = anchor_from_status(&status) {
let _ = tx_graph.insert_anchor(txid, anchor);
}
}
}
}
}
Ok(tx_graph)
}
#[cfg(test)]
mod test {
use crate::blocking_ext::{chain_update, fetch_latest_blocks};
use bdk_chain::bitcoin::hashes::Hash;
use bdk_chain::bitcoin::Txid;
use bdk_chain::local_chain::LocalChain;
use bdk_chain::BlockId;
use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv};
use esplora_client::{BlockHash, Builder};
use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;
macro_rules! h {
($index:literal) => {{
bdk_chain::bitcoin::hashes::Hash::hash($index.as_bytes())
}};
}
macro_rules! local_chain {
[ $(($height:expr, $block_hash:expr)), * ] => {{
#[allow(unused_mut)]
bdk_chain::local_chain::LocalChain::from_blocks([$(($height, $block_hash).into()),*].into_iter().collect())
.expect("chain must have genesis block")
}};
}
/// Ensure that update does not remove heights (from original), and all anchor heights are included.
#[test]
pub fn test_finalize_chain_update() -> anyhow::Result<()> {
struct TestCase<'a> {
name: &'a str,
/// Initial blockchain height to start the env with.
initial_env_height: u32,
/// Initial checkpoint heights to start with in the local chain.
initial_cps: &'a [u32],
/// The final blockchain height of the env.
final_env_height: u32,
/// The anchors to test with: `(height, txid)`. Only the height is provided as we can fetch
/// the blockhash from the env.
anchors: &'a [(u32, Txid)],
}
let test_cases = [
TestCase {
name: "chain_extends",
initial_env_height: 60,
initial_cps: &[59, 60],
final_env_height: 90,
anchors: &[],
},
TestCase {
name: "introduce_older_heights",
initial_env_height: 50,
initial_cps: &[10, 15],
final_env_height: 50,
anchors: &[(11, h!("A")), (14, h!("B"))],
},
TestCase {
name: "introduce_older_heights_after_chain_extends",
initial_env_height: 50,
initial_cps: &[10, 15],
final_env_height: 100,
anchors: &[(11, h!("A")), (14, h!("B"))],
},
];
for (i, t) in test_cases.into_iter().enumerate() {
println!("[{}] running test case: {}", i, t.name);
let env = TestEnv::new()?;
let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
let client = Builder::new(base_url.as_str()).build_blocking();
// set env to `initial_env_height`
if let Some(to_mine) = t
.initial_env_height
.checked_sub(env.make_checkpoint_tip().height())
{
env.mine_blocks(to_mine as _, None)?;
}
while client.get_height()? < t.initial_env_height {
std::thread::sleep(Duration::from_millis(10));
}
// craft initial `local_chain`
let local_chain = {
let (mut chain, _) = LocalChain::from_genesis_hash(env.genesis_hash()?);
// force `chain_update_blocking` to add all checkpoints in `t.initial_cps`
let anchors = t
.initial_cps
.iter()
.map(|&height| -> anyhow::Result<_> {
Ok((
BlockId {
height,
hash: env.bitcoind.client.get_block_hash(height as _)?,
},
Txid::all_zeros(),
))
})
.collect::<anyhow::Result<BTreeSet<_>>>()?;
let update = chain_update(
&client,
&fetch_latest_blocks(&client)?,
&chain.tip(),
&anchors,
)?;
chain.apply_update(update)?;
chain
};
println!("local chain height: {}", local_chain.tip().height());
// extend env chain
if let Some(to_mine) = t
.final_env_height
.checked_sub(env.make_checkpoint_tip().height())
{
env.mine_blocks(to_mine as _, None)?;
}
while client.get_height()? < t.final_env_height {
std::thread::sleep(Duration::from_millis(10));
}
// craft update
let update = {
let anchors = t
.anchors
.iter()
.map(|&(height, txid)| -> anyhow::Result<_> {
Ok((
BlockId {
height,
hash: env.bitcoind.client.get_block_hash(height as _)?,
},
txid,
))
})
.collect::<anyhow::Result<_>>()?;
chain_update(
&client,
&fetch_latest_blocks(&client)?,
&local_chain.tip(),
&anchors,
)?
};
// apply update
let mut updated_local_chain = local_chain.clone();
updated_local_chain.apply_update(update)?;
println!(
"updated local chain height: {}",
updated_local_chain.tip().height()
);
assert!(
{
let initial_heights = local_chain
.iter_checkpoints()
.map(|cp| cp.height())
.collect::<BTreeSet<_>>();
let updated_heights = updated_local_chain
.iter_checkpoints()
.map(|cp| cp.height())
.collect::<BTreeSet<_>>();
updated_heights.is_superset(&initial_heights)
},
"heights from the initial chain must all be in the updated chain",
);
assert!(
{
let exp_anchor_heights = t
.anchors
.iter()
.map(|(h, _)| *h)
.chain(t.initial_cps.iter().copied())
.collect::<BTreeSet<_>>();
let anchor_heights = updated_local_chain
.iter_checkpoints()
.map(|cp| cp.height())
.collect::<BTreeSet<_>>();
anchor_heights.is_superset(&exp_anchor_heights)
},
"anchor heights must all be in updated chain",
);
}
Ok(())
}
#[test]
fn update_local_chain() -> anyhow::Result<()> {
const TIP_HEIGHT: u32 = 50;
let env = TestEnv::new()?;
let blocks = {
let bitcoind_client = &env.bitcoind.client;
assert_eq!(bitcoind_client.get_block_count()?, 1);
[
(0, bitcoind_client.get_block_hash(0)?),
(1, bitcoind_client.get_block_hash(1)?),
]
.into_iter()
.chain((2..).zip(env.mine_blocks((TIP_HEIGHT - 1) as usize, None)?))
.collect::<BTreeMap<_, _>>()
};
// so new blocks can be seen by Electrs
let env = env.reset_electrsd()?;
let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
let client = Builder::new(base_url.as_str()).build_blocking();
struct TestCase {
name: &'static str,
/// Original local chain to start off with.
chain: LocalChain,
/// Heights of floating anchors. [`chain_update_blocking`] will request for checkpoints
/// of these heights.
request_heights: &'static [u32],
/// The expected local chain result (heights only).
exp_update_heights: &'static [u32],
}
let test_cases = [
TestCase {
name: "request_later_blocks",
chain: local_chain![(0, blocks[&0]), (21, blocks[&21])],
request_heights: &[22, 25, 28],
exp_update_heights: &[21, 22, 25, 28],
},
TestCase {
name: "request_prev_blocks",
chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (5, blocks[&5])],
request_heights: &[4],
exp_update_heights: &[4, 5],
},
TestCase {
name: "request_prev_blocks_2",
chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (10, blocks[&10])],
request_heights: &[4, 6],
exp_update_heights: &[4, 6, 10],
},
TestCase {
name: "request_later_and_prev_blocks",
chain: local_chain![(0, blocks[&0]), (7, blocks[&7]), (11, blocks[&11])],
request_heights: &[8, 9, 15],
exp_update_heights: &[8, 9, 11, 15],
},
TestCase {
name: "request_tip_only",
chain: local_chain![(0, blocks[&0]), (5, blocks[&5]), (49, blocks[&49])],
request_heights: &[TIP_HEIGHT],
exp_update_heights: &[49],
},
TestCase {
name: "request_nothing",
chain: local_chain![(0, blocks[&0]), (13, blocks[&13]), (23, blocks[&23])],
request_heights: &[],
exp_update_heights: &[23],
},
TestCase {
name: "request_nothing_during_reorg",
chain: local_chain![(0, blocks[&0]), (13, blocks[&13]), (23, h!("23"))],
request_heights: &[],
exp_update_heights: &[13, 23],
},
TestCase {
name: "request_nothing_during_reorg_2",
chain: local_chain![
(0, blocks[&0]),
(21, blocks[&21]),
(22, h!("22")),
(23, h!("23"))
],
request_heights: &[],
exp_update_heights: &[21, 22, 23],
},
TestCase {
name: "request_prev_blocks_during_reorg",
chain: local_chain![
(0, blocks[&0]),
(21, blocks[&21]),
(22, h!("22")),
(23, h!("23"))
],
request_heights: &[17, 20],
exp_update_heights: &[17, 20, 21, 22, 23],
},
TestCase {
name: "request_later_blocks_during_reorg",
chain: local_chain![
(0, blocks[&0]),
(9, blocks[&9]),
(22, h!("22")),
(23, h!("23"))
],
request_heights: &[25, 27],
exp_update_heights: &[9, 22, 23, 25, 27],
},
TestCase {
name: "request_later_blocks_during_reorg_2",
chain: local_chain![(0, blocks[&0]), (9, h!("9"))],
request_heights: &[10],
exp_update_heights: &[0, 9, 10],
},
TestCase {
name: "request_later_and_prev_blocks_during_reorg",
chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (9, h!("9"))],
request_heights: &[8, 11],
exp_update_heights: &[1, 8, 9, 11],
},
];
for (i, t) in test_cases.into_iter().enumerate() {
println!("Case {}: {}", i, t.name);
let mut chain = t.chain;
let mock_anchors = t
.request_heights
.iter()
.map(|&h| {
let anchor_blockhash: BlockHash = bdk_chain::bitcoin::hashes::Hash::hash(
&format!("hash_at_height_{}", h).into_bytes(),
);
let txid: Txid = bdk_chain::bitcoin::hashes::Hash::hash(
&format!("txid_at_height_{}", h).into_bytes(),
);
let anchor = BlockId {
height: h,
hash: anchor_blockhash,
};
(anchor, txid)
})
.collect::<BTreeSet<_>>();
let chain_update = chain_update(
&client,
&fetch_latest_blocks(&client)?,
&chain.tip(),
&mock_anchors,
)?;
let update_blocks = chain_update
.iter()
.map(|cp| cp.block_id())
.collect::<BTreeSet<_>>();
let exp_update_blocks = t
.exp_update_heights
.iter()
.map(|&height| {
let hash = blocks[&height];
BlockId { height, hash }
})
.chain(
// Electrs Esplora `get_block` call fetches 10 blocks which is included in the
// update
blocks
.range(TIP_HEIGHT - 9..)
.map(|(&height, &hash)| BlockId { height, hash }),
)
.collect::<BTreeSet<_>>();
assert!(
update_blocks.is_superset(&exp_update_blocks),
"[{}:{}] unexpected update",
i,
t.name
);
let _ = chain
.apply_update(chain_update)
.unwrap_or_else(|err| panic!("[{}:{}] update failed to apply: {}", i, t.name, err));
// all requested heights must exist in the final chain
for height in t.request_heights {
let exp_blockhash = blocks.get(height).expect("block must exist in bitcoind");
assert_eq!(
chain.get(*height).map(|cp| cp.hash()),
Some(*exp_blockhash),
"[{}:{}] block {}:{} must exist in final chain",
i,
t.name,
height,
exp_blockhash
);
}
}
Ok(())
}
}

49
crates/esplora/src/lib.rs Normal file
View File

@ -0,0 +1,49 @@
#![doc = include_str!("../README.md")]
//! This crate is used for updating structures of [`bdk_chain`] with data from an Esplora server.
//!
//! The two primary methods are [`EsploraExt::sync`] and [`EsploraExt::full_scan`]. In most cases
//! [`EsploraExt::sync`] is used to sync the transaction histories of scripts that the application
//! cares about, for example the scripts for all the receive addresses of a Wallet's keychain that it
//! has shown a user. [`EsploraExt::full_scan`] is meant to be used when importing or restoring a
//! keychain where the range of possibly used scripts is not known. In this case it is necessary to
//! scan all keychain scripts until a number (the "stop gap") of unused scripts is discovered. For a
//! sync or full scan the user receives relevant blockchain data and output updates for [`bdk_chain`]
//! via a new [`TxGraph`] to be appended to any existing [`TxGraph`] data.
//!
//! Refer to [`example_esplora`] for a complete example.
//!
//! [`TxGraph`]: bdk_chain::tx_graph::TxGraph
//! [`example_esplora`]: https://github.com/bitcoindevkit/bdk/tree/master/example-crates/example_esplora
use bdk_chain::{BlockId, ConfirmationBlockTime};
use esplora_client::TxStatus;
pub use esplora_client;
#[cfg(feature = "blocking")]
mod blocking_ext;
#[cfg(feature = "blocking")]
pub use blocking_ext::*;
#[cfg(feature = "async")]
mod async_ext;
#[cfg(feature = "async")]
pub use async_ext::*;
fn anchor_from_status(status: &TxStatus) -> Option<ConfirmationBlockTime> {
if let TxStatus {
block_height: Some(height),
block_hash: Some(hash),
block_time: Some(time),
..
} = status.clone()
{
Some(ConfirmationBlockTime {
block_id: BlockId { height, hash },
confirmation_time: time,
})
} else {
None
}
}

View File

@ -0,0 +1,231 @@
use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_esplora::EsploraAsyncExt;
use esplora_client::{self, Builder};
use std::collections::{BTreeSet, HashSet};
use std::str::FromStr;
use std::thread::sleep;
use std::time::Duration;
use bdk_chain::bitcoin::{Address, Amount, Txid};
use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv};
#[tokio::test]
pub async fn test_update_tx_graph_without_keychain() -> anyhow::Result<()> {
let env = TestEnv::new()?;
let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
let client = Builder::new(base_url.as_str()).build_async()?;
let receive_address0 =
Address::from_str("bcrt1qc6fweuf4xjvz4x3gx3t9e0fh4hvqyu2qw4wvxm")?.assume_checked();
let receive_address1 =
Address::from_str("bcrt1qfjg5lv3dvc9az8patec8fjddrs4aqtauadnagr")?.assume_checked();
let misc_spks = [
receive_address0.script_pubkey(),
receive_address1.script_pubkey(),
];
let _block_hashes = env.mine_blocks(101, None)?;
let txid1 = env.bitcoind.client.send_to_address(
&receive_address1,
Amount::from_sat(10000),
None,
None,
None,
None,
Some(1),
None,
)?;
let txid2 = env.bitcoind.client.send_to_address(
&receive_address0,
Amount::from_sat(20000),
None,
None,
None,
None,
Some(1),
None,
)?;
let _block_hashes = env.mine_blocks(1, None)?;
while client.get_height().await.unwrap() < 102 {
sleep(Duration::from_millis(10))
}
// use a full checkpoint linked list (since this is not what we are testing)
let cp_tip = env.make_checkpoint_tip();
let sync_update = {
let request = SyncRequest::from_chain_tip(cp_tip.clone()).set_spks(misc_spks);
client.sync(request, 1).await?
};
assert!(
{
let update_cps = sync_update
.chain_update
.iter()
.map(|cp| cp.block_id())
.collect::<BTreeSet<_>>();
let superset_cps = cp_tip
.iter()
.map(|cp| cp.block_id())
.collect::<BTreeSet<_>>();
superset_cps.is_superset(&update_cps)
},
"update should not alter original checkpoint tip since we already started with all checkpoints",
);
let graph_update = sync_update.graph_update;
// Check to see if we have the floating txouts available from our two created transactions'
// previous outputs in order to calculate transaction fees.
for tx in graph_update.full_txs() {
// Retrieve the calculated fee from `TxGraph`, which will panic if we do not have the
// floating txouts available from the transactions' previous outputs.
let fee = graph_update.calculate_fee(&tx.tx).expect("Fee must exist");
// Retrieve the fee in the transaction data from `bitcoind`.
let tx_fee = env
.bitcoind
.client
.get_transaction(&tx.txid, None)
.expect("Tx must exist")
.fee
.expect("Fee must exist")
.abs()
.to_unsigned()
.expect("valid `Amount`");
// Check that the calculated fee matches the fee from the transaction data.
assert_eq!(fee, tx_fee);
}
let mut graph_update_txids: Vec<Txid> = graph_update.full_txs().map(|tx| tx.txid).collect();
graph_update_txids.sort();
let mut expected_txids = vec![txid1, txid2];
expected_txids.sort();
assert_eq!(graph_update_txids, expected_txids);
Ok(())
}
/// Test the bounds of the address scan depending on the `stop_gap`.
#[tokio::test]
pub async fn test_async_update_tx_graph_stop_gap() -> anyhow::Result<()> {
let env = TestEnv::new()?;
let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
let client = Builder::new(base_url.as_str()).build_async()?;
let _block_hashes = env.mine_blocks(101, None)?;
// Now let's test the gap limit. First of all get a chain of 10 addresses.
let addresses = [
"bcrt1qj9f7r8r3p2y0sqf4r3r62qysmkuh0fzep473d2ar7rcz64wqvhssjgf0z4",
"bcrt1qmm5t0ch7vh2hryx9ctq3mswexcugqe4atkpkl2tetm8merqkthas3w7q30",
"bcrt1qut9p7ej7l7lhyvekj28xknn8gnugtym4d5qvnp5shrsr4nksmfqsmyn87g",
"bcrt1qqz0xtn3m235p2k96f5wa2dqukg6shxn9n3txe8arlrhjh5p744hsd957ww",
"bcrt1q9c0t62a8l6wfytmf2t9lfj35avadk3mm8g4p3l84tp6rl66m48sqrme7wu",
"bcrt1qkmh8yrk2v47cklt8dytk8f3ammcwa4q7dzattedzfhqzvfwwgyzsg59zrh",
"bcrt1qvgrsrzy07gjkkfr5luplt0azxtfwmwq5t62gum5jr7zwcvep2acs8hhnp2",
"bcrt1qw57edarcg50ansq8mk3guyrk78rk0fwvrds5xvqeupteu848zayq549av8",
"bcrt1qvtve5ekf6e5kzs68knvnt2phfw6a0yjqrlgat392m6zt9jsvyxhqfx67ef",
"bcrt1qw03ddumfs9z0kcu76ln7jrjfdwam20qtffmkcral3qtza90sp9kqm787uk",
];
let addresses: Vec<_> = addresses
.into_iter()
.map(|s| Address::from_str(s).unwrap().assume_checked())
.collect();
let spks: Vec<_> = addresses
.iter()
.enumerate()
.map(|(i, addr)| (i as u32, addr.script_pubkey()))
.collect();
// Then receive coins on the 4th address.
let txid_4th_addr = env.bitcoind.client.send_to_address(
&addresses[3],
Amount::from_sat(10000),
None,
None,
None,
None,
Some(1),
None,
)?;
let _block_hashes = env.mine_blocks(1, None)?;
while client.get_height().await.unwrap() < 103 {
sleep(Duration::from_millis(10))
}
// use a full checkpoint linked list (since this is not what we are testing)
let cp_tip = env.make_checkpoint_tip();
// A scan with a gap limit of 3 won't find the transaction, but a scan with a gap limit of 4
// will.
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 3, 1).await?
};
assert!(full_scan_update.graph_update.full_txs().next().is_none());
assert!(full_scan_update.last_active_indices.is_empty());
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 4, 1).await?
};
assert_eq!(
full_scan_update
.graph_update
.full_txs()
.next()
.unwrap()
.txid,
txid_4th_addr
);
assert_eq!(full_scan_update.last_active_indices[&0], 3);
// Now receive a coin on the last address.
let txid_last_addr = env.bitcoind.client.send_to_address(
&addresses[addresses.len() - 1],
Amount::from_sat(10000),
None,
None,
None,
None,
Some(1),
None,
)?;
let _block_hashes = env.mine_blocks(1, None)?;
while client.get_height().await.unwrap() < 104 {
sleep(Duration::from_millis(10))
}
// A scan with gap limit 5 won't find the second transaction, but a scan with gap limit 6 will.
// The last active indice won't be updated in the first case but will in the second one.
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 5, 1).await?
};
let txs: HashSet<_> = full_scan_update
.graph_update
.full_txs()
.map(|tx| tx.txid)
.collect();
assert_eq!(txs.len(), 1);
assert!(txs.contains(&txid_4th_addr));
assert_eq!(full_scan_update.last_active_indices[&0], 3);
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 6, 1).await?
};
let txs: HashSet<_> = full_scan_update
.graph_update
.full_txs()
.map(|tx| tx.txid)
.collect();
assert_eq!(txs.len(), 2);
assert!(txs.contains(&txid_4th_addr) && txs.contains(&txid_last_addr));
assert_eq!(full_scan_update.last_active_indices[&0], 9);
Ok(())
}

View File

@ -0,0 +1,232 @@
use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_esplora::EsploraExt;
use esplora_client::{self, Builder};
use std::collections::{BTreeSet, HashSet};
use std::str::FromStr;
use std::thread::sleep;
use std::time::Duration;
use bdk_chain::bitcoin::{Address, Amount, Txid};
use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv};
#[test]
pub fn test_update_tx_graph_without_keychain() -> anyhow::Result<()> {
let env = TestEnv::new()?;
let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
let client = Builder::new(base_url.as_str()).build_blocking();
let receive_address0 =
Address::from_str("bcrt1qc6fweuf4xjvz4x3gx3t9e0fh4hvqyu2qw4wvxm")?.assume_checked();
let receive_address1 =
Address::from_str("bcrt1qfjg5lv3dvc9az8patec8fjddrs4aqtauadnagr")?.assume_checked();
let misc_spks = [
receive_address0.script_pubkey(),
receive_address1.script_pubkey(),
];
let _block_hashes = env.mine_blocks(101, None)?;
let txid1 = env.bitcoind.client.send_to_address(
&receive_address1,
Amount::from_sat(10000),
None,
None,
None,
None,
Some(1),
None,
)?;
let txid2 = env.bitcoind.client.send_to_address(
&receive_address0,
Amount::from_sat(20000),
None,
None,
None,
None,
Some(1),
None,
)?;
let _block_hashes = env.mine_blocks(1, None)?;
while client.get_height().unwrap() < 102 {
sleep(Duration::from_millis(10))
}
// use a full checkpoint linked list (since this is not what we are testing)
let cp_tip = env.make_checkpoint_tip();
let sync_update = {
let request = SyncRequest::from_chain_tip(cp_tip.clone()).set_spks(misc_spks);
client.sync(request, 1)?
};
assert!(
{
let update_cps = sync_update
.chain_update
.iter()
.map(|cp| cp.block_id())
.collect::<BTreeSet<_>>();
let superset_cps = cp_tip
.iter()
.map(|cp| cp.block_id())
.collect::<BTreeSet<_>>();
superset_cps.is_superset(&update_cps)
},
"update should not alter original checkpoint tip since we already started with all checkpoints",
);
let graph_update = sync_update.graph_update;
// Check to see if we have the floating txouts available from our two created transactions'
// previous outputs in order to calculate transaction fees.
for tx in graph_update.full_txs() {
// Retrieve the calculated fee from `TxGraph`, which will panic if we do not have the
// floating txouts available from the transactions' previous outputs.
let fee = graph_update.calculate_fee(&tx.tx).expect("Fee must exist");
// Retrieve the fee in the transaction data from `bitcoind`.
let tx_fee = env
.bitcoind
.client
.get_transaction(&tx.txid, None)
.expect("Tx must exist")
.fee
.expect("Fee must exist")
.abs()
.to_unsigned()
.expect("valid `Amount`");
// Check that the calculated fee matches the fee from the transaction data.
assert_eq!(fee, tx_fee);
}
let mut graph_update_txids: Vec<Txid> = graph_update.full_txs().map(|tx| tx.txid).collect();
graph_update_txids.sort();
let mut expected_txids = vec![txid1, txid2];
expected_txids.sort();
assert_eq!(graph_update_txids, expected_txids);
Ok(())
}
/// Test the bounds of the address scan depending on the `stop_gap`.
#[test]
pub fn test_update_tx_graph_stop_gap() -> anyhow::Result<()> {
let env = TestEnv::new()?;
let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
let client = Builder::new(base_url.as_str()).build_blocking();
let _block_hashes = env.mine_blocks(101, None)?;
// Now let's test the gap limit. First of all get a chain of 10 addresses.
let addresses = [
"bcrt1qj9f7r8r3p2y0sqf4r3r62qysmkuh0fzep473d2ar7rcz64wqvhssjgf0z4",
"bcrt1qmm5t0ch7vh2hryx9ctq3mswexcugqe4atkpkl2tetm8merqkthas3w7q30",
"bcrt1qut9p7ej7l7lhyvekj28xknn8gnugtym4d5qvnp5shrsr4nksmfqsmyn87g",
"bcrt1qqz0xtn3m235p2k96f5wa2dqukg6shxn9n3txe8arlrhjh5p744hsd957ww",
"bcrt1q9c0t62a8l6wfytmf2t9lfj35avadk3mm8g4p3l84tp6rl66m48sqrme7wu",
"bcrt1qkmh8yrk2v47cklt8dytk8f3ammcwa4q7dzattedzfhqzvfwwgyzsg59zrh",
"bcrt1qvgrsrzy07gjkkfr5luplt0azxtfwmwq5t62gum5jr7zwcvep2acs8hhnp2",
"bcrt1qw57edarcg50ansq8mk3guyrk78rk0fwvrds5xvqeupteu848zayq549av8",
"bcrt1qvtve5ekf6e5kzs68knvnt2phfw6a0yjqrlgat392m6zt9jsvyxhqfx67ef",
"bcrt1qw03ddumfs9z0kcu76ln7jrjfdwam20qtffmkcral3qtza90sp9kqm787uk",
];
let addresses: Vec<_> = addresses
.into_iter()
.map(|s| Address::from_str(s).unwrap().assume_checked())
.collect();
let spks: Vec<_> = addresses
.iter()
.enumerate()
.map(|(i, addr)| (i as u32, addr.script_pubkey()))
.collect();
// Then receive coins on the 4th address.
let txid_4th_addr = env.bitcoind.client.send_to_address(
&addresses[3],
Amount::from_sat(10000),
None,
None,
None,
None,
Some(1),
None,
)?;
let _block_hashes = env.mine_blocks(1, None)?;
while client.get_height().unwrap() < 103 {
sleep(Duration::from_millis(10))
}
// use a full checkpoint linked list (since this is not what we are testing)
let cp_tip = env.make_checkpoint_tip();
// A scan with a stop_gap of 3 won't find the transaction, but a scan with a gap limit of 4
// will.
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 3, 1)?
};
assert!(full_scan_update.graph_update.full_txs().next().is_none());
assert!(full_scan_update.last_active_indices.is_empty());
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 4, 1)?
};
assert_eq!(
full_scan_update
.graph_update
.full_txs()
.next()
.unwrap()
.txid,
txid_4th_addr
);
assert_eq!(full_scan_update.last_active_indices[&0], 3);
// Now receive a coin on the last address.
let txid_last_addr = env.bitcoind.client.send_to_address(
&addresses[addresses.len() - 1],
Amount::from_sat(10000),
None,
None,
None,
None,
Some(1),
None,
)?;
let _block_hashes = env.mine_blocks(1, None)?;
while client.get_height().unwrap() < 104 {
sleep(Duration::from_millis(10))
}
// A scan with gap limit 5 won't find the second transaction, but a scan with gap limit 6 will.
// The last active indice won't be updated in the first case but will in the second one.
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 5, 1)?
};
let txs: HashSet<_> = full_scan_update
.graph_update
.full_txs()
.map(|tx| tx.txid)
.collect();
assert_eq!(txs.len(), 1);
assert!(txs.contains(&txid_4th_addr));
assert_eq!(full_scan_update.last_active_indices[&0], 3);
let full_scan_update = {
let request =
FullScanRequest::from_chain_tip(cp_tip.clone()).set_spks_for_keychain(0, spks.clone());
client.full_scan(request, 6, 1)?
};
let txs: HashSet<_> = full_scan_update
.graph_update
.full_txs()
.map(|tx| tx.txid)
.collect();
assert_eq!(txs.len(), 2);
assert!(txs.contains(&txid_4th_addr) && txs.contains(&txid_last_addr));
assert_eq!(full_scan_update.last_active_indices[&0], 9);
Ok(())
}

View File

@ -0,0 +1,19 @@
[package]
name = "bdk_file_store"
version = "0.14.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/bitcoindevkit/bdk"
documentation = "https://docs.rs/bdk_file_store"
description = "A simple append-only flat file database for persisting bdk_chain data."
keywords = ["bitcoin", "persist", "persistence", "bdk", "file"]
authors = ["Bitcoin Dev Kit Developers"]
readme = "README.md"
[dependencies]
bdk_chain = { path = "../chain", version = "0.17.0", features = [ "serde", "miniscript" ] }
bincode = { version = "1" }
serde = { version = "1", features = ["derive"] }
[dev-dependencies]
tempfile = "3"

View File

@ -0,0 +1,7 @@
# BDK File Store
This is a simple append-only flat file database for persisting [`bdk_chain`] changesets.
The main structure is [`Store`] which works with any [`bdk_chain`] based changesets to persist data into a flat file.
[`bdk_chain`]:https://docs.rs/bdk_chain/latest/bdk_chain/

View File

@ -0,0 +1,108 @@
use bincode::Options;
use std::{
fs::File,
io::{self, BufReader, Seek},
marker::PhantomData,
};
use crate::bincode_options;
/// Iterator over entries in a file store.
///
/// Reads and returns an entry each time [`next`] is called. If an error occurs while reading the
/// iterator will yield a `Result::Err(_)` instead and then `None` for the next call to `next`.
///
/// [`next`]: Self::next
pub struct EntryIter<'t, T> {
/// Buffered reader around the file
db_file: BufReader<&'t mut File>,
finished: bool,
/// The file position for the first read of `db_file`.
start_pos: Option<u64>,
types: PhantomData<T>,
}
impl<'t, T> EntryIter<'t, T> {
pub fn new(start_pos: u64, db_file: &'t mut File) -> Self {
Self {
db_file: BufReader::new(db_file),
start_pos: Some(start_pos),
finished: false,
types: PhantomData,
}
}
}
impl<'t, T> Iterator for EntryIter<'t, T>
where
T: serde::de::DeserializeOwned,
{
type Item = Result<T, IterError>;
fn next(&mut self) -> Option<Self::Item> {
if self.finished {
return None;
}
(|| {
if let Some(start) = self.start_pos.take() {
self.db_file.seek(io::SeekFrom::Start(start))?;
}
let pos_before_read = self.db_file.stream_position()?;
match bincode_options().deserialize_from(&mut self.db_file) {
Ok(changeset) => Ok(Some(changeset)),
Err(e) => {
self.finished = true;
let pos_after_read = self.db_file.stream_position()?;
// allow unexpected EOF if 0 bytes were read
if let bincode::ErrorKind::Io(inner) = &*e {
if inner.kind() == io::ErrorKind::UnexpectedEof
&& pos_after_read == pos_before_read
{
return Ok(None);
}
}
self.db_file.seek(io::SeekFrom::Start(pos_before_read))?;
Err(IterError::Bincode(*e))
}
}
})()
.transpose()
}
}
impl<'t, T> Drop for EntryIter<'t, T> {
fn drop(&mut self) {
// This syncs the underlying file's offset with the buffer's position. This way, we
// maintain the correct position to start the next read/write.
if let Ok(pos) = self.db_file.stream_position() {
let _ = self.db_file.get_mut().seek(io::SeekFrom::Start(pos));
}
}
}
/// Error type for [`EntryIter`].
#[derive(Debug)]
pub enum IterError {
/// Failure to read from the file.
Io(io::Error),
/// Failure to decode data from the file.
Bincode(bincode::ErrorKind),
}
impl core::fmt::Display for IterError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
IterError::Io(e) => write!(f, "io error trying to read entry {}", e),
IterError::Bincode(e) => write!(f, "bincode error while reading entry {}", e),
}
}
}
impl From<io::Error> for IterError {
fn from(value: io::Error) -> Self {
IterError::Io(value)
}
}
impl std::error::Error for IterError {}

View File

@ -0,0 +1,42 @@
#![doc = include_str!("../README.md")]
mod entry_iter;
mod store;
use std::io;
use bincode::{DefaultOptions, Options};
pub use entry_iter::*;
pub use store::*;
pub(crate) fn bincode_options() -> impl bincode::Options {
DefaultOptions::new().with_varint_encoding()
}
/// Error that occurs due to problems encountered with the file.
#[derive(Debug)]
pub enum FileError {
/// IO error, this may mean that the file is too short.
Io(io::Error),
/// Magic bytes do not match what is expected.
InvalidMagicBytes { got: Vec<u8>, expected: Vec<u8> },
}
impl core::fmt::Display for FileError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Io(e) => write!(f, "io error trying to read file: {}", e),
Self::InvalidMagicBytes { got, expected } => write!(
f,
"file has invalid magic bytes: expected={:?} got={:?}",
expected, got,
),
}
}
}
impl From<io::Error> for FileError {
fn from(value: io::Error) -> Self {
Self::Io(value)
}
}
impl std::error::Error for FileError {}

View File

@ -0,0 +1,443 @@
use crate::{bincode_options, EntryIter, FileError, IterError};
use bdk_chain::Merge;
use bincode::Options;
use std::{
fmt::{self, Debug},
fs::{File, OpenOptions},
io::{self, Read, Seek, Write},
marker::PhantomData,
path::Path,
};
/// Persists an append-only list of changesets (`C`) to a single file.
#[derive(Debug)]
pub struct Store<C>
where
C: Sync + Send,
{
magic_len: usize,
db_file: File,
marker: PhantomData<C>,
}
impl<C> Store<C>
where
C: Merge
+ serde::Serialize
+ serde::de::DeserializeOwned
+ core::marker::Send
+ core::marker::Sync,
{
/// Create a new [`Store`] file in write-only mode; error if the file exists.
///
/// `magic` is the prefixed bytes to write to the new file. This will be checked when opening
/// the `Store` in the future with [`open`].
///
/// [`open`]: Store::open
pub fn create_new<P>(magic: &[u8], file_path: P) -> Result<Self, FileError>
where
P: AsRef<Path>,
{
if file_path.as_ref().exists() {
// `io::Error` is used instead of a variant on `FileError` because there is already a
// nightly-only `File::create_new` method
return Err(FileError::Io(io::Error::new(
io::ErrorKind::Other,
"file already exists",
)));
}
let mut f = OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(true)
.open(file_path)?;
f.write_all(magic)?;
Ok(Self {
magic_len: magic.len(),
db_file: f,
marker: Default::default(),
})
}
/// Open an existing [`Store`].
///
/// Use [`create_new`] to create a new `Store`.
///
/// # Errors
///
/// If the prefixed bytes of the opened file does not match the provided `magic`, the
/// [`FileError::InvalidMagicBytes`] error variant will be returned.
///
/// [`create_new`]: Store::create_new
pub fn open<P>(magic: &[u8], file_path: P) -> Result<Self, FileError>
where
P: AsRef<Path>,
{
let mut f = OpenOptions::new().read(true).write(true).open(file_path)?;
let mut magic_buf = vec![0_u8; magic.len()];
f.read_exact(&mut magic_buf)?;
if magic_buf != magic {
return Err(FileError::InvalidMagicBytes {
got: magic_buf,
expected: magic.to_vec(),
});
}
Ok(Self {
magic_len: magic.len(),
db_file: f,
marker: Default::default(),
})
}
/// Attempt to open existing [`Store`] file; create it if the file is non-existent.
///
/// Internally, this calls either [`open`] or [`create_new`].
///
/// [`open`]: Store::open
/// [`create_new`]: Store::create_new
pub fn open_or_create_new<P>(magic: &[u8], file_path: P) -> Result<Self, FileError>
where
P: AsRef<Path>,
{
if file_path.as_ref().exists() {
Self::open(magic, file_path)
} else {
Self::create_new(magic, file_path)
}
}
/// Iterates over the stored changeset from first to last, changing the seek position at each
/// iteration.
///
/// The iterator may fail to read an entry and therefore return an error. However, the first time
/// it returns an error will be the last. After doing so, the iterator will always yield `None`.
///
/// **WARNING**: This method changes the write position in the underlying file. You should
/// always iterate over all entries until `None` is returned if you want your next write to go
/// at the end; otherwise, you will write over existing entries.
pub fn iter_changesets(&mut self) -> EntryIter<C> {
EntryIter::new(self.magic_len as u64, &mut self.db_file)
}
/// Loads all the changesets that have been stored as one giant changeset.
///
/// This function returns the aggregate changeset, or `None` if nothing was persisted.
/// If reading or deserializing any of the entries fails, an error is returned that
/// consists of all those it was able to read.
///
/// You should usually check the error. In many applications, it may make sense to do a full
/// wallet scan with a stop-gap after getting an error, since it is likely that one of the
/// changesets was unable to read changes of the derivation indices of a keychain.
///
/// **WARNING**: This method changes the write position of the underlying file. The next
/// changeset will be written over the erroring entry (or the end of the file if none existed).
pub fn aggregate_changesets(&mut self) -> Result<Option<C>, AggregateChangesetsError<C>> {
let mut changeset = Option::<C>::None;
for next_changeset in self.iter_changesets() {
let next_changeset = match next_changeset {
Ok(next_changeset) => next_changeset,
Err(iter_error) => {
return Err(AggregateChangesetsError {
changeset,
iter_error,
})
}
};
match &mut changeset {
Some(changeset) => changeset.merge(next_changeset),
changeset => *changeset = Some(next_changeset),
}
}
Ok(changeset)
}
/// Append a new changeset to the file and truncate the file to the end of the appended
/// changeset.
///
/// The truncation is to avoid the possibility of having a valid but inconsistent changeset
/// directly after the appended changeset.
pub fn append_changeset(&mut self, changeset: &C) -> Result<(), io::Error> {
// no need to write anything if changeset is empty
if changeset.is_empty() {
return Ok(());
}
bincode_options()
.serialize_into(&mut self.db_file, changeset)
.map_err(|e| match *e {
bincode::ErrorKind::Io(error) => error,
unexpected_err => panic!("unexpected bincode error: {}", unexpected_err),
})?;
// truncate file after this changeset addition
// if this is not done, data after this changeset may represent valid changesets, however
// applying those changesets on top of this one may result in an inconsistent state
let pos = self.db_file.stream_position()?;
self.db_file.set_len(pos)?;
Ok(())
}
}
/// Error type for [`Store::aggregate_changesets`].
#[derive(Debug)]
pub struct AggregateChangesetsError<C> {
/// The partially-aggregated changeset.
pub changeset: Option<C>,
/// The error returned by [`EntryIter`].
pub iter_error: IterError,
}
impl<C> std::fmt::Display for AggregateChangesetsError<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.iter_error, f)
}
}
impl<C: fmt::Debug> std::error::Error for AggregateChangesetsError<C> {}
#[cfg(test)]
mod test {
use super::*;
use bincode::DefaultOptions;
use std::{
collections::BTreeSet,
io::{Read, Write},
vec::Vec,
};
use tempfile::NamedTempFile;
const TEST_MAGIC_BYTES_LEN: usize = 12;
const TEST_MAGIC_BYTES: [u8; TEST_MAGIC_BYTES_LEN] =
[98, 100, 107, 102, 115, 49, 49, 49, 49, 49, 49, 49];
type TestChangeSet = BTreeSet<String>;
/// Check behavior of [`Store::create_new`] and [`Store::open`].
#[test]
fn construct_store() {
let temp_dir = tempfile::tempdir().unwrap();
let file_path = temp_dir.path().join("db_file");
let _ = Store::<TestChangeSet>::open(&TEST_MAGIC_BYTES, &file_path)
.expect_err("must not open as file does not exist yet");
let _ = Store::<TestChangeSet>::create_new(&TEST_MAGIC_BYTES, &file_path)
.expect("must create file");
// cannot create new as file already exists
let _ = Store::<TestChangeSet>::create_new(&TEST_MAGIC_BYTES, &file_path)
.expect_err("must fail as file already exists now");
let _ = Store::<TestChangeSet>::open(&TEST_MAGIC_BYTES, &file_path)
.expect("must open as file exists now");
}
#[test]
fn open_or_create_new() {
let temp_dir = tempfile::tempdir().unwrap();
let file_path = temp_dir.path().join("db_file");
let changeset = BTreeSet::from(["hello".to_string(), "world".to_string()]);
{
let mut db = Store::<TestChangeSet>::open_or_create_new(&TEST_MAGIC_BYTES, &file_path)
.expect("must create");
assert!(file_path.exists());
db.append_changeset(&changeset).expect("must succeed");
}
{
let mut db = Store::<TestChangeSet>::open_or_create_new(&TEST_MAGIC_BYTES, &file_path)
.expect("must recover");
let recovered_changeset = db.aggregate_changesets().expect("must succeed");
assert_eq!(recovered_changeset, Some(changeset));
}
}
#[test]
fn new_fails_if_file_is_too_short() {
let mut file = NamedTempFile::new().unwrap();
file.write_all(&TEST_MAGIC_BYTES[..TEST_MAGIC_BYTES_LEN - 1])
.expect("should write");
match Store::<TestChangeSet>::open(&TEST_MAGIC_BYTES, file.path()) {
Err(FileError::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof),
unexpected => panic!("unexpected result: {:?}", unexpected),
};
}
#[test]
fn new_fails_if_magic_bytes_are_invalid() {
let invalid_magic_bytes = "ldkfs0000000";
let mut file = NamedTempFile::new().unwrap();
file.write_all(invalid_magic_bytes.as_bytes())
.expect("should write");
match Store::<TestChangeSet>::open(&TEST_MAGIC_BYTES, file.path()) {
Err(FileError::InvalidMagicBytes { got, .. }) => {
assert_eq!(got, invalid_magic_bytes.as_bytes())
}
unexpected => panic!("unexpected result: {:?}", unexpected),
};
}
#[test]
fn append_changeset_truncates_invalid_bytes() {
// initial data to write to file (magic bytes + invalid data)
let mut data = [255_u8; 2000];
data[..TEST_MAGIC_BYTES_LEN].copy_from_slice(&TEST_MAGIC_BYTES);
let changeset = TestChangeSet::from(["one".into(), "two".into(), "three!".into()]);
let mut file = NamedTempFile::new().unwrap();
file.write_all(&data).expect("should write");
let mut store =
Store::<TestChangeSet>::open(&TEST_MAGIC_BYTES, file.path()).expect("should open");
match store.iter_changesets().next() {
Some(Err(IterError::Bincode(_))) => {}
unexpected_res => panic!("unexpected result: {:?}", unexpected_res),
}
store.append_changeset(&changeset).expect("should append");
drop(store);
let got_bytes = {
let mut buf = Vec::new();
file.reopen()
.unwrap()
.read_to_end(&mut buf)
.expect("should read");
buf
};
let expected_bytes = {
let mut buf = TEST_MAGIC_BYTES.to_vec();
DefaultOptions::new()
.with_varint_encoding()
.serialize_into(&mut buf, &changeset)
.expect("should encode");
buf
};
assert_eq!(got_bytes, expected_bytes);
}
#[test]
fn last_write_is_short() {
let temp_dir = tempfile::tempdir().unwrap();
let changesets = [
TestChangeSet::from(["1".into()]),
TestChangeSet::from(["2".into(), "3".into()]),
TestChangeSet::from(["4".into(), "5".into(), "6".into()]),
];
let last_changeset = TestChangeSet::from(["7".into(), "8".into(), "9".into()]);
let last_changeset_bytes = bincode_options().serialize(&last_changeset).unwrap();
for short_write_len in 1..last_changeset_bytes.len() - 1 {
let file_path = temp_dir.path().join(format!("{}.dat", short_write_len));
println!("Test file: {:?}", file_path);
// simulate creating a file, writing data where the last write is incomplete
{
let mut db =
Store::<TestChangeSet>::create_new(&TEST_MAGIC_BYTES, &file_path).unwrap();
for changeset in &changesets {
db.append_changeset(changeset).unwrap();
}
// this is the incomplete write
db.db_file
.write_all(&last_changeset_bytes[..short_write_len])
.unwrap();
}
// load file again and aggregate changesets
// write the last changeset again (this time it succeeds)
{
let mut db = Store::<TestChangeSet>::open(&TEST_MAGIC_BYTES, &file_path).unwrap();
let err = db
.aggregate_changesets()
.expect_err("should return error as last read is short");
assert_eq!(
err.changeset,
changesets.iter().cloned().reduce(|mut acc, cs| {
Merge::merge(&mut acc, cs);
acc
}),
"should recover all changesets that are written in full",
);
db.db_file.write_all(&last_changeset_bytes).unwrap();
}
// load file again - this time we should successfully aggregate all changesets
{
let mut db = Store::<TestChangeSet>::open(&TEST_MAGIC_BYTES, &file_path).unwrap();
let aggregated_changesets = db
.aggregate_changesets()
.expect("aggregating all changesets should succeed");
assert_eq!(
aggregated_changesets,
changesets
.iter()
.cloned()
.chain(core::iter::once(last_changeset.clone()))
.reduce(|mut acc, cs| {
Merge::merge(&mut acc, cs);
acc
}),
"should recover all changesets",
);
}
}
}
#[test]
fn write_after_short_read() {
let temp_dir = tempfile::tempdir().unwrap();
let changesets = (0..20)
.map(|n| TestChangeSet::from([format!("{}", n)]))
.collect::<Vec<_>>();
let last_changeset = TestChangeSet::from(["last".into()]);
for read_count in 0..changesets.len() {
let file_path = temp_dir.path().join(format!("{}.dat", read_count));
println!("Test file: {:?}", file_path);
// First, we create the file with all the changesets!
let mut db = Store::<TestChangeSet>::create_new(&TEST_MAGIC_BYTES, &file_path).unwrap();
for changeset in &changesets {
db.append_changeset(changeset).unwrap();
}
drop(db);
// We re-open the file and read `read_count` number of changesets.
let mut db = Store::<TestChangeSet>::open(&TEST_MAGIC_BYTES, &file_path).unwrap();
let mut exp_aggregation = db
.iter_changesets()
.take(read_count)
.map(|r| r.expect("must read valid changeset"))
.fold(TestChangeSet::default(), |mut acc, v| {
Merge::merge(&mut acc, v);
acc
});
// We write after a short read.
db.append_changeset(&last_changeset)
.expect("last write must succeed");
Merge::merge(&mut exp_aggregation, last_changeset.clone());
drop(db);
// We open the file again and check whether aggregate changeset is expected.
let aggregation = Store::<TestChangeSet>::open(&TEST_MAGIC_BYTES, &file_path)
.unwrap()
.aggregate_changesets()
.expect("must aggregate changesets")
.unwrap_or_default();
assert_eq!(aggregation, exp_aggregation);
}
}
}

13
crates/hwi/Cargo.toml Normal file
View File

@ -0,0 +1,13 @@
[package]
name = "bdk_hwi"
version = "0.4.0"
edition = "2021"
homepage = "https://bitcoindevkit.org"
repository = "https://github.com/bitcoindevkit/bdk"
description = "Utilities to use bdk with hardware wallets"
license = "MIT OR Apache-2.0"
readme = "README.md"
[dependencies]
bdk_wallet = { path = "../wallet", version = "1.0.0-beta.1" }
hwi = { version = "0.9.0", features = [ "miniscript"] }

3
crates/hwi/README.md Normal file
View File

@ -0,0 +1,3 @@
# BDK HWI Signer
This crate contains `HWISigner`, an implementation of a `TransactionSigner` to be used with hardware wallets.

39
crates/hwi/src/lib.rs Normal file
View File

@ -0,0 +1,39 @@
//! HWI Signer
//!
//! This crate contains HWISigner, an implementation of a [`TransactionSigner`] to be
//! used with hardware wallets.
//! ```no_run
//! # use bdk_wallet::bitcoin::Network;
//! # use bdk_wallet::descriptor::Descriptor;
//! # use bdk_wallet::signer::SignerOrdering;
//! # use bdk_hwi::HWISigner;
//! # use bdk_wallet::{KeychainKind, SignOptions, Wallet};
//! # use hwi::HWIClient;
//! # use std::sync::Arc;
//! # use std::str::FromStr;
//! #
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut devices = HWIClient::enumerate()?;
//! if devices.is_empty() {
//! panic!("No devices found!");
//! }
//! let first_device = devices.remove(0)?;
//! let custom_signer = HWISigner::from_device(&first_device, Network::Testnet.into())?;
//!
//! # let mut wallet = Wallet::create("", "").network(Network::Testnet).create_wallet_no_persist()?;
//! #
//! // Adding the hardware signer to the BDK wallet
//! wallet.add_signer(
//! KeychainKind::External,
//! SignerOrdering(200),
//! Arc::new(custom_signer),
//! );
//!
//! # Ok(())
//! # }
//! ```
//!
//! [`TransactionSigner`]: bdk_wallet::signer::TransactionSigner
mod signer;
pub use signer::*;

94
crates/hwi/src/signer.rs Normal file
View File

@ -0,0 +1,94 @@
use bdk_wallet::bitcoin::bip32::Fingerprint;
use bdk_wallet::bitcoin::secp256k1::{All, Secp256k1};
use bdk_wallet::bitcoin::Psbt;
use hwi::error::Error;
use hwi::types::{HWIChain, HWIDevice};
use hwi::HWIClient;
use bdk_wallet::signer::{SignerCommon, SignerError, SignerId, TransactionSigner};
#[derive(Debug)]
/// Custom signer for Hardware Wallets
///
/// This ignores `sign_options` and leaves the decisions up to the hardware wallet.
pub struct HWISigner {
fingerprint: Fingerprint,
client: HWIClient,
}
impl HWISigner {
/// Create a instance from the specified device and chain
pub fn from_device(device: &HWIDevice, chain: HWIChain) -> Result<HWISigner, Error> {
let client = HWIClient::get_client(device, false, chain)?;
Ok(HWISigner {
fingerprint: device.fingerprint,
client,
})
}
}
impl SignerCommon for HWISigner {
fn id(&self, _secp: &Secp256k1<All>) -> SignerId {
SignerId::Fingerprint(self.fingerprint)
}
}
impl TransactionSigner for HWISigner {
fn sign_transaction(
&self,
psbt: &mut Psbt,
_sign_options: &bdk_wallet::SignOptions,
_secp: &Secp256k1<All>,
) -> Result<(), SignerError> {
psbt.combine(
self.client
.sign_tx(psbt)
.map_err(|e| {
SignerError::External(format!("While signing with hardware wallet: {}", e))
})?
.psbt,
)
.expect("Failed to combine HW signed psbt with passed PSBT");
Ok(())
}
}
// TODO: re-enable this once we have the `get_funded_wallet` test util
// #[cfg(test)]
// mod tests {
// #[test]
// fn test_hardware_signer() {
// use std::sync::Arc;
//
// use bdk_wallet::tests::get_funded_wallet;
// use bdk_wallet::signer::SignerOrdering;
// use bdk_wallet::bitcoin::Network;
// use crate::HWISigner;
// use hwi::HWIClient;
//
// let mut devices = HWIClient::enumerate().unwrap();
// if devices.is_empty() {
// panic!("No devices found!");
// }
// let device = devices.remove(0).unwrap();
// let client = HWIClient::get_client(&device, true, Network::Regtest.into()).unwrap();
// let descriptors = client.get_descriptors::<String>(None).unwrap();
// let custom_signer = HWISigner::from_device(&device, Network::Regtest.into()).unwrap();
//
// let (mut wallet, _) = get_funded_wallet(&descriptors.internal[0]);
// wallet.add_signer(
// bdk_wallet::KeychainKind::External,
// SignerOrdering(200),
// Arc::new(custom_signer),
// );
//
// let addr = wallet.get_address(bdk_wallet::AddressIndex::LastUnused);
// let mut builder = wallet.build_tx();
// builder.drain_to(addr.script_pubkey()).drain_wallet();
// let (mut psbt, _) = builder.finish().unwrap();
//
// let finalized = wallet.sign(&mut psbt, Default::default()).unwrap();
// assert!(finalized);
// }
// }

22
crates/testenv/Cargo.toml Normal file
View File

@ -0,0 +1,22 @@
[package]
name = "bdk_testenv"
version = "0.7.0"
edition = "2021"
rust-version = "1.63"
homepage = "https://bitcoindevkit.org"
repository = "https://github.com/bitcoindevkit/bdk"
documentation = "https://docs.rs/bdk_testenv"
description = "Testing framework for BDK chain sources."
license = "MIT OR Apache-2.0"
readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bdk_chain = { path = "../chain", version = "0.17", default-features = false }
electrsd = { version = "0.28.0", features = ["bitcoind_25_0", "esplora_a33e97e1", "legacy"] }
[features]
default = ["std"]
std = ["bdk_chain/std"]
serde = ["bdk_chain/serde"]

6
crates/testenv/README.md Normal file
View File

@ -0,0 +1,6 @@
# BDK TestEnv
This crate sets up a regtest environment with a single [`bitcoind`] node
connected to an [`electrs`] instance. This framework provides the infrastructure
for testing chain source crates, e.g., [`bdk_chain`], [`bdk_electrum`],
[`bdk_esplora`], etc.

304
crates/testenv/src/lib.rs Normal file
View File

@ -0,0 +1,304 @@
use bdk_chain::{
bitcoin::{
address::NetworkChecked, block::Header, hash_types::TxMerkleNode, hashes::Hash,
secp256k1::rand::random, transaction, Address, Amount, Block, BlockHash, CompactTarget,
ScriptBuf, ScriptHash, Transaction, TxIn, TxOut, Txid,
},
local_chain::CheckPoint,
BlockId,
};
use bitcoincore_rpc::{
bitcoincore_rpc_json::{GetBlockTemplateModes, GetBlockTemplateRules},
RpcApi,
};
pub use electrsd;
pub use electrsd::bitcoind;
pub use electrsd::bitcoind::anyhow;
pub use electrsd::bitcoind::bitcoincore_rpc;
pub use electrsd::electrum_client;
use electrsd::electrum_client::ElectrumApi;
use std::time::Duration;
/// Struct for running a regtest environment with a single `bitcoind` node with an `electrs`
/// instance connected to it.
pub struct TestEnv {
pub bitcoind: electrsd::bitcoind::BitcoinD,
pub electrsd: electrsd::ElectrsD,
}
impl TestEnv {
/// Construct a new [`TestEnv`] instance with default configurations.
pub fn new() -> anyhow::Result<Self> {
let bitcoind = match std::env::var_os("BITCOIND_EXE") {
Some(bitcoind_path) => electrsd::bitcoind::BitcoinD::new(bitcoind_path),
None => {
let bitcoind_exe = electrsd::bitcoind::downloaded_exe_path()
.expect(
"you need to provide an env var BITCOIND_EXE or specify a bitcoind version feature",
);
electrsd::bitcoind::BitcoinD::with_conf(
bitcoind_exe,
&electrsd::bitcoind::Conf::default(),
)
}
}?;
let mut electrsd_conf = electrsd::Conf::default();
electrsd_conf.http_enabled = true;
let electrsd = match std::env::var_os("ELECTRS_EXE") {
Some(env_electrs_exe) => {
electrsd::ElectrsD::with_conf(env_electrs_exe, &bitcoind, &electrsd_conf)
}
None => {
let electrs_exe = electrsd::downloaded_exe_path()
.expect("electrs version feature must be enabled");
electrsd::ElectrsD::with_conf(electrs_exe, &bitcoind, &electrsd_conf)
}
}?;
Ok(Self { bitcoind, electrsd })
}
/// Exposes the [`ElectrumApi`] calls from the Electrum client.
pub fn electrum_client(&self) -> &impl ElectrumApi {
&self.electrsd.client
}
/// Exposes the [`RpcApi`] calls from [`bitcoincore_rpc`].
pub fn rpc_client(&self) -> &impl RpcApi {
&self.bitcoind.client
}
// Reset `electrsd` so that new blocks can be seen.
pub fn reset_electrsd(mut self) -> anyhow::Result<Self> {
let mut electrsd_conf = electrsd::Conf::default();
electrsd_conf.http_enabled = true;
let electrsd = match std::env::var_os("ELECTRS_EXE") {
Some(env_electrs_exe) => {
electrsd::ElectrsD::with_conf(env_electrs_exe, &self.bitcoind, &electrsd_conf)
}
None => {
let electrs_exe = electrsd::downloaded_exe_path()
.expect("electrs version feature must be enabled");
electrsd::ElectrsD::with_conf(electrs_exe, &self.bitcoind, &electrsd_conf)
}
}?;
self.electrsd = electrsd;
Ok(self)
}
/// Mine a number of blocks of a given size `count`, which may be specified to a given coinbase
/// `address`.
pub fn mine_blocks(
&self,
count: usize,
address: Option<Address>,
) -> anyhow::Result<Vec<BlockHash>> {
let coinbase_address = match address {
Some(address) => address,
None => self
.bitcoind
.client
.get_new_address(None, None)?
.assume_checked(),
};
let block_hashes = self
.bitcoind
.client
.generate_to_address(count as _, &coinbase_address)?;
Ok(block_hashes)
}
/// Mine a block that is guaranteed to be empty even with transactions in the mempool.
pub fn mine_empty_block(&self) -> anyhow::Result<(usize, BlockHash)> {
let bt = self.bitcoind.client.get_block_template(
GetBlockTemplateModes::Template,
&[GetBlockTemplateRules::SegWit],
&[],
)?;
let txdata = vec![Transaction {
version: transaction::Version::ONE,
lock_time: bdk_chain::bitcoin::absolute::LockTime::from_height(0)?,
input: vec![TxIn {
previous_output: bdk_chain::bitcoin::OutPoint::default(),
script_sig: ScriptBuf::builder()
.push_int(bt.height as _)
// randomn number so that re-mining creates unique block
.push_int(random())
.into_script(),
sequence: bdk_chain::bitcoin::Sequence::default(),
witness: bdk_chain::bitcoin::Witness::new(),
}],
output: vec![TxOut {
value: Amount::ZERO,
script_pubkey: ScriptBuf::new_p2sh(&ScriptHash::all_zeros()),
}],
}];
let bits: [u8; 4] = bt
.bits
.clone()
.try_into()
.expect("rpc provided us with invalid bits");
let mut block = Block {
header: Header {
version: bdk_chain::bitcoin::block::Version::default(),
prev_blockhash: bt.previous_block_hash,
merkle_root: TxMerkleNode::all_zeros(),
time: Ord::max(bt.min_time, std::time::UNIX_EPOCH.elapsed()?.as_secs()) as u32,
bits: CompactTarget::from_consensus(u32::from_be_bytes(bits)),
nonce: 0,
},
txdata,
};
block.header.merkle_root = block.compute_merkle_root().expect("must compute");
for nonce in 0..=u32::MAX {
block.header.nonce = nonce;
if block.header.target().is_met_by(block.block_hash()) {
break;
}
}
self.bitcoind.client.submit_block(&block)?;
Ok((bt.height as usize, block.block_hash()))
}
/// This method waits for the Electrum notification indicating that a new block has been mined.
pub fn wait_until_electrum_sees_block(&self) -> anyhow::Result<()> {
self.electrsd.client.block_headers_subscribe()?;
let mut delay = Duration::from_millis(64);
loop {
self.electrsd.trigger()?;
self.electrsd.client.ping()?;
if self.electrsd.client.block_headers_pop()?.is_some() {
return Ok(());
}
if delay.as_millis() < 512 {
delay = delay.mul_f32(2.0);
}
std::thread::sleep(delay);
}
}
/// Invalidate a number of blocks of a given size `count`.
pub fn invalidate_blocks(&self, count: usize) -> anyhow::Result<()> {
let mut hash = self.bitcoind.client.get_best_block_hash()?;
for _ in 0..count {
let prev_hash = self
.bitcoind
.client
.get_block_info(&hash)?
.previousblockhash;
self.bitcoind.client.invalidate_block(&hash)?;
match prev_hash {
Some(prev_hash) => hash = prev_hash,
None => break,
}
}
Ok(())
}
/// Reorg a number of blocks of a given size `count`.
/// Refer to [`TestEnv::mine_empty_block`] for more information.
pub fn reorg(&self, count: usize) -> anyhow::Result<Vec<BlockHash>> {
let start_height = self.bitcoind.client.get_block_count()?;
self.invalidate_blocks(count)?;
let res = self.mine_blocks(count, None);
assert_eq!(
self.bitcoind.client.get_block_count()?,
start_height,
"reorg should not result in height change"
);
res
}
/// Reorg with a number of empty blocks of a given size `count`.
pub fn reorg_empty_blocks(&self, count: usize) -> anyhow::Result<Vec<(usize, BlockHash)>> {
let start_height = self.bitcoind.client.get_block_count()?;
self.invalidate_blocks(count)?;
let res = (0..count)
.map(|_| self.mine_empty_block())
.collect::<Result<Vec<_>, _>>()?;
assert_eq!(
self.bitcoind.client.get_block_count()?,
start_height,
"reorg should not result in height change"
);
Ok(res)
}
/// Send a tx of a given `amount` to a given `address`.
pub fn send(&self, address: &Address<NetworkChecked>, amount: Amount) -> anyhow::Result<Txid> {
let txid = self
.bitcoind
.client
.send_to_address(address, amount, None, None, None, None, None, None)?;
Ok(txid)
}
/// Create a checkpoint linked list of all the blocks in the chain.
pub fn make_checkpoint_tip(&self) -> CheckPoint {
CheckPoint::from_block_ids((0_u32..).map_while(|height| {
self.bitcoind
.client
.get_block_hash(height as u64)
.ok()
.map(|hash| BlockId { height, hash })
}))
.expect("must craft tip")
}
/// Get the genesis hash of the blockchain.
pub fn genesis_hash(&self) -> anyhow::Result<BlockHash> {
let hash = self.bitcoind.client.get_block_hash(0)?;
Ok(hash)
}
}
#[cfg(test)]
mod test {
use crate::TestEnv;
use electrsd::bitcoind::{anyhow::Result, bitcoincore_rpc::RpcApi};
/// This checks that reorgs initiated by `bitcoind` is detected by our `electrsd` instance.
#[test]
fn test_reorg_is_detected_in_electrsd() -> Result<()> {
let env = TestEnv::new()?;
// Mine some blocks.
env.mine_blocks(101, None)?;
env.wait_until_electrum_sees_block()?;
let height = env.bitcoind.client.get_block_count()?;
let blocks = (0..=height)
.map(|i| env.bitcoind.client.get_block_hash(i))
.collect::<Result<Vec<_>, _>>()?;
// Perform reorg on six blocks.
env.reorg(6)?;
env.wait_until_electrum_sees_block()?;
let reorged_height = env.bitcoind.client.get_block_count()?;
let reorged_blocks = (0..=height)
.map(|i| env.bitcoind.client.get_block_hash(i))
.collect::<Result<Vec<_>, _>>()?;
assert_eq!(height, reorged_height);
// Block hashes should not be equal on the six reorged blocks.
for (i, (block, reorged_block)) in blocks.iter().zip(reorged_blocks.iter()).enumerate() {
match i <= height as usize - 6 {
true => assert_eq!(block, reorged_block),
false => assert_ne!(block, reorged_block),
}
}
Ok(())
}
}

58
crates/wallet/Cargo.toml Normal file
View File

@ -0,0 +1,58 @@
[package]
name = "bdk_wallet"
homepage = "https://bitcoindevkit.org"
version = "1.0.0-beta.1"
repository = "https://github.com/bitcoindevkit/bdk"
documentation = "https://docs.rs/bdk"
description = "A modern, lightweight, descriptor-based wallet library"
keywords = ["bitcoin", "wallet", "descriptor", "psbt"]
readme = "README.md"
license = "MIT OR Apache-2.0"
authors = ["Bitcoin Dev Kit Developers"]
edition = "2021"
rust-version = "1.63"
[dependencies]
rand_core = { version = "0.6.0" }
miniscript = { version = "12.0.0", features = ["serde"], default-features = false }
bitcoin = { version = "0.32.0", features = ["serde", "base64"], default-features = false }
serde = { version = "^1.0", features = ["derive"] }
serde_json = { version = "^1.0" }
bdk_chain = { path = "../chain", version = "0.17.0", features = ["miniscript", "serde"], default-features = false }
bdk_file_store = { path = "../file_store", version = "0.14.0", optional = true }
# Optional dependencies
bip39 = { version = "2.0", optional = true }
[features]
default = ["std"]
std = ["bitcoin/std", "bitcoin/rand-std", "miniscript/std", "bdk_chain/std"]
compiler = ["miniscript/compiler"]
all-keys = ["keys-bip39"]
keys-bip39 = ["bip39"]
rusqlite = ["bdk_chain/rusqlite"]
file_store = ["bdk_file_store"]
[dev-dependencies]
lazy_static = "1.4"
assert_matches = "1.5.0"
tempfile = "3"
bdk_chain = { path = "../chain", features = ["rusqlite"] }
bdk_wallet = { path = ".", features = ["rusqlite", "file_store"] }
bdk_file_store = { path = "../file_store" }
anyhow = "1"
rand = "^0.8"
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[[example]]
name = "mnemonic_to_descriptors"
path = "examples/mnemonic_to_descriptors.rs"
required-features = ["all-keys"]
[[example]]
name = "miniscriptc"
path = "examples/compiler.rs"
required-features = ["compiler"]

243
crates/wallet/README.md Normal file
View File

@ -0,0 +1,243 @@
<div align="center">
<h1>BDK</h1>
<img src="https://raw.githubusercontent.com/bitcoindevkit/bdk/master/static/bdk.png" width="220" />
<p>
<strong>A modern, lightweight, descriptor-based wallet library written in Rust!</strong>
</p>
<p>
<a href="https://crates.io/crates/bdk_wallet"><img alt="Crate Info" src="https://img.shields.io/crates/v/bdk_wallet.svg"/></a>
<a href="https://github.com/bitcoindevkit/bdk/blob/master/LICENSE"><img alt="MIT or Apache-2.0 Licensed" src="https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg"/></a>
<a href="https://github.com/bitcoindevkit/bdk/actions?query=workflow%3ACI"><img alt="CI Status" src="https://github.com/bitcoindevkit/bdk/workflows/CI/badge.svg"></a>
<a href="https://coveralls.io/github/bitcoindevkit/bdk?branch=master"><img src="https://coveralls.io/repos/github/bitcoindevkit/bdk/badge.svg?branch=master"/></a>
<a href="https://docs.rs/bdk_wallet"><img alt="API Docs" src="https://img.shields.io/badge/docs.rs-bdk_wallet-green"/></a>
<a href="https://blog.rust-lang.org/2022/08/11/Rust-1.63.0.html"><img alt="Rustc Version 1.63.0+" src="https://img.shields.io/badge/rustc-1.63.0%2B-lightgrey.svg"/></a>
<a href="https://discord.gg/d7NkDKm"><img alt="Chat on Discord" src="https://img.shields.io/discord/753336465005608961?logo=discord"></a>
</p>
<h4>
<a href="https://bitcoindevkit.org">Project Homepage</a>
<span> | </span>
<a href="https://docs.rs/bdk_wallet">Documentation</a>
</h4>
</div>
# BDK Wallet
The `bdk_wallet` crate provides the [`Wallet`] type which is a simple, high-level
interface built from the low-level components of [`bdk_chain`]. `Wallet` is a good starting point
for many simple applications as well as a good demonstration of how to use the other mechanisms to
construct a wallet. It has two keychains (external and internal) which are defined by
[miniscript descriptors][`rust-miniscript`] and uses them to generate addresses. When you give it
chain data it also uses the descriptors to find transaction outputs owned by them. From there, you
can create and sign transactions.
For details about the API of `Wallet` see the [module-level documentation][`Wallet`].
## Blockchain data
In order to get blockchain data for `Wallet` to consume, you should configure a client from
an available chain source. Typically you make a request to the chain source and get a response
that the `Wallet` can use to update its view of the chain.
**Blockchain Data Sources**
* [`bdk_esplora`]: Grabs blockchain data from Esplora for updating BDK structures.
* [`bdk_electrum`]: Grabs blockchain data from Electrum for updating BDK structures.
* [`bdk_bitcoind_rpc`]: Grabs blockchain data from Bitcoin Core for updating BDK structures.
**Examples**
* [`example-crates/wallet_esplora_async`](https://github.com/bitcoindevkit/bdk/tree/master/example-crates/wallet_esplora_async)
* [`example-crates/wallet_esplora_blocking`](https://github.com/bitcoindevkit/bdk/tree/master/example-crates/wallet_esplora_blocking)
* [`example-crates/wallet_electrum`](https://github.com/bitcoindevkit/bdk/tree/master/example-crates/wallet_electrum)
* [`example-crates/wallet_rpc`](https://github.com/bitcoindevkit/bdk/tree/master/example-crates/wallet_rpc)
## Persistence
To persist `Wallet` state data use a data store crate that reads and writes [`ChangeSet`].
**Implementations**
* [`bdk_file_store`]: Stores wallet changes in a simple flat file.
**Example**
<!-- compile_fail because outpoint and txout are fake variables -->
```rust,no_run
use bdk_wallet::{bitcoin::Network, KeychainKind, ChangeSet, Wallet};
// Open or create a new file store for wallet data.
let mut db =
bdk_file_store::Store::<ChangeSet>::open_or_create_new(b"magic_bytes", "/tmp/my_wallet.db")
.expect("create store");
// Create a wallet with initial wallet data read from the file store.
let network = Network::Testnet;
let descriptor = "wpkh(tprv8ZgxMBicQKsPdcAqYBpzAFwU5yxBUo88ggoBqu1qPcHUfSbKK1sKMLmC7EAk438btHQrSdu3jGGQa6PA71nvH5nkDexhLteJqkM4dQmWF9g/84'/1'/0'/0/*)";
let change_descriptor = "wpkh(tprv8ZgxMBicQKsPdcAqYBpzAFwU5yxBUo88ggoBqu1qPcHUfSbKK1sKMLmC7EAk438btHQrSdu3jGGQa6PA71nvH5nkDexhLteJqkM4dQmWF9g/84'/1'/0'/1/*)";
let wallet_opt = Wallet::load()
.descriptors(descriptor, change_descriptor)
.network(network)
.load_wallet(&mut db)
.expect("wallet");
let mut wallet = match wallet_opt {
Some(wallet) => wallet,
None => Wallet::create(descriptor, change_descriptor)
.network(network)
.create_wallet(&mut db)
.expect("wallet"),
};
// Get a new address to receive bitcoin.
let receive_address = wallet.reveal_next_address(KeychainKind::External);
// Persist staged wallet data changes to the file store.
wallet.persist(&mut db).expect("persist");
println!("Your new receive address is: {}", receive_address.address);
```
<!-- ### Sync the balance of a descriptor -->
<!-- ```rust,no_run -->
<!-- use bdk_wallet::Wallet; -->
<!-- use bdk_wallet::blockchain::ElectrumBlockchain; -->
<!-- use bdk_wallet::SyncOptions; -->
<!-- use bdk_wallet::electrum_client::Client; -->
<!-- use bdk_wallet::bitcoin::Network; -->
<!-- fn main() -> Result<(), bdk_wallet::Error> { -->
<!-- let blockchain = ElectrumBlockchain::from(Client::new("ssl://electrum.blockstream.info:60002")?); -->
<!-- let wallet = Wallet::new( -->
<!-- "wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)", -->
<!-- Some("wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/1/*)"), -->
<!-- Network::Testnet, -->
<!-- )?; -->
<!-- wallet.sync(&blockchain, SyncOptions::default())?; -->
<!-- println!("Descriptor balance: {} SAT", wallet.balance()?); -->
<!-- Ok(()) -->
<!-- } -->
<!-- ``` -->
<!-- ### Generate a few addresses -->
<!-- ```rust -->
<!-- use bdk_wallet::Wallet; -->
<!-- use bdk_wallet::AddressIndex::New; -->
<!-- use bdk_wallet::bitcoin::Network; -->
<!-- fn main() -> Result<(), bdk_wallet::Error> { -->
<!-- let wallet = Wallet::new( -->
<!-- "wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)", -->
<!-- Some("wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/1/*)"), -->
<!-- Network::Testnet, -->
<!-- )?; -->
<!-- println!("Address #0: {}", wallet.get_address(New)); -->
<!-- println!("Address #1: {}", wallet.get_address(New)); -->
<!-- println!("Address #2: {}", wallet.get_address(New)); -->
<!-- Ok(()) -->
<!-- } -->
<!-- ``` -->
<!-- ### Create a transaction -->
<!-- ```rust,no_run -->
<!-- use bdk_wallet::{FeeRate, Wallet, SyncOptions}; -->
<!-- use bdk_wallet::blockchain::ElectrumBlockchain; -->
<!-- use bdk_wallet::electrum_client::Client; -->
<!-- use bdk_wallet::AddressIndex::New; -->
<!-- use bitcoin::base64; -->
<!-- use bdk_wallet::bitcoin::consensus::serialize; -->
<!-- use bdk_wallet::bitcoin::Network; -->
<!-- fn main() -> Result<(), bdk_wallet::Error> { -->
<!-- let blockchain = ElectrumBlockchain::from(Client::new("ssl://electrum.blockstream.info:60002")?); -->
<!-- let wallet = Wallet::new( -->
<!-- "wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)", -->
<!-- Some("wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/1/*)"), -->
<!-- Network::Testnet, -->
<!-- )?; -->
<!-- wallet.sync(&blockchain, SyncOptions::default())?; -->
<!-- let send_to = wallet.get_address(New); -->
<!-- let (psbt, details) = { -->
<!-- let mut builder = wallet.build_tx(); -->
<!-- builder -->
<!-- .add_recipient(send_to.script_pubkey(), 50_000) -->
<!-- .enable_rbf() -->
<!-- .do_not_spend_change() -->
<!-- .fee_rate(FeeRate::from_sat_per_vb(5.0)); -->
<!-- builder.finish()? -->
<!-- }; -->
<!-- println!("Transaction details: {:#?}", details); -->
<!-- println!("Unsigned PSBT: {}", base64::encode(&serialize(&psbt))); -->
<!-- Ok(()) -->
<!-- } -->
<!-- ``` -->
<!-- ### Sign a transaction -->
<!-- ```rust,no_run -->
<!-- use bdk_wallet::{Wallet, SignOptions}; -->
<!-- use bitcoin::base64; -->
<!-- use bdk_wallet::bitcoin::consensus::deserialize; -->
<!-- use bdk_wallet::bitcoin::Network; -->
<!-- fn main() -> Result<(), bdk_wallet::Error> { -->
<!-- let wallet = Wallet::new( -->
<!-- "wpkh([c258d2e4/84h/1h/0h]tprv8griRPhA7342zfRyB6CqeKF8CJDXYu5pgnj1cjL1u2ngKcJha5jjTRimG82ABzJQ4MQe71CV54xfn25BbhCNfEGGJZnxvCDQCd6JkbvxW6h/0/*)", -->
<!-- Some("wpkh([c258d2e4/84h/1h/0h]tprv8griRPhA7342zfRyB6CqeKF8CJDXYu5pgnj1cjL1u2ngKcJha5jjTRimG82ABzJQ4MQe71CV54xfn25BbhCNfEGGJZnxvCDQCd6JkbvxW6h/1/*)"), -->
<!-- Network::Testnet, -->
<!-- )?; -->
<!-- let psbt = "..."; -->
<!-- let mut psbt = deserialize(&base64::decode(psbt).unwrap())?; -->
<!-- let _finalized = wallet.sign(&mut psbt, SignOptions::default())?; -->
<!-- Ok(()) -->
<!-- } -->
<!-- ``` -->
## Testing
### Unit testing
```bash
cargo test
```
# License
Licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](../../LICENSE-APACHE) or <https://www.apache.org/licenses/LICENSE-2.0>)
* MIT license ([LICENSE-MIT](../../LICENSE-MIT) or <https://opensource.org/licenses/MIT>)
at your option.
# Contribution
Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache-2.0
license, shall be dual licensed as above, without any additional terms or
conditions.
[`Wallet`]: https://docs.rs/bdk_wallet/latest/bdk_wallet/wallet/struct.Wallet.html
[`bdk_chain`]: https://docs.rs/bdk_chain/latest
[`bdk_file_store`]: https://docs.rs/bdk_file_store/latest
[`bdk_electrum`]: https://docs.rs/bdk_electrum/latest
[`bdk_esplora`]: https://docs.rs/bdk_esplora/latest
[`bdk_bitcoind_rpc`]: https://docs.rs/bdk_bitcoind_rpc/latest
[`rust-miniscript`]: https://docs.rs/miniscript/latest/miniscript/index.html

View File

@ -0,0 +1,98 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
extern crate bdk_wallet;
extern crate bitcoin;
extern crate miniscript;
extern crate serde_json;
use std::error::Error;
use std::str::FromStr;
use bitcoin::Network;
use miniscript::policy::Concrete;
use miniscript::Descriptor;
use bdk_wallet::{KeychainKind, Wallet};
/// Miniscript policy is a high level abstraction of spending conditions. Defined in the
/// rust-miniscript library here https://docs.rs/miniscript/7.0.0/miniscript/policy/index.html
/// rust-miniscript provides a `compile()` function that can be used to compile any miniscript policy
/// into a descriptor. This descriptor then in turn can be used in bdk a fully functioning wallet
/// can be derived from the policy.
///
/// This example demonstrates the interaction between a bdk wallet and miniscript policy.
fn main() -> Result<(), Box<dyn Error>> {
// We start with a miniscript policy string
let policy_str = "or(
10@thresh(4,
pk(029ffbe722b147f3035c87cb1c60b9a5947dd49c774cc31e94773478711a929ac0),pk(025f05815e3a1a8a83bfbb03ce016c9a2ee31066b98f567f6227df1d76ec4bd143),pk(025625f41e4a065efc06d5019cbbd56fe8c07595af1231e7cbc03fafb87ebb71ec),pk(02a27c8b850a00f67da3499b60562673dcf5fdfb82b7e17652a7ac54416812aefd),pk(03e618ec5f384d6e19ca9ebdb8e2119e5bef978285076828ce054e55c4daf473e2)
),1@and(
older(4209713),
thresh(2,
pk(03deae92101c790b12653231439f27b8897264125ecb2f46f48278603102573165),pk(033841045a531e1adf9910a6ec279589a90b3b8a904ee64ffd692bd08a8996c1aa),pk(02aebf2d10b040eb936a6f02f44ee82f8b34f5c1ccb20ff3949c2b28206b7c1068)
)
)
)"
.replace(&[' ', '\n', '\t'][..], "");
println!("Compiling policy: \n{}", policy_str);
// Parse the string as a [`Concrete`] type miniscript policy.
let policy = Concrete::<String>::from_str(&policy_str)?;
// Create a `wsh` type descriptor from the policy.
// `policy.compile()` returns the resulting miniscript from the policy.
let descriptor = Descriptor::new_wsh(policy.compile()?)?.to_string();
println!("Compiled into Descriptor: \n{}", descriptor);
// Do the same for another (internal) keychain
let policy_str = "or(
10@thresh(2,
pk(029ffbe722b147f3035c87cb1c60b9a5947dd49c774cc31e94773478711a929ac0),pk(025f05815e3a1a8a83bfbb03ce016c9a2ee31066b98f567f6227df1d76ec4bd143),pk(025625f41e4a065efc06d5019cbbd56fe8c07595af1231e7cbc03fafb87ebb71ec)
),1@and(
pk(03deae92101c790b12653231439f27b8897264125ecb2f46f48278603102573165),
older(12960)
)
)"
.replace(&[' ', '\n', '\t'][..], "");
println!("Compiling internal policy: \n{}", policy_str);
let policy = Concrete::<String>::from_str(&policy_str)?;
let internal_descriptor = Descriptor::new_wsh(policy.compile()?)?.to_string();
println!(
"Compiled into internal Descriptor: \n{}",
internal_descriptor
);
// Create a new wallet from descriptors
let mut wallet = Wallet::create(descriptor, internal_descriptor)
.network(Network::Regtest)
.create_wallet_no_persist()?;
println!(
"First derived address from the descriptor: \n{}",
wallet.next_unused_address(KeychainKind::External),
);
// BDK also has it's own `Policy` structure to represent the spending condition in a more
// human readable json format.
let spending_policy = wallet.policies(KeychainKind::External)?;
println!(
"The BDK spending policy: \n{}",
serde_json::to_string_pretty(&spending_policy)?
);
Ok(())
}

View File

@ -0,0 +1,59 @@
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
use anyhow::anyhow;
use bdk_wallet::bitcoin::bip32::DerivationPath;
use bdk_wallet::bitcoin::secp256k1::Secp256k1;
use bdk_wallet::bitcoin::Network;
use bdk_wallet::descriptor;
use bdk_wallet::descriptor::IntoWalletDescriptor;
use bdk_wallet::keys::bip39::{Language, Mnemonic, WordCount};
use bdk_wallet::keys::{GeneratableKey, GeneratedKey};
use bdk_wallet::miniscript::Tap;
use std::str::FromStr;
/// This example demonstrates how to generate a mnemonic phrase
/// using BDK and use that to generate a descriptor string.
fn main() -> Result<(), anyhow::Error> {
let secp = Secp256k1::new();
// In this example we are generating a 12 words mnemonic phrase
// but it is also possible generate 15, 18, 21 and 24 words
// using their respective `WordCount` variant.
let mnemonic: GeneratedKey<_, Tap> =
Mnemonic::generate((WordCount::Words12, Language::English))
.map_err(|_| anyhow!("Mnemonic generation error"))?;
println!("Mnemonic phrase: {}", *mnemonic);
let mnemonic_with_passphrase = (mnemonic, None);
// define external and internal derivation key path
let external_path = DerivationPath::from_str("m/86h/1h/0h/0").unwrap();
let internal_path = DerivationPath::from_str("m/86h/1h/0h/1").unwrap();
// generate external and internal descriptor from mnemonic
let (external_descriptor, ext_keymap) =
descriptor!(tr((mnemonic_with_passphrase.clone(), external_path)))?
.into_wallet_descriptor(&secp, Network::Testnet)?;
let (internal_descriptor, int_keymap) =
descriptor!(tr((mnemonic_with_passphrase, internal_path)))?
.into_wallet_descriptor(&secp, Network::Testnet)?;
println!("tpub external descriptor: {}", external_descriptor);
println!("tpub internal descriptor: {}", internal_descriptor);
println!(
"tprv external descriptor: {}",
external_descriptor.to_string_with_secret(&ext_keymap)
);
println!(
"tprv internal descriptor: {}",
internal_descriptor.to_string_with_secret(&int_keymap)
);
Ok(())
}

View File

@ -0,0 +1,60 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
extern crate bdk_wallet;
use std::error::Error;
use bdk_wallet::bitcoin::Network;
use bdk_wallet::descriptor::{policy::BuildSatisfaction, ExtractPolicy, IntoWalletDescriptor};
use bdk_wallet::signer::SignersContainer;
/// This example describes the use of the BDK's [`bdk_wallet::descriptor::policy`] module.
///
/// Policy is higher abstraction representation of the wallet descriptor spending condition.
/// This is useful to express complex miniscript spending conditions into more human readable form.
/// The resulting `Policy` structure can be used to derive spending conditions the wallet is capable
/// to spend from.
///
/// This example demos a Policy output for a 2of2 multisig between between 2 parties, where the wallet holds
/// one of the Extend Private key.
fn main() -> Result<(), Box<dyn Error>> {
let secp = bitcoin::secp256k1::Secp256k1::new();
// The descriptor used in the example
// The form is "wsh(multi(2, <privkey>, <pubkey>))"
let desc = "wsh(multi(2,tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/*,tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/1/*))";
// Use the descriptor string to derive the full descriptor and a keymap.
// The wallet descriptor can be used to create a new bdk_wallet::wallet.
// While the `keymap` can be used to create a `SignerContainer`.
//
// The `SignerContainer` can sign for `PSBT`s.
// a `bdk_wallet::Wallet` internally uses these to handle transaction signing.
// But they can be used as independent tools also.
let (wallet_desc, keymap) = desc.into_wallet_descriptor(&secp, Network::Testnet)?;
println!("Example Descriptor for policy analysis : {}", wallet_desc);
// Create the signer with the keymap and descriptor.
let signers_container = SignersContainer::build(keymap, &wallet_desc, &secp);
// Extract the Policy from the given descriptor and signer.
// Note that Policy is a wallet specific structure. It depends on the the descriptor, and
// what the concerned wallet with a given signer can sign for.
let policy = wallet_desc
.extract_policy(&signers_container, BuildSatisfaction::None, &secp)?
.expect("We expect a policy");
println!("Derived Policy for the descriptor {:#?}", policy);
Ok(())
}

View File

@ -0,0 +1,147 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Descriptor checksum
//!
//! This module contains a re-implementation of the function used by Bitcoin Core to calculate the
//! checksum of a descriptor
use crate::descriptor::DescriptorError;
use alloc::string::String;
const INPUT_CHARSET: &[u8] = b"0123456789()[],'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
const CHECKSUM_CHARSET: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
fn poly_mod(mut c: u64, val: u64) -> u64 {
let c0 = c >> 35;
c = ((c & 0x7ffffffff) << 5) ^ val;
if c0 & 1 > 0 {
c ^= 0xf5dee51989
};
if c0 & 2 > 0 {
c ^= 0xa9fdca3312
};
if c0 & 4 > 0 {
c ^= 0x1bab10e32d
};
if c0 & 8 > 0 {
c ^= 0x3706b1677a
};
if c0 & 16 > 0 {
c ^= 0x644d626ffd
};
c
}
/// Compute the checksum bytes of a descriptor, excludes any existing checksum in the descriptor string from the calculation
pub fn calc_checksum_bytes(mut desc: &str) -> Result<[u8; 8], DescriptorError> {
let mut c = 1;
let mut cls = 0;
let mut clscount = 0;
let mut original_checksum = None;
if let Some(split) = desc.split_once('#') {
desc = split.0;
original_checksum = Some(split.1);
}
for ch in desc.as_bytes() {
let pos = INPUT_CHARSET
.iter()
.position(|b| b == ch)
.ok_or(DescriptorError::InvalidDescriptorCharacter(*ch))? as u64;
c = poly_mod(c, pos & 31);
cls = cls * 3 + (pos >> 5);
clscount += 1;
if clscount == 3 {
c = poly_mod(c, cls);
cls = 0;
clscount = 0;
}
}
if clscount > 0 {
c = poly_mod(c, cls);
}
(0..8).for_each(|_| c = poly_mod(c, 0));
c ^= 1;
let mut checksum = [0_u8; 8];
for j in 0..8 {
checksum[j] = CHECKSUM_CHARSET[((c >> (5 * (7 - j))) & 31) as usize];
}
// if input data already had a checksum, check calculated checksum against original checksum
if let Some(original_checksum) = original_checksum {
if original_checksum.as_bytes() != checksum {
return Err(DescriptorError::InvalidDescriptorChecksum);
}
}
Ok(checksum)
}
/// Compute the checksum of a descriptor, excludes any existing checksum in the descriptor string from the calculation
pub fn calc_checksum(desc: &str) -> Result<String, DescriptorError> {
// unsafe is okay here as the checksum only uses bytes in `CHECKSUM_CHARSET`
calc_checksum_bytes(desc).map(|b| unsafe { String::from_utf8_unchecked(b.to_vec()) })
}
#[cfg(test)]
mod test {
use super::*;
use crate::descriptor::calc_checksum;
use assert_matches::assert_matches;
// test calc_checksum() function; it should return the same value as Bitcoin Core
#[test]
fn test_calc_checksum() {
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)";
assert_eq!(calc_checksum(desc).unwrap(), "tqz0nc62");
let desc = "pkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/44'/1'/0'/0/*)";
assert_eq!(calc_checksum(desc).unwrap(), "lasegmfs");
}
// test calc_checksum() function; it should return the same value as Bitcoin Core even if the
// descriptor string includes a checksum hash
#[test]
fn test_calc_checksum_with_checksum_hash() {
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)#tqz0nc62";
assert_eq!(calc_checksum(desc).unwrap(), "tqz0nc62");
let desc = "pkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/44'/1'/0'/0/*)#lasegmfs";
assert_eq!(calc_checksum(desc).unwrap(), "lasegmfs");
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)#tqz0nc26";
assert_matches!(
calc_checksum(desc),
Err(DescriptorError::InvalidDescriptorChecksum)
);
let desc = "pkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/44'/1'/0'/0/*)#lasegmsf";
assert_matches!(
calc_checksum(desc),
Err(DescriptorError::InvalidDescriptorChecksum)
);
}
#[test]
fn test_calc_checksum_invalid_character() {
let sparkle_heart = unsafe { core::str::from_utf8_unchecked(&[240, 159, 146, 150]) };
let invalid_desc = format!("wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcL{}fjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)", sparkle_heart);
assert_matches!(
calc_checksum(&invalid_desc),
Err(DescriptorError::InvalidDescriptorCharacter(invalid_char)) if invalid_char == sparkle_heart.as_bytes()[0]
);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,127 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Descriptor errors
use core::fmt;
/// Errors related to the parsing and usage of descriptors
#[derive(Debug, PartialEq)]
pub enum Error {
/// Invalid HD Key path, such as having a wildcard but a length != 1
InvalidHdKeyPath,
/// The provided descriptor doesn't match its checksum
InvalidDescriptorChecksum,
/// The descriptor contains hardened derivation steps on public extended keys
HardenedDerivationXpub,
/// The descriptor contains multipath keys
MultiPath,
/// Error thrown while working with [`keys`](crate::keys)
Key(crate::keys::KeyError),
/// Error while extracting and manipulating policies
Policy(crate::descriptor::policy::PolicyError),
/// Invalid byte found in the descriptor checksum
InvalidDescriptorCharacter(u8),
/// BIP32 error
Bip32(bitcoin::bip32::Error),
/// Error during base58 decoding
Base58(bitcoin::base58::Error),
/// Key-related error
Pk(bitcoin::key::ParsePublicKeyError),
/// Miniscript error
Miniscript(miniscript::Error),
/// Hex decoding error
Hex(bitcoin::hex::HexToBytesError),
/// The provided wallet descriptors are identical
ExternalAndInternalAreTheSame,
}
impl From<crate::keys::KeyError> for Error {
fn from(key_error: crate::keys::KeyError) -> Error {
match key_error {
crate::keys::KeyError::Miniscript(inner) => Error::Miniscript(inner),
crate::keys::KeyError::Bip32(inner) => Error::Bip32(inner),
e => Error::Key(e),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidHdKeyPath => write!(f, "Invalid HD key path"),
Self::InvalidDescriptorChecksum => {
write!(f, "The provided descriptor doesn't match its checksum")
}
Self::HardenedDerivationXpub => write!(
f,
"The descriptor contains hardened derivation steps on public extended keys"
),
Self::MultiPath => write!(
f,
"The descriptor contains multipath keys, which are not supported yet"
),
Self::Key(err) => write!(f, "Key error: {}", err),
Self::Policy(err) => write!(f, "Policy error: {}", err),
Self::InvalidDescriptorCharacter(char) => {
write!(f, "Invalid descriptor character: {}", char)
}
Self::Bip32(err) => write!(f, "BIP32 error: {}", err),
Self::Base58(err) => write!(f, "Base58 error: {}", err),
Self::Pk(err) => write!(f, "Key-related error: {}", err),
Self::Miniscript(err) => write!(f, "Miniscript error: {}", err),
Self::Hex(err) => write!(f, "Hex decoding error: {}", err),
Self::ExternalAndInternalAreTheSame => {
write!(f, "External and internal descriptors are the same")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
impl From<bitcoin::bip32::Error> for Error {
fn from(err: bitcoin::bip32::Error) -> Self {
Error::Bip32(err)
}
}
impl From<bitcoin::base58::Error> for Error {
fn from(err: bitcoin::base58::Error) -> Self {
Error::Base58(err)
}
}
impl From<bitcoin::key::ParsePublicKeyError> for Error {
fn from(err: bitcoin::key::ParsePublicKeyError) -> Self {
Error::Pk(err)
}
}
impl From<miniscript::Error> for Error {
fn from(err: miniscript::Error) -> Self {
Error::Miniscript(err)
}
}
impl From<bitcoin::hex::HexToBytesError> for Error {
fn from(err: bitcoin::hex::HexToBytesError) -> Self {
Error::Hex(err)
}
}
impl From<crate::descriptor::policy::PolicyError> for Error {
fn from(err: crate::descriptor::policy::PolicyError) -> Self {
Error::Policy(err)
}
}

View File

@ -0,0 +1,916 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Descriptors
//!
//! This module contains generic utilities to work with descriptors, plus some re-exported types
//! from [`miniscript`].
use crate::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use bitcoin::bip32::{ChildNumber, DerivationPath, Fingerprint, KeySource, Xpub};
use bitcoin::{key::XOnlyPublicKey, secp256k1, PublicKey};
use bitcoin::{psbt, taproot};
use bitcoin::{Network, TxOut};
use miniscript::descriptor::{
DefiniteDescriptorKey, DescriptorMultiXKey, DescriptorSecretKey, DescriptorType,
DescriptorXKey, InnerXKey, KeyMap, SinglePubKey, Wildcard,
};
pub use miniscript::{
Descriptor, DescriptorPublicKey, Legacy, Miniscript, ScriptContext, Segwitv0,
};
use miniscript::{ForEachKey, MiniscriptKey, TranslatePk};
use crate::descriptor::policy::BuildSatisfaction;
pub mod checksum;
#[doc(hidden)]
pub mod dsl;
pub mod error;
pub mod policy;
pub mod template;
pub use self::checksum::calc_checksum;
use self::checksum::calc_checksum_bytes;
pub use self::error::Error as DescriptorError;
pub use self::policy::Policy;
use self::template::DescriptorTemplateOut;
use crate::keys::{IntoDescriptorKey, KeyError};
use crate::wallet::signer::SignersContainer;
use crate::wallet::utils::SecpCtx;
/// Alias for a [`Descriptor`] that can contain extended keys using [`DescriptorPublicKey`]
pub type ExtendedDescriptor = Descriptor<DescriptorPublicKey>;
/// Alias for a [`Descriptor`] that contains extended **derived** keys
pub type DerivedDescriptor = Descriptor<DefiniteDescriptorKey>;
/// Alias for the type of maps that represent derivation paths in a [`psbt::Input`] or
/// [`psbt::Output`]
///
/// [`psbt::Input`]: bitcoin::psbt::Input
/// [`psbt::Output`]: bitcoin::psbt::Output
pub type HdKeyPaths = BTreeMap<secp256k1::PublicKey, KeySource>;
/// Alias for the type of maps that represent taproot key origins in a [`psbt::Input`] or
/// [`psbt::Output`]
///
/// [`psbt::Input`]: bitcoin::psbt::Input
/// [`psbt::Output`]: bitcoin::psbt::Output
pub type TapKeyOrigins = BTreeMap<XOnlyPublicKey, (Vec<taproot::TapLeafHash>, KeySource)>;
/// Trait for types which can be converted into an [`ExtendedDescriptor`] and a [`KeyMap`] usable by a wallet in a specific [`Network`]
pub trait IntoWalletDescriptor {
/// Convert to wallet descriptor
fn into_wallet_descriptor(
self,
secp: &SecpCtx,
network: Network,
) -> Result<(ExtendedDescriptor, KeyMap), DescriptorError>;
}
impl IntoWalletDescriptor for &str {
fn into_wallet_descriptor(
self,
secp: &SecpCtx,
network: Network,
) -> Result<(ExtendedDescriptor, KeyMap), DescriptorError> {
let descriptor = match self.split_once('#') {
Some((desc, original_checksum)) => {
let checksum = calc_checksum_bytes(desc)?;
if original_checksum.as_bytes() != checksum {
return Err(DescriptorError::InvalidDescriptorChecksum);
}
desc
}
None => self,
};
ExtendedDescriptor::parse_descriptor(secp, descriptor)?
.into_wallet_descriptor(secp, network)
}
}
impl IntoWalletDescriptor for &String {
fn into_wallet_descriptor(
self,
secp: &SecpCtx,
network: Network,
) -> Result<(ExtendedDescriptor, KeyMap), DescriptorError> {
self.as_str().into_wallet_descriptor(secp, network)
}
}
impl IntoWalletDescriptor for String {
fn into_wallet_descriptor(
self,
secp: &SecpCtx,
network: Network,
) -> Result<(ExtendedDescriptor, KeyMap), DescriptorError> {
self.as_str().into_wallet_descriptor(secp, network)
}
}
impl IntoWalletDescriptor for ExtendedDescriptor {
fn into_wallet_descriptor(
self,
secp: &SecpCtx,
network: Network,
) -> Result<(ExtendedDescriptor, KeyMap), DescriptorError> {
(self, KeyMap::default()).into_wallet_descriptor(secp, network)
}
}
impl IntoWalletDescriptor for (ExtendedDescriptor, KeyMap) {
fn into_wallet_descriptor(
self,
secp: &SecpCtx,
network: Network,
) -> Result<(ExtendedDescriptor, KeyMap), DescriptorError> {
use crate::keys::DescriptorKey;
struct Translator<'s, 'd> {
secp: &'s SecpCtx,
descriptor: &'d ExtendedDescriptor,
network: Network,
}
impl<'s, 'd> miniscript::Translator<DescriptorPublicKey, String, DescriptorError>
for Translator<'s, 'd>
{
fn pk(&mut self, pk: &DescriptorPublicKey) -> Result<String, DescriptorError> {
let secp = &self.secp;
let (_, _, networks) = if self.descriptor.is_taproot() {
let descriptor_key: DescriptorKey<miniscript::Tap> =
pk.clone().into_descriptor_key()?;
descriptor_key.extract(secp)?
} else if self.descriptor.is_witness() {
let descriptor_key: DescriptorKey<miniscript::Segwitv0> =
pk.clone().into_descriptor_key()?;
descriptor_key.extract(secp)?
} else {
let descriptor_key: DescriptorKey<miniscript::Legacy> =
pk.clone().into_descriptor_key()?;
descriptor_key.extract(secp)?
};
if networks.contains(&self.network) {
Ok(Default::default())
} else {
Err(DescriptorError::Key(KeyError::InvalidNetwork))
}
}
fn sha256(
&mut self,
_sha256: &<DescriptorPublicKey as MiniscriptKey>::Sha256,
) -> Result<String, DescriptorError> {
Ok(Default::default())
}
fn hash256(
&mut self,
_hash256: &<DescriptorPublicKey as MiniscriptKey>::Hash256,
) -> Result<String, DescriptorError> {
Ok(Default::default())
}
fn ripemd160(
&mut self,
_ripemd160: &<DescriptorPublicKey as MiniscriptKey>::Ripemd160,
) -> Result<String, DescriptorError> {
Ok(Default::default())
}
fn hash160(
&mut self,
_hash160: &<DescriptorPublicKey as MiniscriptKey>::Hash160,
) -> Result<String, DescriptorError> {
Ok(Default::default())
}
}
// check the network for the keys
use miniscript::TranslateErr;
match self.0.translate_pk(&mut Translator {
secp,
network,
descriptor: &self.0,
}) {
Ok(_) => {}
Err(TranslateErr::TranslatorErr(e)) => return Err(e),
Err(TranslateErr::OuterError(e)) => return Err(e.into()),
}
Ok(self)
}
}
impl IntoWalletDescriptor for DescriptorTemplateOut {
fn into_wallet_descriptor(
self,
_secp: &SecpCtx,
network: Network,
) -> Result<(ExtendedDescriptor, KeyMap), DescriptorError> {
struct Translator {
network: Network,
}
impl miniscript::Translator<DescriptorPublicKey, DescriptorPublicKey, DescriptorError>
for Translator
{
fn pk(
&mut self,
pk: &DescriptorPublicKey,
) -> Result<DescriptorPublicKey, DescriptorError> {
// workaround for xpubs generated by other key types, like bip39: since when the
// conversion is made one network has to be chosen, what we generally choose
// "mainnet", but then override the set of valid networks to specify that all of
// them are valid. here we reset the network to make sure the wallet struct gets a
// descriptor with the right network everywhere.
let pk = match pk {
DescriptorPublicKey::XPub(ref xpub) => {
let mut xpub = xpub.clone();
xpub.xkey.network = self.network.into();
DescriptorPublicKey::XPub(xpub)
}
other => other.clone(),
};
Ok(pk)
}
miniscript::translate_hash_clone!(
DescriptorPublicKey,
DescriptorPublicKey,
DescriptorError
);
}
let (desc, keymap, networks) = self;
if !networks.contains(&network) {
return Err(DescriptorError::Key(KeyError::InvalidNetwork));
}
// fixup the network for keys that need it in the descriptor
use miniscript::TranslateErr;
let translated = match desc.translate_pk(&mut Translator { network }) {
Ok(descriptor) => descriptor,
Err(TranslateErr::TranslatorErr(e)) => return Err(e),
Err(TranslateErr::OuterError(e)) => return Err(e.into()),
};
// ...and in the key map
let fixed_keymap = keymap
.into_iter()
.map(|(mut k, mut v)| {
match (&mut k, &mut v) {
(DescriptorPublicKey::XPub(xpub), DescriptorSecretKey::XPrv(xprv)) => {
xpub.xkey.network = network.into();
xprv.xkey.network = network.into();
}
(_, DescriptorSecretKey::Single(key)) => {
key.key.network = network.into();
}
_ => {}
}
(k, v)
})
.collect();
Ok((translated, fixed_keymap))
}
}
/// Extra checks for [`ExtendedDescriptor`].
pub(crate) fn check_wallet_descriptor(
descriptor: &Descriptor<DescriptorPublicKey>,
) -> Result<(), DescriptorError> {
// Ensure the keys don't contain any hardened derivation steps or hardened wildcards
let descriptor_contains_hardened_steps = descriptor.for_any_key(|k| {
if let DescriptorPublicKey::XPub(DescriptorXKey {
derivation_path,
wildcard,
..
}) = k
{
return *wildcard == Wildcard::Hardened
|| derivation_path.into_iter().any(ChildNumber::is_hardened);
}
false
});
if descriptor_contains_hardened_steps {
return Err(DescriptorError::HardenedDerivationXpub);
}
if descriptor.is_multipath() {
return Err(DescriptorError::MultiPath);
}
// Run miniscript's sanity check, which will look for duplicated keys and other potential
// issues
descriptor.sanity_check()?;
Ok(())
}
#[doc(hidden)]
/// Used internally mainly by the `descriptor!()` and `fragment!()` macros
pub trait CheckMiniscript<Ctx: miniscript::ScriptContext> {
fn check_miniscript(&self) -> Result<(), miniscript::Error>;
}
impl<Ctx: miniscript::ScriptContext, Pk: miniscript::MiniscriptKey> CheckMiniscript<Ctx>
for miniscript::Miniscript<Pk, Ctx>
{
fn check_miniscript(&self) -> Result<(), miniscript::Error> {
Ctx::check_global_validity(self)?;
Ok(())
}
}
/// Trait implemented on [`Descriptor`]s to add a method to extract the spending [`policy`]
pub trait ExtractPolicy {
/// Extract the spending [`policy`]
fn extract_policy(
&self,
signers: &SignersContainer,
psbt: BuildSatisfaction,
secp: &SecpCtx,
) -> Result<Option<Policy>, DescriptorError>;
}
pub(crate) trait XKeyUtils {
fn root_fingerprint(&self, secp: &SecpCtx) -> Fingerprint;
}
impl<T> XKeyUtils for DescriptorMultiXKey<T>
where
T: InnerXKey,
{
fn root_fingerprint(&self, secp: &SecpCtx) -> Fingerprint {
match self.origin {
Some((fingerprint, _)) => fingerprint,
None => self.xkey.xkey_fingerprint(secp),
}
}
}
impl<T> XKeyUtils for DescriptorXKey<T>
where
T: InnerXKey,
{
fn root_fingerprint(&self, secp: &SecpCtx) -> Fingerprint {
match self.origin {
Some((fingerprint, _)) => fingerprint,
None => self.xkey.xkey_fingerprint(secp),
}
}
}
pub(crate) trait DescriptorMeta {
fn is_witness(&self) -> bool;
fn is_taproot(&self) -> bool;
fn get_extended_keys(&self) -> Vec<DescriptorXKey<Xpub>>;
fn derive_from_hd_keypaths(
&self,
hd_keypaths: &HdKeyPaths,
secp: &SecpCtx,
) -> Option<DerivedDescriptor>;
fn derive_from_tap_key_origins(
&self,
tap_key_origins: &TapKeyOrigins,
secp: &SecpCtx,
) -> Option<DerivedDescriptor>;
fn derive_from_psbt_key_origins(
&self,
key_origins: BTreeMap<Fingerprint, (&DerivationPath, SinglePubKey)>,
secp: &SecpCtx,
) -> Option<DerivedDescriptor>;
fn derive_from_psbt_input(
&self,
psbt_input: &psbt::Input,
utxo: Option<TxOut>,
secp: &SecpCtx,
) -> Option<DerivedDescriptor>;
}
impl DescriptorMeta for ExtendedDescriptor {
fn is_witness(&self) -> bool {
matches!(
self.desc_type(),
DescriptorType::Wpkh
| DescriptorType::ShWpkh
| DescriptorType::Wsh
| DescriptorType::ShWsh
| DescriptorType::ShWshSortedMulti
| DescriptorType::WshSortedMulti
)
}
fn is_taproot(&self) -> bool {
self.desc_type() == DescriptorType::Tr
}
fn get_extended_keys(&self) -> Vec<DescriptorXKey<Xpub>> {
let mut answer = Vec::new();
self.for_each_key(|pk| {
if let DescriptorPublicKey::XPub(xpub) = pk {
answer.push(xpub.clone());
}
true
});
answer
}
fn derive_from_psbt_key_origins(
&self,
key_origins: BTreeMap<Fingerprint, (&DerivationPath, SinglePubKey)>,
secp: &SecpCtx,
) -> Option<DerivedDescriptor> {
// Ensure that deriving `xpub` with `path` yields `expected`
let verify_key =
|xpub: &DescriptorXKey<Xpub>, path: &DerivationPath, expected: &SinglePubKey| {
let derived = xpub
.xkey
.derive_pub(secp, path)
.expect("The path should never contain hardened derivation steps")
.public_key;
match expected {
SinglePubKey::FullKey(pk) if &PublicKey::new(derived) == pk => true,
SinglePubKey::XOnly(pk) if &XOnlyPublicKey::from(derived) == pk => true,
_ => false,
}
};
let mut path_found = None;
// using `for_any_key` should make this stop as soon as we return `true`
self.for_any_key(|key| {
if let DescriptorPublicKey::XPub(xpub) = key {
// Check if the key matches one entry in our `key_origins`. If it does, `matches()` will
// return the "prefix" that matched, so we remove that prefix from the full path
// found in `key_origins` and save it in `derive_path`. We expect this to be a derivation
// path of length 1 if the key is `wildcard` and an empty path otherwise.
let root_fingerprint = xpub.root_fingerprint(secp);
let derive_path = key_origins
.get_key_value(&root_fingerprint)
.and_then(|(fingerprint, (path, expected))| {
xpub.matches(&(*fingerprint, (*path).clone()), secp)
.zip(Some((path, expected)))
})
.and_then(|(prefix, (full_path, expected))| {
let derive_path = full_path
.into_iter()
.skip(prefix.into_iter().count())
.cloned()
.collect::<DerivationPath>();
// `derive_path` only contains the replacement index for the wildcard, if present, or
// an empty path for fixed descriptors. To verify the key we also need the normal steps
// that come before the wildcard, so we take them directly from `xpub` and then append
// the final index
if verify_key(
xpub,
&xpub.derivation_path.extend(derive_path.clone()),
expected,
) {
Some(derive_path)
} else {
None
}
});
match derive_path {
Some(path) if xpub.wildcard != Wildcard::None && path.len() == 1 => {
// Ignore hardened wildcards
if let ChildNumber::Normal { index } = path[0] {
path_found = Some(index);
return true;
}
}
Some(path) if xpub.wildcard == Wildcard::None && path.is_empty() => {
path_found = Some(0);
return true;
}
_ => {}
}
}
false
});
path_found.map(|path| {
self.at_derivation_index(path)
.expect("We ignore hardened wildcards")
})
}
fn derive_from_hd_keypaths(
&self,
hd_keypaths: &HdKeyPaths,
secp: &SecpCtx,
) -> Option<DerivedDescriptor> {
// "Convert" an hd_keypaths map to the format required by `derive_from_psbt_key_origins`
let key_origins = hd_keypaths
.iter()
.map(|(pk, (fingerprint, path))| {
(
*fingerprint,
(path, SinglePubKey::FullKey(PublicKey::new(*pk))),
)
})
.collect();
self.derive_from_psbt_key_origins(key_origins, secp)
}
fn derive_from_tap_key_origins(
&self,
tap_key_origins: &TapKeyOrigins,
secp: &SecpCtx,
) -> Option<DerivedDescriptor> {
// "Convert" a tap_key_origins map to the format required by `derive_from_psbt_key_origins`
let key_origins = tap_key_origins
.iter()
.map(|(pk, (_, (fingerprint, path)))| (*fingerprint, (path, SinglePubKey::XOnly(*pk))))
.collect();
self.derive_from_psbt_key_origins(key_origins, secp)
}
fn derive_from_psbt_input(
&self,
psbt_input: &psbt::Input,
utxo: Option<TxOut>,
secp: &SecpCtx,
) -> Option<DerivedDescriptor> {
if let Some(derived) = self.derive_from_hd_keypaths(&psbt_input.bip32_derivation, secp) {
return Some(derived);
}
if let Some(derived) = self.derive_from_tap_key_origins(&psbt_input.tap_key_origins, secp) {
return Some(derived);
}
if self.has_wildcard() {
// We can't try to bruteforce the derivation index, exit here
return None;
}
let descriptor = self.at_derivation_index(0).expect("0 is not hardened");
match descriptor.desc_type() {
// TODO: add pk() here
DescriptorType::Pkh
| DescriptorType::Wpkh
| DescriptorType::ShWpkh
| DescriptorType::Tr
if utxo.is_some()
&& descriptor.script_pubkey() == utxo.as_ref().unwrap().script_pubkey =>
{
Some(descriptor)
}
DescriptorType::Bare | DescriptorType::Sh | DescriptorType::ShSortedMulti
if psbt_input.redeem_script.is_some()
&& &descriptor.explicit_script().unwrap()
== psbt_input.redeem_script.as_ref().unwrap() =>
{
Some(descriptor)
}
DescriptorType::Wsh
| DescriptorType::ShWsh
| DescriptorType::ShWshSortedMulti
| DescriptorType::WshSortedMulti
if psbt_input.witness_script.is_some()
&& &descriptor.explicit_script().unwrap()
== psbt_input.witness_script.as_ref().unwrap() =>
{
Some(descriptor)
}
_ => None,
}
}
}
#[cfg(test)]
mod test {
use alloc::string::ToString;
use core::str::FromStr;
use assert_matches::assert_matches;
use bitcoin::hex::FromHex;
use bitcoin::secp256k1::Secp256k1;
use bitcoin::{bip32, Psbt};
use bitcoin::{NetworkKind, ScriptBuf};
use super::*;
use crate::psbt::PsbtUtils;
#[test]
fn test_derive_from_psbt_input_wpkh_wif() {
let descriptor = Descriptor::<DescriptorPublicKey>::from_str(
"wpkh(02b4632d08485ff1df2db55b9dafd23347d1c47a457072a1e87be26896549a8737)",
)
.unwrap();
let psbt = Psbt::deserialize(
&Vec::<u8>::from_hex(
"70736274ff010052010000000162307be8e431fbaff807cdf9cdc3fde44d7402\
11bc8342c31ffd6ec11fe35bcc0100000000ffffffff01328601000000000016\
001493ce48570b55c42c2af816aeaba06cfee1224fae000000000001011fa086\
01000000000016001493ce48570b55c42c2af816aeaba06cfee1224fae010304\
010000000000",
)
.unwrap(),
)
.unwrap();
assert!(descriptor
.derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new())
.is_some());
}
#[test]
fn test_derive_from_psbt_input_pkh_tpub() {
let descriptor = Descriptor::<DescriptorPublicKey>::from_str(
"pkh([0f056943/44h/0h/0h]tpubDDpWvmUrPZrhSPmUzCMBHffvC3HyMAPnWDSAQNBTnj1iZeJa7BZQEttFiP4DS4GCcXQHezdXhn86Hj6LHX5EDstXPWrMaSneRWM8yUf6NFd/10/*)",
)
.unwrap();
let psbt = Psbt::deserialize(
&Vec::<u8>::from_hex(
"70736274ff010053010000000145843b86be54a3cd8c9e38444e1162676c00df\
e7964122a70df491ea12fd67090100000000ffffffff01c19598000000000017\
a91432bb94283282f72b2e034709e348c44d5a4db0ef8700000000000100f902\
0000000001010167e99c0eb67640f3a1b6805f2d8be8238c947f8aaf49eb0a9c\
bee6a42c984200000000171600142b29a22019cca05b9c2b2d283a4c4489e1cf\
9f8ffeffffff02a01dced06100000017a914e2abf033cadbd74f0f4c74946201\
decd20d5c43c8780969800000000001976a9148b0fce5fb1264e599a65387313\
3c95478b902eb288ac02473044022015d9211576163fa5b001e84dfa3d44efd9\
86b8f3a0d3d2174369288b2b750906022048dacc0e5d73ae42512fd2b97e2071\
a8d0bce443b390b1fe0b8128fe70ec919e01210232dad1c5a67dcb0116d407e2\
52584228ab7ec00e8b9779d0c3ffe8114fc1a7d2c80600000103040100000022\
0603433b83583f8c4879b329dd08bbc7da935e4cc02f637ff746e05f0466ffb2\
a6a2180f0569432c00008000000080000000800a000000000000000000",
)
.unwrap(),
)
.unwrap();
assert!(descriptor
.derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new())
.is_some());
}
#[test]
fn test_derive_from_psbt_input_wsh() {
let descriptor = Descriptor::<DescriptorPublicKey>::from_str(
"wsh(and_v(v:pk(03b6633fef2397a0a9de9d7b6f23aef8368a6e362b0581f0f0af70d5ecfd254b14),older(6)))",
)
.unwrap();
let psbt = Psbt::deserialize(
&Vec::<u8>::from_hex(
"70736274ff01005302000000011c8116eea34408ab6529223c9a176606742207\
67a1ff1d46a6e3c4a88243ea6e01000000000600000001109698000000000017\
a914ad105f61102e0d01d7af40d06d6a5c3ae2f7fde387000000000001012b80\
969800000000002200203ca72f106a72234754890ca7640c43f65d2174e44d33\
336030f9059345091044010304010000000105252103b6633fef2397a0a9de9d\
7b6f23aef8368a6e362b0581f0f0af70d5ecfd254b14ad56b20000",
)
.unwrap(),
)
.unwrap();
assert!(descriptor
.derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new())
.is_some());
}
#[test]
fn test_derive_from_psbt_input_sh() {
let descriptor = Descriptor::<DescriptorPublicKey>::from_str(
"sh(and_v(v:pk(021403881a5587297818fcaf17d239cefca22fce84a45b3b1d23e836c4af671dbb),after(630000)))",
)
.unwrap();
let psbt = Psbt::deserialize(
&Vec::<u8>::from_hex(
"70736274ff0100530100000001bc8c13df445dfadcc42afa6dc841f85d22b01d\
a6270ebf981740f4b7b1d800390000000000feffffff01ba9598000000000017\
a91457b148ba4d3e5fa8608a8657875124e3d1c9390887f09c0900000100e002\
0000000001016ba1bbe05cc93574a0d611ec7d93ad0ab6685b28d0cd80e8a82d\
debb326643c90100000000feffffff02809698000000000017a914d9a6e8c455\
8e16c8253afe53ce37ad61cf4c38c487403504cf6100000017a9144044fb6e0b\
757dfc1b34886b6a95aef4d3db137e870247304402202a9b72d939bcde8ba2a1\
e0980597e47af4f5c152a78499143c3d0a78ac2286a602207a45b1df9e93b8c9\
6f09f5c025fe3e413ca4b905fe65ee55d32a3276439a9b8f012102dc1fcc2636\
4da1aa718f03d8d9bd6f2ff410ed2cf1245a168aa3bcc995ac18e0a806000001\
03040100000001042821021403881a5587297818fcaf17d239cefca22fce84a4\
5b3b1d23e836c4af671dbbad03f09c09b10000",
)
.unwrap(),
)
.unwrap();
assert!(descriptor
.derive_from_psbt_input(&psbt.inputs[0], psbt.get_utxo_for(0), &Secp256k1::new())
.is_some());
}
#[test]
fn test_to_wallet_descriptor_fixup_networks() {
use crate::keys::{any_network, IntoDescriptorKey};
let secp = Secp256k1::new();
let xprv = bip32::Xpriv::from_str("xprv9s21ZrQH143K3c3gF1DUWpWNr2SG2XrG8oYPpqYh7hoWsJy9NjabErnzriJPpnGHyKz5NgdXmq1KVbqS1r4NXdCoKitWg5e86zqXHa8kxyB").unwrap();
let path = bip32::DerivationPath::from_str("m/0").unwrap();
// here `to_descriptor_key` will set the valid networks for the key to only mainnet, since
// we are using an "xpub"
let key = (xprv, path.clone()).into_descriptor_key().unwrap();
// override it with any. this happens in some key conversions, like bip39
let key = key.override_valid_networks(any_network());
// make a descriptor out of it
let desc = crate::descriptor!(wpkh(key)).unwrap();
// this should convert the key that supports "any_network" to the right network (testnet)
let (wallet_desc, keymap) = desc
.into_wallet_descriptor(&secp, Network::Testnet)
.unwrap();
let mut xprv_testnet = xprv;
xprv_testnet.network = NetworkKind::Test;
let xpub_testnet = bip32::Xpub::from_priv(&secp, &xprv_testnet);
let desc_pubkey = DescriptorPublicKey::XPub(DescriptorXKey {
xkey: xpub_testnet,
origin: None,
derivation_path: path,
wildcard: Wildcard::Unhardened,
});
assert_eq!(wallet_desc.to_string(), "wpkh(tpubD6NzVbkrYhZ4XtJzoDja5snUjBNQRP5B3f4Hyn1T1x6PVPxzzVjvw6nJx2D8RBCxog9GEVjZoyStfepTz7TtKoBVdkCtnc7VCJh9dD4RAU9/0/*)#a3svx0ha");
assert_eq!(
keymap
.get(&desc_pubkey)
.map(|key| key.to_public(&secp).unwrap()),
Some(desc_pubkey)
);
}
// test IntoWalletDescriptor trait from &str with and without checksum appended
#[test]
fn test_descriptor_from_str_with_checksum() {
let secp = Secp256k1::new();
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)#tqz0nc62"
.into_wallet_descriptor(&secp, Network::Testnet);
assert!(desc.is_ok());
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)"
.into_wallet_descriptor(&secp, Network::Testnet);
assert!(desc.is_ok());
let desc = "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/1/2/*)#67ju93jw"
.into_wallet_descriptor(&secp, Network::Testnet);
assert!(desc.is_ok());
let desc = "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/1/2/*)"
.into_wallet_descriptor(&secp, Network::Testnet);
assert!(desc.is_ok());
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)#67ju93jw"
.into_wallet_descriptor(&secp, Network::Testnet);
assert_matches!(desc, Err(DescriptorError::InvalidDescriptorChecksum));
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)#67ju93jw"
.into_wallet_descriptor(&secp, Network::Testnet);
assert_matches!(desc, Err(DescriptorError::InvalidDescriptorChecksum));
}
// test IntoWalletDescriptor trait from &str with keys from right and wrong network
#[test]
fn test_descriptor_from_str_with_keys_network() {
let secp = Secp256k1::new();
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)"
.into_wallet_descriptor(&secp, Network::Testnet);
assert!(desc.is_ok());
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)"
.into_wallet_descriptor(&secp, Network::Regtest);
assert!(desc.is_ok());
let desc = "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/1/2/*)"
.into_wallet_descriptor(&secp, Network::Testnet);
assert!(desc.is_ok());
let desc = "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/1/2/*)"
.into_wallet_descriptor(&secp, Network::Regtest);
assert!(desc.is_ok());
let desc = "sh(wpkh(02864bb4ad00cefa806098a69e192bbda937494e69eb452b87bb3f20f6283baedb))"
.into_wallet_descriptor(&secp, Network::Testnet);
assert!(desc.is_ok());
let desc = "sh(wpkh(02864bb4ad00cefa806098a69e192bbda937494e69eb452b87bb3f20f6283baedb))"
.into_wallet_descriptor(&secp, Network::Bitcoin);
assert!(desc.is_ok());
let desc = "wpkh(tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N/1/2/*)"
.into_wallet_descriptor(&secp, Network::Bitcoin);
assert_matches!(desc, Err(DescriptorError::Key(KeyError::InvalidNetwork)));
let desc = "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/1/2/*)"
.into_wallet_descriptor(&secp, Network::Bitcoin);
assert_matches!(desc, Err(DescriptorError::Key(KeyError::InvalidNetwork)));
}
// test IntoWalletDescriptor trait from the output of the descriptor!() macro
#[test]
fn test_descriptor_from_str_from_output_of_macro() {
let secp = Secp256k1::new();
let tpub = bip32::Xpub::from_str("tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK").unwrap();
let path = bip32::DerivationPath::from_str("m/1/2").unwrap();
let key = (tpub, path).into_descriptor_key().unwrap();
// make a descriptor out of it
let desc = crate::descriptor!(wpkh(key)).unwrap();
let (wallet_desc, _) = desc
.into_wallet_descriptor(&secp, Network::Testnet)
.unwrap();
let wallet_desc_str = wallet_desc.to_string();
assert_eq!(wallet_desc_str, "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/1/2/*)#67ju93jw");
let (wallet_desc2, _) = wallet_desc_str
.into_wallet_descriptor(&secp, Network::Testnet)
.unwrap();
assert_eq!(wallet_desc, wallet_desc2)
}
#[test]
fn test_check_wallet_descriptor() {
let secp = Secp256k1::new();
let descriptor = "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/0'/1/2/*)";
let (descriptor, _) = descriptor
.into_wallet_descriptor(&secp, Network::Testnet)
.expect("must parse");
let result = check_wallet_descriptor(&descriptor);
assert_matches!(result, Err(DescriptorError::HardenedDerivationXpub));
let descriptor = "wpkh(tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/<0;1>/*)";
let (descriptor, _) = descriptor
.into_wallet_descriptor(&secp, Network::Testnet)
.expect("must parse");
let result = check_wallet_descriptor(&descriptor);
assert_matches!(result, Err(DescriptorError::MultiPath));
// repeated pubkeys
let descriptor = "wsh(multi(2,tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/0/*,tpubD6NzVbkrYhZ4XHndKkuB8FifXm8r5FQHwrN6oZuWCz13qb93rtgKvD4PQsqC4HP4yhV3tA2fqr2RbY5mNXfM7RxXUoeABoDtsFUq2zJq6YK/0/*))";
let (descriptor, _) = descriptor
.into_wallet_descriptor(&secp, Network::Testnet)
.expect("must parse");
let result = check_wallet_descriptor(&descriptor);
assert!(result.is_err());
}
#[test]
fn test_sh_wsh_sortedmulti_redeemscript() {
use miniscript::psbt::PsbtInputExt;
let secp = Secp256k1::new();
let descriptor = "sh(wsh(sortedmulti(3,tpubDEsqS36T4DVsKJd9UH8pAKzrkGBYPLEt9jZMwpKtzh1G6mgYehfHt9WCgk7MJG5QGSFWf176KaBNoXbcuFcuadAFKxDpUdMDKGBha7bY3QM/0/*,tpubDF3cpwfs7fMvXXuoQbohXtLjNM6ehwYT287LWtmLsd4r77YLg6MZg4vTETx5MSJ2zkfigbYWu31VA2Z2Vc1cZugCYXgS7FQu6pE8V6TriEH/0/*,tpubDE1SKfcW76Tb2AASv5bQWMuScYNAdoqLHoexw13sNDXwmUhQDBbCD3QAedKGLhxMrWQdMDKENzYtnXPDRvexQPNuDrLj52wAjHhNEm8sJ4p/0/*,tpubDFLc6oXwJmhm3FGGzXkfJNTh2KitoY3WhmmQvuAjMhD8YbyWn5mAqckbxXfm2etM3p5J6JoTpSrMqRSTfMLtNW46poDaEZJ1kjd3csRSjwH/0/*,tpubDEWD9NBeWP59xXmdqSNt4VYdtTGwbpyP8WS962BuqpQeMZmX9Pur14dhXdZT5a7wR1pK6dPtZ9fP5WR493hPzemnBvkfLLYxnUjAKj1JCQV/0/*,tpubDEHyZkkwd7gZWCTgQuYQ9C4myF2hMEmyHsBCCmLssGqoqUxeT3gzohF5uEVURkf9TtmeepJgkSUmteac38FwZqirjApzNX59XSHLcwaTZCH/0/*,tpubDEqLouCekwnMUWN486kxGzD44qVgeyuqHyxUypNEiQt5RnUZNJe386TKPK99fqRV1vRkZjYAjtXGTECz98MCsdLcnkM67U6KdYRzVubeCgZ/0/*)))";
let (descriptor, _) = descriptor
.into_wallet_descriptor(&secp, Network::Testnet)
.unwrap();
check_wallet_descriptor(&descriptor).expect("descriptor");
let descriptor = descriptor.at_derivation_index(0).unwrap();
let script = ScriptBuf::from_hex("5321022f533b667e2ea3b36e21961c9fe9dca340fbe0af5210173a83ae0337ab20a57621026bb53a98e810bd0ee61a0ed1164ba6c024786d76554e793e202dc6ce9c78c4ea2102d5b8a7d66a41ffdb6f4c53d61994022e886b4f45001fb158b95c9164d45f8ca3210324b75eead2c1f9c60e8adeb5e7009fec7a29afcdb30d829d82d09562fe8bae8521032d34f8932200833487bd294aa219dcbe000b9f9b3d824799541430009f0fa55121037468f8ea99b6c64788398b5ad25480cad08f4b0d65be54ce3a55fd206b5ae4722103f72d3d96663b0ea99b0aeb0d7f273cab11a8de37885f1dddc8d9112adb87169357ae").unwrap();
let mut psbt_input = psbt::Input::default();
psbt_input
.update_with_descriptor_unchecked(&descriptor)
.unwrap();
assert_eq!(psbt_input.redeem_script, Some(script.to_p2wsh()));
assert_eq!(psbt_input.witness_script, Some(script));
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,227 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! BIP-0039
// TODO: maybe write our own implementation of bip39? Seems stupid to have an extra dependency for
// something that should be fairly simple to re-implement.
use alloc::string::String;
use bitcoin::bip32;
use bitcoin::Network;
use miniscript::ScriptContext;
pub use bip39::{Error, Language, Mnemonic};
type Seed = [u8; 64];
/// Type describing entropy length (aka word count) in the mnemonic
pub enum WordCount {
/// 12 words mnemonic (128 bits entropy)
Words12 = 128,
/// 15 words mnemonic (160 bits entropy)
Words15 = 160,
/// 18 words mnemonic (192 bits entropy)
Words18 = 192,
/// 21 words mnemonic (224 bits entropy)
Words21 = 224,
/// 24 words mnemonic (256 bits entropy)
Words24 = 256,
}
use super::{
any_network, DerivableKey, DescriptorKey, ExtendedKey, GeneratableKey, GeneratedKey, KeyError,
};
fn set_valid_on_any_network<Ctx: ScriptContext>(
descriptor_key: DescriptorKey<Ctx>,
) -> DescriptorKey<Ctx> {
// We have to pick one network to build the xprv, but since the bip39 standard doesn't
// encode the network, the xprv we create is actually valid everywhere. So we override the
// valid networks with `any_network()`.
descriptor_key.override_valid_networks(any_network())
}
/// Type for a BIP39 mnemonic with an optional passphrase
pub type MnemonicWithPassphrase = (Mnemonic, Option<String>);
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
impl<Ctx: ScriptContext> DerivableKey<Ctx> for Seed {
fn into_extended_key(self) -> Result<ExtendedKey<Ctx>, KeyError> {
Ok(bip32::Xpriv::new_master(Network::Bitcoin, &self[..])?.into())
}
fn into_descriptor_key(
self,
source: Option<bip32::KeySource>,
derivation_path: bip32::DerivationPath,
) -> Result<DescriptorKey<Ctx>, KeyError> {
let descriptor_key = self
.into_extended_key()?
.into_descriptor_key(source, derivation_path)?;
Ok(set_valid_on_any_network(descriptor_key))
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
impl<Ctx: ScriptContext> DerivableKey<Ctx> for MnemonicWithPassphrase {
fn into_extended_key(self) -> Result<ExtendedKey<Ctx>, KeyError> {
let (mnemonic, passphrase) = self;
let seed: Seed = mnemonic.to_seed(passphrase.as_deref().unwrap_or(""));
seed.into_extended_key()
}
fn into_descriptor_key(
self,
source: Option<bip32::KeySource>,
derivation_path: bip32::DerivationPath,
) -> Result<DescriptorKey<Ctx>, KeyError> {
let descriptor_key = self
.into_extended_key()?
.into_descriptor_key(source, derivation_path)?;
Ok(set_valid_on_any_network(descriptor_key))
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
impl<Ctx: ScriptContext> DerivableKey<Ctx> for (GeneratedKey<Mnemonic, Ctx>, Option<String>) {
fn into_extended_key(self) -> Result<ExtendedKey<Ctx>, KeyError> {
let (mnemonic, passphrase) = self;
(mnemonic.into_key(), passphrase).into_extended_key()
}
fn into_descriptor_key(
self,
source: Option<bip32::KeySource>,
derivation_path: bip32::DerivationPath,
) -> Result<DescriptorKey<Ctx>, KeyError> {
let (mnemonic, passphrase) = self;
(mnemonic.into_key(), passphrase).into_descriptor_key(source, derivation_path)
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
impl<Ctx: ScriptContext> DerivableKey<Ctx> for Mnemonic {
fn into_extended_key(self) -> Result<ExtendedKey<Ctx>, KeyError> {
(self, None).into_extended_key()
}
fn into_descriptor_key(
self,
source: Option<bip32::KeySource>,
derivation_path: bip32::DerivationPath,
) -> Result<DescriptorKey<Ctx>, KeyError> {
let descriptor_key = self
.into_extended_key()?
.into_descriptor_key(source, derivation_path)?;
Ok(set_valid_on_any_network(descriptor_key))
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "keys-bip39")))]
impl<Ctx: ScriptContext> GeneratableKey<Ctx> for Mnemonic {
type Entropy = [u8; 32];
type Options = (WordCount, Language);
type Error = Option<bip39::Error>;
fn generate_with_entropy(
(word_count, language): Self::Options,
entropy: Self::Entropy,
) -> Result<GeneratedKey<Self, Ctx>, Self::Error> {
let entropy = &entropy[..(word_count as usize / 8)];
let mnemonic = Mnemonic::from_entropy_in(language, entropy)?;
Ok(GeneratedKey::new(mnemonic, any_network()))
}
}
#[cfg(test)]
mod test {
use alloc::string::ToString;
use core::str::FromStr;
use bitcoin::bip32;
use bip39::{Language, Mnemonic};
use crate::keys::{any_network, GeneratableKey, GeneratedKey};
use super::WordCount;
#[test]
fn test_keys_bip39_mnemonic() {
let mnemonic =
"aim bunker wash balance finish force paper analyst cabin spoon stable organ";
let mnemonic = Mnemonic::parse_in(Language::English, mnemonic).unwrap();
let path = bip32::DerivationPath::from_str("m/44'/0'/0'/0").unwrap();
let key = (mnemonic, path);
let (desc, keys, networks) = crate::descriptor!(wpkh(key)).unwrap();
assert_eq!(desc.to_string(), "wpkh([be83839f/44'/0'/0']xpub6DCQ1YcqvZtSwGWMrwHELPehjWV3f2MGZ69yBADTxFEUAoLwb5Mp5GniQK6tTp3AgbngVz9zEFbBJUPVnkG7LFYt8QMTfbrNqs6FNEwAPKA/0/*)#0r8v4nkv");
assert_eq!(keys.len(), 1);
assert_eq!(networks.len(), 4);
}
#[test]
fn test_keys_bip39_mnemonic_passphrase() {
let mnemonic =
"aim bunker wash balance finish force paper analyst cabin spoon stable organ";
let mnemonic = Mnemonic::parse_in(Language::English, mnemonic).unwrap();
let path = bip32::DerivationPath::from_str("m/44'/0'/0'/0").unwrap();
let key = ((mnemonic, Some("passphrase".into())), path);
let (desc, keys, networks) = crate::descriptor!(wpkh(key)).unwrap();
assert_eq!(desc.to_string(), "wpkh([8f6cb80c/44'/0'/0']xpub6DWYS8bbihFevy29M4cbw4ZR3P5E12jB8R88gBDWCTCNpYiDHhYWNywrCF9VZQYagzPmsZpxXpytzSoxynyeFr4ZyzheVjnpLKuse4fiwZw/0/*)#h0j0tg5m");
assert_eq!(keys.len(), 1);
assert_eq!(networks.len(), 4);
}
#[test]
fn test_keys_generate_bip39() {
let generated_mnemonic: GeneratedKey<_, miniscript::Segwitv0> =
Mnemonic::generate_with_entropy(
(WordCount::Words12, Language::English),
crate::keys::test::TEST_ENTROPY,
)
.unwrap();
assert_eq!(generated_mnemonic.valid_networks, any_network());
assert_eq!(
generated_mnemonic.to_string(),
"primary fetch primary fetch primary fetch primary fetch primary fetch primary fever"
);
let generated_mnemonic: GeneratedKey<_, miniscript::Segwitv0> =
Mnemonic::generate_with_entropy(
(WordCount::Words24, Language::English),
crate::keys::test::TEST_ENTROPY,
)
.unwrap();
assert_eq!(generated_mnemonic.valid_networks, any_network());
assert_eq!(generated_mnemonic.to_string(), "primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary fetch primary foster");
}
#[test]
fn test_keys_generate_bip39_random() {
let generated_mnemonic: GeneratedKey<_, miniscript::Segwitv0> =
Mnemonic::generate((WordCount::Words12, Language::English)).unwrap();
assert_eq!(generated_mnemonic.valid_networks, any_network());
let generated_mnemonic: GeneratedKey<_, miniscript::Segwitv0> =
Mnemonic::generate((WordCount::Words24, Language::English)).unwrap();
assert_eq!(generated_mnemonic.valid_networks, any_network());
}
}

File diff suppressed because it is too large Load Diff

50
crates/wallet/src/lib.rs Normal file
View File

@ -0,0 +1,50 @@
#![doc = include_str!("../README.md")]
// only enables the `doc_cfg` feature when the `docsrs` configuration attribute is defined
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(
docsrs,
doc(html_logo_url = "https://github.com/bitcoindevkit/bdk/raw/master/static/bdk.png")
)]
#![no_std]
#![warn(missing_docs)]
#[cfg(feature = "std")]
#[macro_use]
extern crate std;
#[doc(hidden)]
#[macro_use]
pub extern crate alloc;
pub extern crate bdk_chain as chain;
#[cfg(feature = "file_store")]
pub extern crate bdk_file_store as file_store;
#[cfg(feature = "keys-bip39")]
pub extern crate bip39;
pub extern crate bitcoin;
pub extern crate miniscript;
pub extern crate serde;
pub extern crate serde_json;
pub mod descriptor;
pub mod keys;
pub mod psbt;
mod types;
mod wallet;
pub(crate) use bdk_chain::collections;
#[cfg(feature = "rusqlite")]
pub use bdk_chain::rusqlite;
#[cfg(feature = "rusqlite")]
pub use bdk_chain::rusqlite_impl;
pub use descriptor::template;
pub use descriptor::HdKeyPaths;
pub use signer;
pub use signer::SignOptions;
pub use tx_builder::*;
pub use types::*;
pub use wallet::*;
/// Get the version of [`bdk_wallet`](crate) at runtime.
pub fn version() -> &'static str {
env!("CARGO_PKG_VERSION", "unknown")
}

View File

@ -0,0 +1,70 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Additional functions on the `rust-bitcoin` `Psbt` structure.
use alloc::vec::Vec;
use bitcoin::Amount;
use bitcoin::FeeRate;
use bitcoin::Psbt;
use bitcoin::TxOut;
// TODO upstream the functions here to `rust-bitcoin`?
/// Trait to add functions to extract utxos and calculate fees.
pub trait PsbtUtils {
/// Get the `TxOut` for the specified input index, if it doesn't exist in the PSBT `None` is returned.
fn get_utxo_for(&self, input_index: usize) -> Option<TxOut>;
/// The total transaction fee amount, sum of input amounts minus sum of output amounts, in sats.
/// If the PSBT is missing a TxOut for an input returns None.
fn fee_amount(&self) -> Option<Amount>;
/// The transaction's fee rate. This value will only be accurate if calculated AFTER the
/// `Psbt` is finalized and all witness/signature data is added to the
/// transaction.
/// If the PSBT is missing a TxOut for an input returns None.
fn fee_rate(&self) -> Option<FeeRate>;
}
impl PsbtUtils for Psbt {
fn get_utxo_for(&self, input_index: usize) -> Option<TxOut> {
let tx = &self.unsigned_tx;
let input = self.inputs.get(input_index)?;
match (&input.witness_utxo, &input.non_witness_utxo) {
(Some(_), _) => input.witness_utxo.clone(),
(_, Some(_)) => input.non_witness_utxo.as_ref().map(|in_tx| {
in_tx.output[tx.input[input_index].previous_output.vout as usize].clone()
}),
_ => None,
}
}
fn fee_amount(&self) -> Option<Amount> {
let tx = &self.unsigned_tx;
let utxos: Option<Vec<TxOut>> = (0..tx.input.len()).map(|i| self.get_utxo_for(i)).collect();
utxos.map(|inputs| {
let input_amount: Amount = inputs.iter().map(|i| i.value).sum();
let output_amount: Amount = self.unsigned_tx.output.iter().map(|o| o.value).sum();
input_amount
.checked_sub(output_amount)
.expect("input amount must be greater than output amount")
})
}
fn fee_rate(&self) -> Option<FeeRate> {
let fee_amount = self.fee_amount();
let weight = self.clone().extract_tx().ok()?.weight();
fee_amount.map(|fee| fee / weight)
}
}

135
crates/wallet/src/types.rs Normal file
View File

@ -0,0 +1,135 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
use alloc::boxed::Box;
use core::convert::AsRef;
use bdk_chain::ConfirmationTime;
use bitcoin::transaction::{OutPoint, Sequence, TxOut};
use bitcoin::{psbt, Weight};
use serde::{Deserialize, Serialize};
/// Types of keychains
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum KeychainKind {
/// External keychain, used for deriving recipient addresses.
External = 0,
/// Internal keychain, used for deriving change addresses.
Internal = 1,
}
impl KeychainKind {
/// Return [`KeychainKind`] as a byte
pub fn as_byte(&self) -> u8 {
match self {
KeychainKind::External => b'e',
KeychainKind::Internal => b'i',
}
}
}
impl AsRef<[u8]> for KeychainKind {
fn as_ref(&self) -> &[u8] {
match self {
KeychainKind::External => b"e",
KeychainKind::Internal => b"i",
}
}
}
/// An unspent output owned by a [`Wallet`].
///
/// [`Wallet`]: crate::Wallet
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
pub struct LocalOutput {
/// Reference to a transaction output
pub outpoint: OutPoint,
/// Transaction output
pub txout: TxOut,
/// Type of keychain
pub keychain: KeychainKind,
/// Whether this UTXO is spent or not
pub is_spent: bool,
/// The derivation index for the script pubkey in the wallet
pub derivation_index: u32,
/// The confirmation time for transaction containing this utxo
pub confirmation_time: ConfirmationTime,
}
/// A [`Utxo`] with its `satisfaction_weight`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WeightedUtxo {
/// The weight of the witness data and `scriptSig` expressed in [weight units]. This is used to
/// properly maintain the feerate when adding this input to a transaction during coin selection.
///
/// [weight units]: https://en.bitcoin.it/wiki/Weight_units
pub satisfaction_weight: Weight,
/// The UTXO
pub utxo: Utxo,
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// An unspent transaction output (UTXO).
pub enum Utxo {
/// A UTXO owned by the local wallet.
Local(LocalOutput),
/// A UTXO owned by another wallet.
Foreign {
/// The location of the output.
outpoint: OutPoint,
/// The nSequence value to set for this input.
sequence: Option<Sequence>,
/// The information about the input we require to add it to a PSBT.
// Box it to stop the type being too big.
psbt_input: Box<psbt::Input>,
},
}
impl Utxo {
/// Get the location of the UTXO
pub fn outpoint(&self) -> OutPoint {
match &self {
Utxo::Local(local) => local.outpoint,
Utxo::Foreign { outpoint, .. } => *outpoint,
}
}
/// Get the `TxOut` of the UTXO
pub fn txout(&self) -> &TxOut {
match &self {
Utxo::Local(local) => &local.txout,
Utxo::Foreign {
outpoint,
psbt_input,
..
} => {
if let Some(prev_tx) = &psbt_input.non_witness_utxo {
return &prev_tx.output[outpoint.vout as usize];
}
if let Some(txout) = &psbt_input.witness_utxo {
return txout;
}
unreachable!("Foreign UTXOs will always have one of these set")
}
}
}
/// Get the sequence number if an explicit sequence number has to be set for this input.
pub fn sequence(&self) -> Option<Sequence> {
match self {
Utxo::Local(_) => None,
Utxo::Foreign { sequence, .. } => *sequence,
}
}
}

View File

@ -0,0 +1,209 @@
use bdk_chain::{
indexed_tx_graph, keychain_txout, local_chain, tx_graph, ConfirmationBlockTime, Merge,
};
use miniscript::{Descriptor, DescriptorPublicKey};
type IndexedTxGraphChangeSet =
indexed_tx_graph::ChangeSet<ConfirmationBlockTime, keychain_txout::ChangeSet>;
/// A changeset for [`Wallet`](crate::Wallet).
#[derive(Default, Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
#[non_exhaustive]
pub struct ChangeSet {
/// Descriptor for recipient addresses.
pub descriptor: Option<Descriptor<DescriptorPublicKey>>,
/// Descriptor for change addresses.
pub change_descriptor: Option<Descriptor<DescriptorPublicKey>>,
/// Stores the network type of the transaction data.
pub network: Option<bitcoin::Network>,
/// Changes to the [`LocalChain`](local_chain::LocalChain).
pub local_chain: local_chain::ChangeSet,
/// Changes to [`TxGraph`](tx_graph::TxGraph).
pub tx_graph: tx_graph::ChangeSet<ConfirmationBlockTime>,
/// Changes to [`KeychainTxOutIndex`](keychain_txout::KeychainTxOutIndex).
pub indexer: keychain_txout::ChangeSet,
}
impl Merge for ChangeSet {
/// Merge another [`ChangeSet`] into itself.
fn merge(&mut self, other: Self) {
if other.descriptor.is_some() {
debug_assert!(
self.descriptor.is_none() || self.descriptor == other.descriptor,
"descriptor must never change"
);
self.descriptor = other.descriptor;
}
if other.change_descriptor.is_some() {
debug_assert!(
self.change_descriptor.is_none()
|| self.change_descriptor == other.change_descriptor,
"change descriptor must never change"
);
self.change_descriptor = other.change_descriptor;
}
if other.network.is_some() {
debug_assert!(
self.network.is_none() || self.network == other.network,
"network must never change"
);
self.network = other.network;
}
Merge::merge(&mut self.local_chain, other.local_chain);
Merge::merge(&mut self.tx_graph, other.tx_graph);
Merge::merge(&mut self.indexer, other.indexer);
}
fn is_empty(&self) -> bool {
self.descriptor.is_none()
&& self.change_descriptor.is_none()
&& self.network.is_none()
&& self.local_chain.is_empty()
&& self.tx_graph.is_empty()
&& self.indexer.is_empty()
}
}
#[cfg(feature = "rusqlite")]
impl ChangeSet {
/// Schema name for wallet.
pub const WALLET_SCHEMA_NAME: &'static str = "bdk_wallet";
/// Name of table to store wallet descriptors and network.
pub const WALLET_TABLE_NAME: &'static str = "bdk_wallet";
/// Initialize sqlite tables for wallet schema & table.
fn init_wallet_sqlite_tables(
db_tx: &chain::rusqlite::Transaction,
) -> chain::rusqlite::Result<()> {
let schema_v0: &[&str] = &[&format!(
"CREATE TABLE {} ( \
id INTEGER PRIMARY KEY NOT NULL CHECK (id = 0), \
descriptor TEXT, \
change_descriptor TEXT, \
network TEXT \
) STRICT;",
Self::WALLET_TABLE_NAME,
)];
crate::rusqlite_impl::migrate_schema(db_tx, Self::WALLET_SCHEMA_NAME, &[schema_v0])
}
/// Recover a [`ChangeSet`] from sqlite database.
pub fn from_sqlite(db_tx: &chain::rusqlite::Transaction) -> chain::rusqlite::Result<Self> {
Self::init_wallet_sqlite_tables(db_tx)?;
use chain::rusqlite::OptionalExtension;
use chain::Impl;
let mut changeset = Self::default();
let mut wallet_statement = db_tx.prepare(&format!(
"SELECT descriptor, change_descriptor, network FROM {}",
Self::WALLET_TABLE_NAME,
))?;
let row = wallet_statement
.query_row([], |row| {
Ok((
row.get::<_, Impl<Descriptor<DescriptorPublicKey>>>("descriptor")?,
row.get::<_, Impl<Descriptor<DescriptorPublicKey>>>("change_descriptor")?,
row.get::<_, Impl<bitcoin::Network>>("network")?,
))
})
.optional()?;
if let Some((Impl(desc), Impl(change_desc), Impl(network))) = row {
changeset.descriptor = Some(desc);
changeset.change_descriptor = Some(change_desc);
changeset.network = Some(network);
}
changeset.local_chain = local_chain::ChangeSet::from_sqlite(db_tx)?;
changeset.tx_graph = tx_graph::ChangeSet::<_>::from_sqlite(db_tx)?;
changeset.indexer = keychain_txout::ChangeSet::from_sqlite(db_tx)?;
Ok(changeset)
}
/// Persist [`ChangeSet`] to sqlite database.
pub fn persist_to_sqlite(
&self,
db_tx: &chain::rusqlite::Transaction,
) -> chain::rusqlite::Result<()> {
Self::init_wallet_sqlite_tables(db_tx)?;
use chain::rusqlite::named_params;
use chain::Impl;
let mut descriptor_statement = db_tx.prepare_cached(&format!(
"INSERT INTO {}(id, descriptor) VALUES(:id, :descriptor) ON CONFLICT(id) DO UPDATE SET descriptor=:descriptor",
Self::WALLET_TABLE_NAME,
))?;
if let Some(descriptor) = &self.descriptor {
descriptor_statement.execute(named_params! {
":id": 0,
":descriptor": Impl(descriptor.clone()),
})?;
}
let mut change_descriptor_statement = db_tx.prepare_cached(&format!(
"INSERT INTO {}(id, change_descriptor) VALUES(:id, :change_descriptor) ON CONFLICT(id) DO UPDATE SET change_descriptor=:change_descriptor",
Self::WALLET_TABLE_NAME,
))?;
if let Some(change_descriptor) = &self.change_descriptor {
change_descriptor_statement.execute(named_params! {
":id": 0,
":change_descriptor": Impl(change_descriptor.clone()),
})?;
}
let mut network_statement = db_tx.prepare_cached(&format!(
"INSERT INTO {}(id, network) VALUES(:id, :network) ON CONFLICT(id) DO UPDATE SET network=:network",
Self::WALLET_TABLE_NAME,
))?;
if let Some(network) = self.network {
network_statement.execute(named_params! {
":id": 0,
":network": Impl(network),
})?;
}
self.local_chain.persist_to_sqlite(db_tx)?;
self.tx_graph.persist_to_sqlite(db_tx)?;
self.indexer.persist_to_sqlite(db_tx)?;
Ok(())
}
}
impl From<local_chain::ChangeSet> for ChangeSet {
fn from(chain: local_chain::ChangeSet) -> Self {
Self {
local_chain: chain,
..Default::default()
}
}
}
impl From<IndexedTxGraphChangeSet> for ChangeSet {
fn from(indexed_tx_graph: IndexedTxGraphChangeSet) -> Self {
Self {
tx_graph: indexed_tx_graph.tx_graph,
indexer: indexed_tx_graph.indexer,
..Default::default()
}
}
}
impl From<tx_graph::ChangeSet<ConfirmationBlockTime>> for ChangeSet {
fn from(tx_graph: tx_graph::ChangeSet<ConfirmationBlockTime>) -> Self {
Self {
tx_graph,
..Default::default()
}
}
}
impl From<keychain_txout::ChangeSet> for ChangeSet {
fn from(indexer: keychain_txout::ChangeSet) -> Self {
Self {
indexer,
..Default::default()
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,260 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Errors that can be thrown by the [`Wallet`](crate::wallet::Wallet)
use crate::descriptor::policy::PolicyError;
use crate::descriptor::DescriptorError;
use crate::wallet::coin_selection;
use crate::{descriptor, KeychainKind};
use alloc::string::String;
use bitcoin::{absolute, psbt, Amount, OutPoint, Sequence, Txid};
use core::fmt;
/// Errors returned by miniscript when updating inconsistent PSBTs
#[derive(Debug, Clone)]
pub enum MiniscriptPsbtError {
/// Descriptor key conversion error
Conversion(miniscript::descriptor::ConversionError),
/// Return error type for PsbtExt::update_input_with_descriptor
UtxoUpdate(miniscript::psbt::UtxoUpdateError),
/// Return error type for PsbtExt::update_output_with_descriptor
OutputUpdate(miniscript::psbt::OutputUpdateError),
}
impl fmt::Display for MiniscriptPsbtError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Conversion(err) => write!(f, "Conversion error: {}", err),
Self::UtxoUpdate(err) => write!(f, "UTXO update error: {}", err),
Self::OutputUpdate(err) => write!(f, "Output update error: {}", err),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for MiniscriptPsbtError {}
#[derive(Debug)]
/// Error returned from [`TxBuilder::finish`]
///
/// [`TxBuilder::finish`]: crate::wallet::tx_builder::TxBuilder::finish
pub enum CreateTxError {
/// There was a problem with the descriptors passed in
Descriptor(DescriptorError),
/// There was a problem while extracting and manipulating policies
Policy(PolicyError),
/// Spending policy is not compatible with this [`KeychainKind`]
SpendingPolicyRequired(KeychainKind),
/// Requested invalid transaction version '0'
Version0,
/// Requested transaction version `1`, but at least `2` is needed to use OP_CSV
Version1Csv,
/// Requested `LockTime` is less than is required to spend from this script
LockTime {
/// Requested `LockTime`
requested: absolute::LockTime,
/// Required `LockTime`
required: absolute::LockTime,
},
/// Cannot enable RBF with a `Sequence` >= 0xFFFFFFFE
RbfSequence,
/// Cannot enable RBF with `Sequence` given a required OP_CSV
RbfSequenceCsv {
/// Given RBF `Sequence`
rbf: Sequence,
/// Required OP_CSV `Sequence`
csv: Sequence,
},
/// When bumping a tx the absolute fee requested is lower than replaced tx absolute fee
FeeTooLow {
/// Required fee absolute value [`Amount`]
required: Amount,
},
/// When bumping a tx the fee rate requested is lower than required
FeeRateTooLow {
/// Required fee rate
required: bitcoin::FeeRate,
},
/// `manually_selected_only` option is selected but no utxo has been passed
NoUtxosSelected,
/// Output created is under the dust limit, 546 satoshis
OutputBelowDustLimit(usize),
/// There was an error with coin selection
CoinSelection(coin_selection::Error),
/// Cannot build a tx without recipients
NoRecipients,
/// Partially signed bitcoin transaction error
Psbt(psbt::Error),
/// In order to use the [`TxBuilder::add_global_xpubs`] option every extended
/// key in the descriptor must either be a master key itself (having depth = 0) or have an
/// explicit origin provided
///
/// [`TxBuilder::add_global_xpubs`]: crate::wallet::tx_builder::TxBuilder::add_global_xpubs
MissingKeyOrigin(String),
/// Happens when trying to spend an UTXO that is not in the internal database
UnknownUtxo,
/// Missing non_witness_utxo on foreign utxo for given `OutPoint`
MissingNonWitnessUtxo(OutPoint),
/// Miniscript PSBT error
MiniscriptPsbt(MiniscriptPsbtError),
}
impl fmt::Display for CreateTxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Descriptor(e) => e.fmt(f),
Self::Policy(e) => e.fmt(f),
CreateTxError::SpendingPolicyRequired(keychain_kind) => {
write!(f, "Spending policy required: {:?}", keychain_kind)
}
CreateTxError::Version0 => {
write!(f, "Invalid version `0`")
}
CreateTxError::Version1Csv => {
write!(
f,
"TxBuilder requested version `1`, but at least `2` is needed to use OP_CSV"
)
}
CreateTxError::LockTime {
requested,
required,
} => {
write!(f, "TxBuilder requested timelock of `{:?}`, but at least `{:?}` is required to spend from this script", required, requested)
}
CreateTxError::RbfSequence => {
write!(f, "Cannot enable RBF with a nSequence >= 0xFFFFFFFE")
}
CreateTxError::RbfSequenceCsv { rbf, csv } => {
write!(
f,
"Cannot enable RBF with nSequence `{:?}` given a required OP_CSV of `{:?}`",
rbf, csv
)
}
CreateTxError::FeeTooLow { required } => {
write!(f, "Fee to low: required {}", required.display_dynamic())
}
CreateTxError::FeeRateTooLow { required } => {
write!(
f,
// Note: alternate fmt as sat/vb (ceil) available in bitcoin-0.31
//"Fee rate too low: required {required:#}"
"Fee rate too low: required {} sat/vb",
crate::floating_rate!(required)
)
}
CreateTxError::NoUtxosSelected => {
write!(f, "No UTXO selected")
}
CreateTxError::OutputBelowDustLimit(limit) => {
write!(f, "Output below the dust limit: {}", limit)
}
CreateTxError::CoinSelection(e) => e.fmt(f),
CreateTxError::NoRecipients => {
write!(f, "Cannot build tx without recipients")
}
CreateTxError::Psbt(e) => e.fmt(f),
CreateTxError::MissingKeyOrigin(err) => {
write!(f, "Missing key origin: {}", err)
}
CreateTxError::UnknownUtxo => {
write!(f, "UTXO not found in the internal database")
}
CreateTxError::MissingNonWitnessUtxo(outpoint) => {
write!(f, "Missing non_witness_utxo on foreign utxo {}", outpoint)
}
CreateTxError::MiniscriptPsbt(err) => {
write!(f, "Miniscript PSBT error: {}", err)
}
}
}
}
impl From<descriptor::error::Error> for CreateTxError {
fn from(err: descriptor::error::Error) -> Self {
CreateTxError::Descriptor(err)
}
}
impl From<PolicyError> for CreateTxError {
fn from(err: PolicyError) -> Self {
CreateTxError::Policy(err)
}
}
impl From<MiniscriptPsbtError> for CreateTxError {
fn from(err: MiniscriptPsbtError) -> Self {
CreateTxError::MiniscriptPsbt(err)
}
}
impl From<psbt::Error> for CreateTxError {
fn from(err: psbt::Error) -> Self {
CreateTxError::Psbt(err)
}
}
impl From<coin_selection::Error> for CreateTxError {
fn from(err: coin_selection::Error) -> Self {
CreateTxError::CoinSelection(err)
}
}
#[cfg(feature = "std")]
impl std::error::Error for CreateTxError {}
#[derive(Debug)]
/// Error returned from [`Wallet::build_fee_bump`]
///
/// [`Wallet::build_fee_bump`]: super::Wallet::build_fee_bump
pub enum BuildFeeBumpError {
/// Happens when trying to spend an UTXO that is not in the internal database
UnknownUtxo(OutPoint),
/// Thrown when a tx is not found in the internal database
TransactionNotFound(Txid),
/// Happens when trying to bump a transaction that is already confirmed
TransactionConfirmed(Txid),
/// Trying to replace a tx that has a sequence >= `0xFFFFFFFE`
IrreplaceableTransaction(Txid),
/// Node doesn't have data to estimate a fee rate
FeeRateUnavailable,
}
impl fmt::Display for BuildFeeBumpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownUtxo(outpoint) => write!(
f,
"UTXO not found in the internal database with txid: {}, vout: {}",
outpoint.txid, outpoint.vout
),
Self::TransactionNotFound(txid) => {
write!(
f,
"Transaction not found in the internal database with txid: {}",
txid
)
}
Self::TransactionConfirmed(txid) => {
write!(f, "Transaction already confirmed with txid: {}", txid)
}
Self::IrreplaceableTransaction(txid) => {
write!(f, "Transaction can't be replaced with txid: {}", txid)
}
Self::FeeRateUnavailable => write!(f, "Fee rate unavailable"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for BuildFeeBumpError {}

View File

@ -0,0 +1,366 @@
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Wallet export
//!
//! This modules implements the wallet export format used by [FullyNoded](https://github.com/Fonta1n3/FullyNoded/blob/10b7808c8b929b171cca537fb50522d015168ac9/Docs/Wallets/Wallet-Export-Spec.md).
//!
//! ## Examples
//!
//! ### Import from JSON
//!
//! ```
//! # use std::str::FromStr;
//! # use bitcoin::*;
//! # use bdk_wallet::export::*;
//! # use bdk_wallet::*;
//! let import = r#"{
//! "descriptor": "wpkh([c258d2e4\/84h\/1h\/0h]tpubDD3ynpHgJQW8VvWRzQ5WFDCrs4jqVFGHB3vLC3r49XHJSqP8bHKdK4AriuUKLccK68zfzowx7YhmDN8SiSkgCDENUFx9qVw65YyqM78vyVe\/0\/*)",
//! "blockheight":1782088,
//! "label":"testnet"
//! }"#;
//!
//! let import = FullyNodedExport::from_str(import)?;
//! let wallet = Wallet::create(
//! import.descriptor(),
//! import.change_descriptor().expect("change descriptor"),
//! )
//! .network(Network::Testnet)
//! .create_wallet_no_persist()?;
//! # Ok::<_, Box<dyn std::error::Error>>(())
//! ```
//!
//! ### Export a `Wallet`
//! ```
//! # use bitcoin::*;
//! # use bdk_wallet::export::*;
//! # use bdk_wallet::*;
//! let wallet = Wallet::create(
//! "wpkh([c258d2e4/84h/1h/0h]tpubDD3ynpHgJQW8VvWRzQ5WFDCrs4jqVFGHB3vLC3r49XHJSqP8bHKdK4AriuUKLccK68zfzowx7YhmDN8SiSkgCDENUFx9qVw65YyqM78vyVe/0/*)",
//! "wpkh([c258d2e4/84h/1h/0h]tpubDD3ynpHgJQW8VvWRzQ5WFDCrs4jqVFGHB3vLC3r49XHJSqP8bHKdK4AriuUKLccK68zfzowx7YhmDN8SiSkgCDENUFx9qVw65YyqM78vyVe/1/*)",
//! )
//! .network(Network::Testnet)
//! .create_wallet_no_persist()?;
//! let export = FullyNodedExport::export_wallet(&wallet, "exported wallet", true).unwrap();
//!
//! println!("Exported: {}", export.to_string());
//! # Ok::<_, Box<dyn std::error::Error>>(())
//! ```
use alloc::string::String;
use core::fmt;
use core::str::FromStr;
use serde::{Deserialize, Serialize};
use miniscript::descriptor::{ShInner, WshInner};
use miniscript::{Descriptor, ScriptContext, Terminal};
use crate::types::KeychainKind;
use crate::wallet::Wallet;
/// Alias for [`FullyNodedExport`]
#[deprecated(since = "0.18.0", note = "Please use [`FullyNodedExport`] instead")]
pub type WalletExport = FullyNodedExport;
/// Structure that contains the export of a wallet
///
/// For a usage example see [this module](crate::wallet::export)'s documentation.
#[derive(Debug, Serialize, Deserialize)]
pub struct FullyNodedExport {
descriptor: String,
/// Earliest block to rescan when looking for the wallet's transactions
pub blockheight: u32,
/// Arbitrary label for the wallet
pub label: String,
}
impl fmt::Display for FullyNodedExport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}
impl FromStr for FullyNodedExport {
type Err = serde_json::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
serde_json::from_str(s)
}
}
fn remove_checksum(s: String) -> String {
s.split_once('#').map(|(a, _)| String::from(a)).unwrap()
}
impl FullyNodedExport {
/// Export a wallet
///
/// This function returns an error if it determines that the `wallet`'s descriptor(s) are not
/// supported by Bitcoin Core or don't follow the standard derivation paths defined by BIP44
/// and others.
///
/// If `include_blockheight` is `true`, this function will look into the `wallet`'s database
/// for the oldest transaction it knows and use that as the earliest block to rescan.
///
/// If the database is empty or `include_blockheight` is false, the `blockheight` field
/// returned will be `0`.
pub fn export_wallet(
wallet: &Wallet,
label: &str,
include_blockheight: bool,
) -> Result<Self, &'static str> {
let descriptor = wallet
.public_descriptor(KeychainKind::External)
.to_string_with_secret(
&wallet
.get_signers(KeychainKind::External)
.as_key_map(wallet.secp_ctx()),
);
let descriptor = remove_checksum(descriptor);
Self::is_compatible_with_core(&descriptor)?;
let blockheight = if include_blockheight {
wallet.transactions().next().map_or(0, |canonical_tx| {
match canonical_tx.chain_position {
bdk_chain::ChainPosition::Confirmed(a) => a.block_id.height,
bdk_chain::ChainPosition::Unconfirmed(_) => 0,
}
})
} else {
0
};
let export = FullyNodedExport {
descriptor,
label: label.into(),
blockheight,
};
let change_descriptor = {
let descriptor = wallet
.public_descriptor(KeychainKind::Internal)
.to_string_with_secret(
&wallet
.get_signers(KeychainKind::Internal)
.as_key_map(wallet.secp_ctx()),
);
Some(remove_checksum(descriptor))
};
if export.change_descriptor() != change_descriptor {
return Err("Incompatible change descriptor");
}
Ok(export)
}
fn is_compatible_with_core(descriptor: &str) -> Result<(), &'static str> {
fn check_ms<Ctx: ScriptContext>(
terminal: &Terminal<String, Ctx>,
) -> Result<(), &'static str> {
if let Terminal::Multi(_) = terminal {
Ok(())
} else {
Err("The descriptor contains operators not supported by Bitcoin Core")
}
}
// pkh(), wpkh(), sh(wpkh()) are always fine, as well as multi() and sortedmulti()
match Descriptor::<String>::from_str(descriptor).map_err(|_| "Invalid descriptor")? {
Descriptor::Pkh(_) | Descriptor::Wpkh(_) => Ok(()),
Descriptor::Sh(sh) => match sh.as_inner() {
ShInner::Wpkh(_) => Ok(()),
ShInner::SortedMulti(_) => Ok(()),
ShInner::Wsh(wsh) => match wsh.as_inner() {
WshInner::SortedMulti(_) => Ok(()),
WshInner::Ms(ms) => check_ms(&ms.node),
},
ShInner::Ms(ms) => check_ms(&ms.node),
},
Descriptor::Wsh(wsh) => match wsh.as_inner() {
WshInner::SortedMulti(_) => Ok(()),
WshInner::Ms(ms) => check_ms(&ms.node),
},
Descriptor::Tr(_) => Ok(()),
_ => Err("The descriptor is not compatible with Bitcoin Core"),
}
}
/// Return the external descriptor
pub fn descriptor(&self) -> String {
self.descriptor.clone()
}
/// Return the internal descriptor, if present
pub fn change_descriptor(&self) -> Option<String> {
let replaced = self.descriptor.replace("/0/*", "/1/*");
if replaced != self.descriptor {
Some(replaced)
} else {
None
}
}
}
#[cfg(test)]
mod test {
use core::str::FromStr;
use crate::std::string::ToString;
use bdk_chain::{BlockId, ConfirmationBlockTime};
use bitcoin::hashes::Hash;
use bitcoin::{transaction, BlockHash, Network, Transaction};
use super::*;
use crate::Wallet;
fn get_test_wallet(descriptor: &str, change_descriptor: &str, network: Network) -> Wallet {
use crate::wallet::Update;
use bdk_chain::TxGraph;
let mut wallet = Wallet::create(descriptor.to_string(), change_descriptor.to_string())
.network(network)
.create_wallet_no_persist()
.expect("must create wallet");
let transaction = Transaction {
input: vec![],
output: vec![],
version: transaction::Version::non_standard(0),
lock_time: bitcoin::absolute::LockTime::ZERO,
};
let txid = transaction.compute_txid();
let block_id = BlockId {
height: 5000,
hash: BlockHash::all_zeros(),
};
wallet.insert_checkpoint(block_id).unwrap();
wallet
.insert_checkpoint(BlockId {
height: 5001,
hash: BlockHash::all_zeros(),
})
.unwrap();
wallet.insert_tx(transaction);
let anchor = ConfirmationBlockTime {
confirmation_time: 0,
block_id,
};
let mut graph = TxGraph::default();
let _ = graph.insert_anchor(txid, anchor);
wallet
.apply_update(Update {
graph,
..Default::default()
})
.unwrap();
wallet
}
#[test]
fn test_export_bip44() {
let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/1/*)";
let wallet = get_test_wallet(descriptor, change_descriptor, Network::Bitcoin);
let export = FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
assert_eq!(export.descriptor(), descriptor);
assert_eq!(export.change_descriptor(), Some(change_descriptor.into()));
assert_eq!(export.blockheight, 5000);
assert_eq!(export.label, "Test Label");
}
#[test]
#[should_panic(expected = "Incompatible change descriptor")]
fn test_export_no_change() {
// The wallet's change descriptor has no wildcard. It should be impossible to
// export, because exporting this kind of external descriptor normally implies the
// existence of a compatible internal descriptor
let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/1/0)";
let wallet = get_test_wallet(descriptor, change_descriptor, Network::Bitcoin);
FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
}
#[test]
#[should_panic(expected = "Incompatible change descriptor")]
fn test_export_incompatible_change() {
// This wallet has a change descriptor, but the derivation path is not in the "standard"
// bip44/49/etc format
let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/50'/0'/1/*)";
let wallet = get_test_wallet(descriptor, change_descriptor, Network::Bitcoin);
FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
}
#[test]
fn test_export_multi() {
let descriptor = "wsh(multi(2,\
[73756c7f/48'/0'/0'/2']tpubDCKxNyM3bLgbEX13Mcd8mYxbVg9ajDkWXMh29hMWBurKfVmBfWAM96QVP3zaUcN51HvkZ3ar4VwP82kC8JZhhux8vFQoJintSpVBwpFvyU3/0/*,\
[f9f62194/48'/0'/0'/2']tpubDDp3ZSH1yCwusRppH7zgSxq2t1VEUyXSeEp8E5aFS8m43MknUjiF1bSLo3CGWAxbDyhF1XowA5ukPzyJZjznYk3kYi6oe7QxtX2euvKWsk4/0/*,\
[c98b1535/48'/0'/0'/2']tpubDCDi5W4sP6zSnzJeowy8rQDVhBdRARaPhK1axABi8V1661wEPeanpEXj4ZLAUEoikVtoWcyK26TKKJSecSfeKxwHCcRrge9k1ybuiL71z4a/0/*\
))";
let change_descriptor = "wsh(multi(2,\
[73756c7f/48'/0'/0'/2']tpubDCKxNyM3bLgbEX13Mcd8mYxbVg9ajDkWXMh29hMWBurKfVmBfWAM96QVP3zaUcN51HvkZ3ar4VwP82kC8JZhhux8vFQoJintSpVBwpFvyU3/1/*,\
[f9f62194/48'/0'/0'/2']tpubDDp3ZSH1yCwusRppH7zgSxq2t1VEUyXSeEp8E5aFS8m43MknUjiF1bSLo3CGWAxbDyhF1XowA5ukPzyJZjznYk3kYi6oe7QxtX2euvKWsk4/1/*,\
[c98b1535/48'/0'/0'/2']tpubDCDi5W4sP6zSnzJeowy8rQDVhBdRARaPhK1axABi8V1661wEPeanpEXj4ZLAUEoikVtoWcyK26TKKJSecSfeKxwHCcRrge9k1ybuiL71z4a/1/*\
))";
let wallet = get_test_wallet(descriptor, change_descriptor, Network::Testnet);
let export = FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
assert_eq!(export.descriptor(), descriptor);
assert_eq!(export.change_descriptor(), Some(change_descriptor.into()));
assert_eq!(export.blockheight, 5000);
assert_eq!(export.label, "Test Label");
}
#[test]
fn test_export_tr() {
let descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/0/*)";
let change_descriptor = "tr([73c5da0a/86'/0'/0']tprv8fMn4hSKPRC1oaCPqxDb1JWtgkpeiQvZhsr8W2xuy3GEMkzoArcAWTfJxYb6Wj8XNNDWEjfYKK4wGQXh3ZUXhDF2NcnsALpWTeSwarJt7Vc/1/*)";
let wallet = get_test_wallet(descriptor, change_descriptor, Network::Testnet);
let export = FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
assert_eq!(export.descriptor(), descriptor);
assert_eq!(export.change_descriptor(), Some(change_descriptor.into()));
assert_eq!(export.blockheight, 5000);
assert_eq!(export.label, "Test Label");
}
#[test]
fn test_export_to_json() {
let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/1/*)";
let wallet = get_test_wallet(descriptor, change_descriptor, Network::Bitcoin);
let export = FullyNodedExport::export_wallet(&wallet, "Test Label", true).unwrap();
assert_eq!(export.to_string(), "{\"descriptor\":\"wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44\'/0\'/0\'/0/*)\",\"blockheight\":5000,\"label\":\"Test Label\"}");
}
#[test]
fn test_export_from_json() {
let descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/0/*)";
let change_descriptor = "wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44'/0'/0'/1/*)";
let import_str = "{\"descriptor\":\"wpkh(xprv9s21ZrQH143K4CTb63EaMxja1YiTnSEWKMbn23uoEnAzxjdUJRQkazCAtzxGm4LSoTSVTptoV9RbchnKPW9HxKtZumdyxyikZFDLhogJ5Uj/44\'/0\'/0\'/0/*)\",\"blockheight\":5000,\"label\":\"Test Label\"}";
let export = FullyNodedExport::from_str(import_str).unwrap();
assert_eq!(export.descriptor(), descriptor);
assert_eq!(export.change_descriptor(), Some(change_descriptor.into()));
assert_eq!(export.blockheight, 5000);
assert_eq!(export.label, "Test Label");
}
}

Some files were not shown because too many files have changed in this diff Show More