Compare commits

...

74 Commits

Author SHA1 Message Date
Steve Myers
30e54ac067 Bump version to 0.6.0 2022-05-10 22:41:48 -07:00
Steve Myers
71583eca7f Merge bitcoindevkit/bdk-ffi#150: Add new BumpFeeTxBuilder interface
0787d9c446 Fix order of BumpFeeTxBuilder parameters (Steve Myers)
390d12703e Change TxBuilder and BumpFeeTxBuilder build() to finish() (Steve Myers)
9f903932dc Add BumpFeeTxBuilder (Steve Myers)

Pull request description:

  Add BumpFeeTxBuilder to bump the fee on an unconfirmed tx created by the Wallet. The structure of the new interface is:

  ```udl
  interface BumpFeeTxBuilder {
    constructor(string txid, float new_fee_rate);
    BumpFeeTxBuilder allow_shrinking(string address);
    BumpFeeTxBuilder enable_rbf();
    BumpFeeTxBuilder enable_rbf_with_sequence(u32 nsequence);
    [Throws=BdkError]
    PartiallySignedBitcoinTransaction build([ByRef] Wallet wallet);
  };
  ```
  Fixes #150

Top commit has no ACKs.

Tree-SHA512: a24ed41f7b897a0e091ef55d4c1347b3973cbe628b7d1bd69c95e663bc6f049de8f7e3b019115d763cff3fa6d5cb4d31ed474022c3087e8404a2af37f380d56d
2022-05-10 22:35:32 -07:00
Steve Myers
0787d9c446 Fix order of BumpFeeTxBuilder parameters 2022-05-06 09:59:07 -07:00
Steve Myers
390d12703e Change TxBuilder and BumpFeeTxBuilder build() to finish() 2022-05-06 09:52:20 -07:00
Steve Myers
9f903932dc Add BumpFeeTxBuilder 2022-05-05 20:22:55 -07:00
Steve Myers
3b243efefd Merge bitcoindevkit/bdk-ffi#149: Update to bdk 0.18.0
f38f4c6197 Update CHANGELOG (Steve Myers)
11ba16ec1b Move txid getter to PartiallySignedBitcoinTransaction (Steve Myers)
4665c551dd Update EsploraConfig, Blockchain broadcast, Wallet sync (Steve Myers)
907540d214 Update bdk to 0.18.0 with sqlite-bundled feature (Steve Myers)

Pull request description:

  Changes that were needed to match updated bdk APIs:
  * new bdk-ffi `Blockchain`  interface with `constructo(BlockchainConfig)` and `broadcast()` functions
  * `Blockchain.broadcast()` function is now void (doesn't return txid)
  * added `PartiallySignedBitcoinTransaction.txid()` getter function
  * `Wallet.sync()` function now takes a `Blockchain` and optional `Progress` callback interface

  Tests performed:
  * from `bdk-kotlin/bdk-ffi` added local remote to this branch, ran build.sh script
  * fixed broken `bdk-kotlin` jvm and android tests and confirmed tests all pass

Top commit has no ACKs.

Tree-SHA512: d50633bbc8fd8a0d141597b30122c72957d2a0d64fc1537b649eeb8a5df1b1fb9a78ee1f03b9c606f47dee3952c9a91ae09eb47eb7a66d5f0fcb5545c86d906b
2022-05-05 09:29:37 -07:00
Steve Myers
f38f4c6197 Update CHANGELOG 2022-05-02 16:17:27 -07:00
Steve Myers
11ba16ec1b Move txid getter to PartiallySignedBitcoinTransaction 2022-04-25 21:31:40 -07:00
Steve Myers
4665c551dd Update EsploraConfig, Blockchain broadcast, Wallet sync 2022-04-25 21:31:38 -07:00
Steve Myers
907540d214 Update bdk to 0.18.0 with sqlite-bundled feature 2022-04-25 21:31:36 -07:00
Steve Myers
e6a6be5b60 Merge bitcoindevkit/bdk-ffi#145: Fix fee parameter typo in TransactionDetails
c722223b49 Fix fee parameter typo in TransactionDetails (dhruvbaliyan)

Pull request description:

  Solves issue #136
  Generated Kotlin file now have "fee" in TransactionDetails as parameter instead of "fees"
  ```
  data class TransactionDetails (
      var fee: ULong?,
      var received: ULong,
      var sent: ULong,
      var txid: String
  ) {
      // ...
  }
  ```

ACKs for top commit:
  thunderbiscuit:
    Tested ACK c722223. Works as expected in my apps. Thanks for the quick fix!

Tree-SHA512: c55a6e77ca5a0cd19758fc628fc48ed997b3c86247a1eadf5be77771818e3aa5f4db10025e7aa30d05be573e94d7439b15c7fc1f3d6dad752487f7f1ad455367
2022-04-25 21:30:17 -07:00
dhruvbaliyan
c722223b49 Fix fee parameter typo in TransactionDetails 2022-04-20 06:13:49 +05:30
Steve Myers
236360e8c4 Merge bitcoindevkit/bdk-ffi#140: Add RBF methods to TxBuilder
220835cffd Add RBF to TxBuilder (Sudarsan Balaji)
b3c93b0435 Expose functions (Sudarsan Balaji)

Pull request description:

  Fix #133

  We need to create another `RbfValue` enum because the actual type is only visible within the crate in `bdk`.

ACKs for top commit:
  notmandatory:
    tACK 220835cffd

Tree-SHA512: 648ea26a9742c8a395876f38c7299ff0dabb4ccad64e2f6a47d29ceecf44d9e54d845410fa68665e4d4d03d8eda1e51f680d0b89df307b003de49cf7b98e8701
2022-04-16 22:36:34 -07:00
Sudarsan Balaji
220835cffd Add RBF to TxBuilder 2022-04-15 21:04:21 +01:00
Sudarsan Balaji
b3c93b0435 Expose functions 2022-04-15 21:04:04 +01:00
Sudarsan Balaji
a12e5ed396 Use Path instead of PathBuf 2022-04-04 11:07:51 +01:00
Sudarsan Balaji
fc00d0d38c Use unwrap_or_else panic instead of expect 2022-04-04 11:01:50 +01:00
Sudarsan Balaji
7ea5e75bc4 Use write_all when not writing partially 2022-04-04 10:59:19 +01:00
Sudarsan Balaji
a5bd16db4d Enforce rust naming conventions 2022-04-04 10:58:01 +01:00
Steve Myers
d72905168b Merge bitcoindevkit/bdk-ffi#128: Release/0.5
8a556d0ba0 Bump bdk-ffi version to 0.5.0 (Steve Myers)
d7c5f24fe8 Bump bdk-ffi-bindgen version to 0.2.0 (Steve Myers)
f1431c3073 Update CHANGELOG.md (Steve Myers)

Pull request description:

Top commit has no ACKs.

Tree-SHA512: 2d612936740b93148c90acf512005c82e1fe38b4708710952abeac03d361e7dca6c6bdea4e82981a87dbba1cb6d37c0bd48b4ab252467798aa60aca463af5e5e
2022-04-01 19:24:48 -07:00
Steve Myers
8a556d0ba0 Bump bdk-ffi version to 0.5.0 2022-04-01 19:16:53 -07:00
Steve Myers
d7c5f24fe8 Bump bdk-ffi-bindgen version to 0.2.0 2022-04-01 19:16:29 -07:00
Steve Myers
f1431c3073 Update CHANGELOG.md 2022-04-01 19:15:58 -07:00
Steve Myers
e797efea57 Merge bitcoindevkit/bdk-ffi#126: Add workspace and bdk-ffi-bindgen binary cli tool
b207464fe6 Update README.md with bdk-ffi-bindgen info (Steve Myers)
fca5d1602b Add workspace and move bin to bdk-ffi-bindgen package (Steve Myers)
f4e097c4ac Only print python fix up lib path if used (Steve Myers)
c66dfdd52a Use structopt to capture generate options (Steve Myers)
ce848725b4 Add binary to remove the need for uniffi-bindgen cli tool (thunderbiscuit)

Pull request description:

  This PR is based on the mozilla/application-services [embedded-uniffi-bindgen](https://github.com/mozilla/application-services/tree/main/tools/embedded-uniffi-bindgen) tool. The purpose is to keep the bdk-ffi and bdk-ffi-bindgen tool in sync with the same version of uniffi-rs.

  Fixes #124, this PR replaces #122.

  The `bdkffi` library code remains unchanged but the `bin/generate` and `bin/generate-bindings` bins are combined and put in a new workspace binary package called `bdk-ffi-bindgen`.  The `bdk-ffi-bindgen` binary uses the following options, defaults, and environment variables:

  ```shell
  % cargo run -p bdk-ffi-bindgen -- --help

  bdk-ffi-bindgen 0.1.0
  A tool to generate bdk-ffi language bindings

  USAGE:
      bdk-ffi-bindgen [OPTIONS] --language <language> --out-dir <out-dir>

  FLAGS:
      -h, --help       Prints help information
      -V, --version    Prints version information

  OPTIONS:
      -l, --language <language>
              Language to generate bindings for [env: BDKFFI_BINDGEN_LANGUAGE=]  [possible values: kotlin, swift, python]

      -o, --out-dir <out-dir>
              Output directory to put generated language bindings [env: BDKFFI_BINDGEN_OUTPUT_DIR=]

      -p, --python-fixup-path <python-fixup-path>    Python fix up lib path [env: BDKFFI_BINDGEN_PYTHON_FIXUP_PATH=]
      -u, --udl-file <udl-file>                      UDL file [env: BDKFFI_BINDGEN_UDL=]  [default: src/bdk.udl]

  ```

Top commit has no ACKs.

Tree-SHA512: fa1a1c097fe5d0e704d76078c10f82c466dad5d045c8c93d579c2d13c448c52fb6a4f99dfd3dbc46be30471477ae2d1f9264201e14bae7948b408c8e0b3c9b81
2022-04-01 18:58:18 -07:00
Sudarsan Balaji
a41d628b14 Fix typo 2022-04-01 13:56:43 +05:30
Steve Myers
b207464fe6 Update README.md with bdk-ffi-bindgen info 2022-03-31 20:18:31 -07:00
Steve Myers
fca5d1602b Add workspace and move bin to bdk-ffi-bindgen package 2022-03-31 19:29:05 -07:00
Steve Myers
f4e097c4ac Only print python fix up lib path if used 2022-03-31 19:29:03 -07:00
Steve Myers
c66dfdd52a Use structopt to capture generate options 2022-03-31 19:29:01 -07:00
thunderbiscuit
ce848725b4 Add binary to remove the need for uniffi-bindgen cli tool 2022-03-31 19:28:59 -07:00
Sudarsan Balaji
5512b31969 Simplify 2022-03-31 17:26:32 +01:00
Sudarsan Balaji
a48f9b4387 Simplify 2022-03-31 17:22:52 +01:00
Sudarsan Balaji
87a0a15ea7 Fix formatting
cargo fmt
2022-03-31 17:18:03 +01:00
Sudarsan Balaji
ee91ad5b31 Add TxBuilder::drain_to 2022-03-31 17:17:43 +01:00
Sudarsan Balaji
ba68103be1 Add TxBuilder::drain_wallet 2022-03-31 17:17:24 +01:00
Steve Myers
bc43d2eb1a Map TxBuilder address error to BdkError::Generic 2022-03-28 17:30:40 -07:00
Sudarsan Balaji
adc3f68e31 Remove unnecessary map_err 2022-03-28 20:04:22 +01:00
Sudarsan Balaji
dd5622f724 Remove PSBT constructor 2022-03-25 17:39:25 +00:00
Sudarsan Balaji
e5aa51c3f8 Use TxBuilder in PSBT constructor 2022-03-25 17:37:25 +00:00
Sudarsan Balaji
a39fc787d5 Add initial version of TxBuilder 2022-03-25 17:24:21 +00:00
Sudarsan Balaji
51603e06d9 Remove to_owned() 2022-03-25 15:18:25 +00:00
Steve Myers
a1b89adf84 Remove unneeded WalletHolder and WalletOperations traits 2022-03-20 19:59:20 -05:00
Steve Myers
b1d483463f Merge bitcoindevkit/bdk-ffi#120: Fix Wallet.broadcast function, now returns a tx id as a hex string
851f61296a Fix Wallet.broadcast function, now returns a tx id as a hex string (Steve Myers)

Pull request description:

ACKs for top commit:
  thunderbiscuit:
    Tested ACK 851f612.

Tree-SHA512: 86e1d39029924e4fa3a0c21e9f45c1ba0694f4db9d1cfd8dee25a5675d5a8b7851a7c712ce57fb74382a7428fcecbe8ecee4b7b87b9245672bbd6ccea63dfc13
2022-03-16 16:53:20 -05:00
Steve Myers
851f61296a Fix Wallet.broadcast function, now returns a tx id as a hex string 2022-03-15 20:50:12 -05:00
Steve Myers
5128ce8d5b Bump version to 0.4.1 2022-03-14 14:46:31 -05:00
Steve Myers
c6e9a62628 Bump version to 0.4.0 2022-03-14 14:40:55 -05:00
Steve Myers
f76f3234b4 Merge bitcoindevkit/bdk-ffi#109: Refactor memory database config enum
cc3736809a Fix memory database configuration enum (thunderbiscuit)

Pull request description:

  The `DatabaseConfig.Memory` enum currently requires a "junk" string argument which is not used when creating the wallet:

  ```rust
  // lib.rs line 24
  pub enum DatabaseConfig {
      Memory { junk: String },
      Sled { config: SledDbConfiguration },
  }

  // lib.rs line 209
  impl Wallet {
      fn new(
          descriptor: String,
          change_descriptor: Option<String>,
          network: Network,
          database_config: DatabaseConfig,
          blockchain_config: BlockchainConfig,
      ) -> Result<Self, BdkError> {
          let any_database_config = match database_config {
              DatabaseConfig::Memory { .. } => AnyDatabaseConfig::Memory(()),
              DatabaseConfig::Sled { config } => AnyDatabaseConfig::Sled(config),
          };
  ```

  Which translates to the udl file like this:
  ```txt
  [Enum]
  interface DatabaseConfig {
    Memory(string junk);
    Sled(SledDbConfiguration config);
  };
  ```

  According to the [docs from uniffi-rs](https://mozilla.github.io/uniffi-rs/udl/enumerations.html) the `interface` here is required because the enums have named fields. But after testing I found that we can declare the udl file like so, and remove the requirement for the `junk` argument:
  ```txt
  [Enum]
  interface DatabaseConfig {
    Memory();
    Sled(SledDbConfiguration config);
  };
  ```

  On the Rust side we then have
  ```rust
  pub enum DatabaseConfig {
      Memory,
      Sled { config: SledDbConfiguration },
  }
  ```

  And the resulting bindings go from (note that the bindings transform the enum into a sealed class rather than a Kotlin enum)
  ```kotlin
  sealed class DatabaseConfig  {

      data class Memory(
          val junk: String
          ) : DatabaseConfig()

      data class Sled(
          val config: SledDbConfiguration
          ) : DatabaseConfig()
  ```
  to
  ```kotlin
  sealed class DatabaseConfig  {
      object Memory : DatabaseConfig()

      data class Sled(
          val config: SledDbConfiguration
          ) : DatabaseConfig()
  ```

  Which makes the API simpler to use, and removes the confusion created by having to provide an empty string (or not know what we're supposed to provide) to the `Memory()` enum.

  The final call-site looks like this:
  ```kotlin
      fun onlineWalletSyncGetBalance() {
          // val db = DatabaseConfig.Memory("")
          val db = DatabaseConfig.Memory
          val client = BlockchainConfig.Electrum(
              ElectrumConfig(
                  "ssl://electrum.blockstream.info:60002",
                  null,
                  5u,
                  null,
                  100u
              )
          )
          val wallet = Wallet(descriptor, null, Network.REGTEST, databaseConfig, blockchainConfig)
          wallet.sync(LogProgress(), null)
          val balance = wallet.getBalance()
          assertTrue(balance > 0u)
      }
  ```

  All tests run well on my side of things, but I'm opening this more as a discussion piece because I wasn't sure if there were other reasons for the choice of providing the argument to the `Memory` enum, or other design choices I'm not aware of. Any thoughts on this @artfuldev? I think you were the one who wrote the initial enum.

Top commit has no ACKs.

Tree-SHA512: 135e5943039a08522773f721a7cf6bbb93bd5bb9394bf42a30bab5f3e16fd35ce078056756e020a666d4f574d74080bc3404cc81809c0d7e0afe5c9471878425
2022-03-14 10:02:04 -05:00
thunderbiscuit
cc3736809a Fix memory database configuration enum 2022-03-14 10:01:45 -04:00
Steve Myers
4fc9fb916b Merge bitcoindevkit/bdk-ffi#116: Add sqlite database support
12f4784b85 Add sqlite database option (Steve Myers)

Pull request description:

  ### Description

  Add sqlite db database option.

  ### Notes to the reviewers

  When https://github.com/bitcoindevkit/bdk/pull/566 is released we need to updated this project to use the `sqlite-packaged` feature, see TODO in Cargo.toml.

ACKs for top commit:
  thunderbiscuit:
    Tested ACK [12f4784](12f4784b85).

Tree-SHA512: c39472507596e036dd81c22a05d424c6d363545b1a8bd622bf9647967b1b86ab44764da1a15169ac542c80a62a79331b5abcda7b657cc28d93ffdda51a62bd6e
2022-03-13 19:09:28 -05:00
Steve Myers
12f4784b85 Add sqlite database option 2022-03-11 22:45:37 -06:00
Steve Myers
58e75d1a1d Merge commit 'refs/pull/112/head' of github.com:bitcoindevkit/bdk-ffi 2022-03-02 14:49:41 -08:00
Steve Myers
89d58db02a Bump version to 0.3.1 2022-03-02 14:46:06 -08:00
Steve Myers
cda682b634 Remove hard coded sync progress value 2022-03-02 14:45:26 -08:00
Steve Myers
939a88214a Remove hard coded sync progress value 2022-03-02 14:06:40 -08:00
Steve Myers
1bbd85378a Merge bitcoindevkit/bdk-ffi#107: Add license files
f3c6d97d81 Add license files (Steve Myers)
d17ea4b90c Bump version to 0.3.0 (Steve Myers)
76fa9b9521 Add CHANGELOG.md (Steve Myers)

Pull request description:

  This issue is based on https://github.com/bitcoindevkit/bdk/issues/301, to be clear we should add license files to all our repositories.

  If you're on the below list and agree with this change please add a comment with "I hereby license my previous contributions to BDK under [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) and [MIT](https://choosealicense.com/licenses/mit/) licenses."

  - [x] @artfuldev
  - [x] @notmandatory
  - [x] @afilini
  - [x] @thunderbiscuit

Top commit has no ACKs.

Tree-SHA512: 7e0f2c7bf93d1cdb28cec979330790e00c1efd3ce80986e9084bc371fa73eda6413014e3ad8e598ca6ce1f797622dbfbe8339453de8d7ebefbb27fd5204bc4c6
2022-02-28 09:19:41 -08:00
Steve Myers
f3c6d97d81 Add license files 2022-02-27 21:26:23 -08:00
Steve Myers
d17ea4b90c Bump version to 0.3.0 2022-02-27 21:18:05 -08:00
Steve Myers
76fa9b9521 Add CHANGELOG.md 2022-02-27 21:17:37 -08:00
Steve Myers
cafa8dacab Merge bitcoindevkit/bdk-ffi#104: Add PSBT deserialize and serialize functions, remove details
c039281ffc Add PSBT deserialize and serialize functions, remove details (Steve Myers)
1f0b053872 Fix bin/generate with no features (Steve Myers)

Pull request description:

  1. Fix bin/generate with no features
  2. Add `PartiallySignedBitcoinTransaction::deserialize` function as named constructor to decode from a string per [BIP 0174]
  3. Add `PartiallySignedBitcoinTransaction::serialize` function to encode to a string per [BIP 0174]
  4. Remove `PartiallySignedBitcoinTransaction.details` struct field

  [BIP 0174]:https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#encoding

  Fixes #103

Top commit has no ACKs.

Tree-SHA512: 0ba34d96625d71434d41573089a150d09fcfb6439648a7eed6e36dcdddd2682c969525b7c6efda898b2f979a7ca6ce51dc2158acf65da7f1f4c554d98b60f4ff
2022-02-25 14:47:47 -08:00
Steve Myers
c039281ffc Add PSBT deserialize and serialize functions, remove details 2022-02-24 20:49:59 -08:00
Steve Myers
1f0b053872 Fix bin/generate with no features 2022-02-24 17:17:05 -08:00
Alekos Filini
97f1011748 Add a binary to generate bindings 2022-02-08 22:15:10 +01:00
Alekos Filini
edfcde1cc6 Generate bindings for Python in build.rs 2022-02-08 21:04:12 +01:00
Sudarsan Balaji
15c0dac622 Rename field to wallet_mutex 2022-01-30 21:22:40 +00:00
Sudarsan Balaji
a99e022756 Rename OnlineWallet to Wallet
and remove OfflineWallet
2022-01-24 20:32:49 +00:00
Steve Myers
672131ca0f Fix uniffi_macros and uniffi_build versions 2022-01-24 10:58:48 -08:00
Steve Myers
72f90f1d63 Upgrade bdk to 0.14.0 2021-12-21 22:16:29 -08:00
Steve Myers
5240cd895e Update uniffi-rs to 0.16.0 2021-12-21 22:16:27 -08:00
Steve Myers
55462fb426 Remove bindings and examples, update README.md 2021-12-21 22:16:25 -08:00
Steve Myers
9188dec2f2 Remove swift related files and -s option in build.sh
Build script and files to create a bdkFFI binary xcframework and BitcoinDevKit swift package
have been moved to the bdk-swift repo.
2021-11-24 12:23:19 -08:00
Steve Myers
a9a01950ee Fix IOSBdkAppSample to work with git hosted BitcoinDevKit swift package 2021-11-23 10:05:19 -08:00
Steve Myers
39cc3b3bfa Update build.sh to create swift xcframework 2021-11-23 10:05:19 -08:00
Steve Myers
c08fe99ad6 Pin anyhow version to "=1.0.45"
This change can be removed after upgrading to the next version of uniffi.
See: https://github.com/mozilla/uniffi-rs/issues/1109
2021-11-22 15:59:12 -08:00
thunderbiscuit
d53eb793ea Refactor transaction 'id' property to 'txid' 2021-11-12 12:50:40 -05:00
13 changed files with 887 additions and 499 deletions

3
.gitignore vendored
View File

@@ -2,9 +2,6 @@ target
build
Cargo.lock
/bindings/bdk-kotlin/local.properties
/bindings/bdk-swift
/bindings/bdk-swift.swiftdoc
/bindings/bdk-swift.swiftsourceinfo
.gradle
wallet_db
bdk_ffi_test

52
CHANGELOG.md Normal file
View File

@@ -0,0 +1,52 @@
# Changelog
All notable changes to this project will be documented in this file.
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.6.0]
- Update BDK to version 0.18.0
- Add BumpFeeTxBuilder to bump the fee on an unconfirmed tx created by the Wallet
- Change TxBuilder.build() to TxBuilder.finish() to align with bdk function name
## [v0.5.0]
- Fix Wallet.broadcast function, now returns a tx id as a hex string
- Remove creating a new spending Transaction via the PartiallySignedBitcoinTransaction constructor
- Add TxBuilder for creating new spending PartiallySignedBitcoinTransaction
- Add TxBuilder .add_recipient, .fee_rate, and .build functions
- Add TxBuilder .drain_wallet and .drain_to functions
- Update generate cli tool to generate all binding languages and rename to bdk-ffi-bindgen
## [v0.4.0]
- Add dual license MIT and Apache 2.0
- Add sqlite database support
- Fix memory database configuration enum, remove junk field
## [v0.3.1]
- Remove hard coded sync progress value (was always returning 21.0)
## [v0.3.0]
- Move bdk-kotlin bindings and ios example to separate repos
- Add bin to generate Python bindings
- Add `PartiallySignedBitcoinTransaction::deserialize` function as named constructor to decode from a string per [BIP 0174]
- Add `PartiallySignedBitcoinTransaction::serialize` function to encode to a string per [BIP 0174]
- Remove `PartiallySignedBitcoinTransaction.details` struct field
[BIP 0174]:https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#encoding
## [v0.2.0]
[unreleased]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.6.0...HEAD
[v0.6.0]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.5.0...v0.6.0
[v0.5.0]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.4.0...v0.5.0
[v0.4.0]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.3.1...v0.4.0
[v0.3.1]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.3.0...v0.3.1
[v0.3.0]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.2.0...v0.3.0
[v0.2.0]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.0.0...v0.2.0

View File

@@ -1,19 +1,23 @@
[package]
name = "bdk-ffi"
version = "0.1.0"
version = "0.6.0"
authors = ["Steve Myers <steve@notmandatory.org>", "Sudarsan Balaji <sudarsan.balaji@artfuldev.com>"]
edition = "2018"
[workspace]
members = [".","bdk-ffi-bindgen"]
default-members = [".", "bdk-ffi-bindgen"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["staticlib", "cdylib"]
name = "bdkffi"
[dependencies]
bdk = { version = "0.13", features = ["all-keys", "use-esplora-ureq"] }
uniffi_macros = "0.14.1"
uniffi = "0.14.1"
thiserror = "1.0"
bdk = { version = "0.18", features = ["all-keys", "use-esplora-ureq", "sqlite-bundled"] }
uniffi_macros = { version = "0.16.0", features = ["builtin-bindgen"] }
uniffi = { version = "0.16.0", features = ["builtin-bindgen"] }
[build-dependencies]
uniffi_build = "0.14.1"
uniffi_build = { version = "0.16.0", features = ["builtin-bindgen"] }

14
LICENSE Normal file
View File

@@ -0,0 +1,14 @@
This software is licensed under [Apache 2.0](LICENSE-APACHE) or
[MIT](LICENSE-MIT), at your option.
Some files retain their own copyright notice, however, for full authorship
information, see version control history.
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.
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.

110
README.md
View File

@@ -1,89 +1,43 @@
# Foreign language bindings for BDK (bdk-ffi)
# Native language bindings for BDK
This repository contains source code for generating foreign language bindings
for the rust library bdk for the Bitcoin Dev Kit (BDK) project.
The workspace in this repository creates the `libbdkffi` multi-language library for the rust based
[bdk] library from the [Bitcoin Dev Kit] project. The `bdk-ffi-bindgen` package builds a tool for
generating the actual language binding code used to access the `libbdkffi` library.
Each supported language has its own repository that includes this project as a [git submodule].
The rust code in this project is a wrapper around the [bdk] library to expose it's APIs in a
uniform way using the [mozilla/uniffi-rs] bindings generator for each supported target language.
## Supported target languages and platforms
| Language | Platform | Status |
| --- | --- | --- |
| Kotlin | JVM | WIP |
| Kotlin | Android | WIP |
| Swift | iOS | WIP |
The below repositories include instructions for using, building, and publishing the native
language binding for [bdk] supported by this project.
| Language | Platform | Repository |
| -------- | ------------ | ------------ |
| Kotlin | jvm | [bdk-kotlin] |
| Kotlin | android | [bdk-kotlin] |
| Swift | iOS, macOS | [bdk-swift] |
| Python | linux, macOS | [bdk-python] |
## Getting Started (User)
## Language bindings generator tool
If you just want to consume the language bindings:
Use the `bdk-ffi-bindgen` tool to generate language binding code for the above supported languages.
To run `bdk-ffi-bindgen` and see the available options use the command:
```shell
cargo run -p bdk-ffi-bindgen -- --help
```
### Kotlin (JVM)
[bdk]: https://github.com/bitcoindevkit/bdk
[Bitcoin Dev Kit]: https://github.com/bitcoindevkit
[git submodule]: https://git-scm.com/book/en/v2/Git-Tools-Submodules
[uniffi-rs]: https://github.com/mozilla/uniffi-rs
Just add the dependency `org.bitcoindevkit:bdk-jvm:0.1.1`. The package is `org.bitcoindevkit.bdk`.
[bdk-kotlin]: https://github.com/bitcoindevkit/bdk-kotlin
[bdk-swift]: https://github.com/bitcoindevkit/bdk-swift
[bdk-python]: https://github.com/thunderbiscuit/bdk-python
### Kotlin (Android)
Just add the dependency `org.bitcoindevkit:bdk-android:0.1.1`. The package is `org.bitcoindevkit.bdk`.
## Getting Started (Developer)
This project uses rust. A basic knowledge of the rust ecosystem is helpful.
### General
1. Install `uniffi-bindgen`
```sh
cargo install uniffi_bindgen
```
1. See the [UniFFI User Guide](https://mozilla.github.io/uniffi-rs/) for more info
### Kotlin Bindings for JVM (OSX / Linux)
1. Install required targets
```sh
rustup target add x86_64-apple-darwin x86_64-unknown-linux-gnu
```
1. Build kotlin (JVM) bindings
```sh
./build.sh -k
```
1. Generated kotlin bindings are available at `/bindings/bdk-kotlin/`
1. A demo app is available at `/bindings/bdk-kotlin/demo/`. It uses stdin for
inputs and can be run from gradle.
```sh
cd bindings/bdk-kotlin
./gradlew :demo:run
```
### Kotlin bindings for Android
1. Install required targets
```sh
rustup target add x86_64-linux-android aarch64-linux-android
armv7-linux-androideabi i686-linux-android
```
1. Install Android SDK and Build-Tools for API level 30+
1. Setup `$ANDROID_NDK_HOME` and `$ANDROID_SDK_ROOT` path variables (which are
required by the build scripts)
1. Build kotlin (Android) bindings
```sh
./build.sh -a
```
2. A demo android app is available at [notmandatory/bdk-sample-app](https://github.com/notmandatory/bitcoindevkit-android-sample-app/tree/upgrade-to-bdk-ffi/)
### Swift bindings for iOS
1. Install the latest version of xcode, download and install the advanced tools.
1. Ensure Swift is installed
1. Install required targets
```sh
rustup target add aarch64-apple-ios x86_64-apple-ios
```
1. Build swift (iOS) bindings
```sh
./build.sh -s
```
1. Example iOS app can be found in `/examples/iOS` which can be run by xcode.
## Notes
## Contributing
### Adding new structs and functions
@@ -109,4 +63,6 @@ See the [UniFFI User Guide](https://mozilla.github.io/uniffi-rs/)
## Thanks
This project is made possible thanks to the wonderful work on [mozilla/uniffi-rs](https://github.com/mozilla/uniffi-rs)
This project is made possible thanks to the wonderful work by the [mozilla/uniffi-rs] team.
[mozilla/uniffi-rs]: https://github.com/mozilla/uniffi-rs

View File

@@ -0,0 +1,11 @@
[package]
name = "bdk-ffi-bindgen"
version = "0.2.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "=1.0.45" # remove after upgrading to next version of uniffi
structopt = "0.3"
uniffi_bindgen = "0.16.0"

134
bdk-ffi-bindgen/src/main.rs Normal file
View File

@@ -0,0 +1,134 @@
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use structopt::StructOpt;
#[derive(Debug, PartialEq)]
pub enum Language {
Kotlin,
Python,
Swift,
}
impl fmt::Display for Language {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Language::Kotlin => write!(f, "kotlin"),
Language::Swift => write!(f, "swift"),
Language::Python => write!(f, "python"),
}
}
}
#[derive(Debug)]
pub enum Error {
UnsupportedLanguage,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl FromStr for Language {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"kotlin" => Ok(Language::Kotlin),
"python" => Ok(Language::Python),
"swift" => Ok(Language::Swift),
_ => Err(Error::UnsupportedLanguage),
}
}
}
fn generate_bindings(opt: &Opt) -> anyhow::Result<(), anyhow::Error> {
uniffi_bindgen::generate_bindings(
&opt.udl_file,
None,
vec![opt.language.to_string().as_str()],
Some(&opt.out_dir),
false,
)?;
Ok(())
}
fn fixup_python_lib_path(
out_dir: &Path,
lib_name: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
use std::fs;
use std::io::Write;
const LOAD_INDIRECT_DEF: &str = "def loadIndirect():";
let bindings_file = out_dir.join("bdk.py");
let mut data = fs::read_to_string(&bindings_file)?;
let pos = data
.find(LOAD_INDIRECT_DEF)
.unwrap_or_else(|| panic!("loadIndirect not found in `{}`", bindings_file.display()));
let range = pos..pos + LOAD_INDIRECT_DEF.len();
let replacement = format!(
r#"
def loadIndirect():
import glob
return getattr(ctypes.cdll, glob.glob(os.path.join(os.path.dirname(os.path.abspath(__file__)), '{}.*'))[0])
def _loadIndirectOld():"#,
&lib_name.to_str().expect("lib name")
);
data.replace_range(range, &replacement);
let mut file = fs::OpenOptions::new()
.write(true)
.truncate(true)
.open(&bindings_file)?;
file.write_all(data.as_bytes())?;
Ok(())
}
#[derive(Debug, StructOpt)]
#[structopt(
name = "bdk-ffi-bindgen",
about = "A tool to generate bdk-ffi language bindings"
)]
struct Opt {
/// UDL file
#[structopt(env = "BDKFFI_BINDGEN_UDL", short, long, default_value("src/bdk.udl"), parse(try_from_str = PathBuf::from_str))]
udl_file: PathBuf,
/// Language to generate bindings for
#[structopt(env = "BDKFFI_BINDGEN_LANGUAGE", short, long, possible_values(&["kotlin","swift","python"]), parse(try_from_str = Language::from_str))]
language: Language,
/// Output directory to put generated language bindings
#[structopt(env = "BDKFFI_BINDGEN_OUTPUT_DIR", short, long, parse(try_from_str = PathBuf::from_str))]
out_dir: PathBuf,
/// Python fix up lib path
#[structopt(env = "BDKFFI_BINDGEN_PYTHON_FIXUP_PATH", short, long, parse(try_from_str = PathBuf::from_str))]
python_fixup_path: Option<PathBuf>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let opt = Opt::from_args();
println!("Input UDL file is {:?}", opt.udl_file);
println!("Chosen language is {}", opt.language);
println!("Output directory is {:?}", opt.out_dir);
generate_bindings(&opt)?;
if opt.language == Language::Python {
if let Some(path) = opt.python_fixup_path {
println!("Fixing up python lib path, {:?}", &path);
fixup_python_lib_path(&opt.out_dir, &path)?;
}
}
Ok(())
}

145
build.sh
View File

@@ -1,145 +0,0 @@
#!/usr/bin/env bash
set -eo pipefail
# functions
## help
help()
{
# Display Help
echo "Build bdk-ffi and related libraries."
echo
echo "Syntax: build [-a|h|k|s]"
echo "options:"
echo "-a Android."
echo "-h Print this Help."
echo "-k Kotlin."
echo "-s Swift."
echo
}
## rust
build_rust() {
echo "Build Rust library"
cargo fmt
cargo build
cargo test
}
## copy to bdk-bdk-kotlin
copy_lib_kotlin() {
echo -n "Copy "
case $OS in
"Darwin")
echo -n "darwin "
mkdir -p bindings/bdk-kotlin/jvm/src/main/resources/darwin-x86-64
cp target/debug/libbdkffi.dylib bindings/bdk-kotlin/jvm/src/main/resources/darwin-x86-64
;;
"Linux")
echo -n "linux "
mkdir -p bindings/bdk-kotlin/jvm/src/main/resources/linux-x86-64
cp target/debug/libbdkffi.so bindings/bdk-kotlin/jvm/src/main/resources/linux-x86-64
;;
esac
echo "libs to kotlin sub-project"
}
## bdk-bdk-kotlin jar
build_kotlin() {
copy_lib_kotlin
uniffi-bindgen generate src/bdk.udl --no-format --out-dir bindings/bdk-kotlin/jvm/src/main/kotlin --language kotlin
}
## bdk swift
build_swift() {
uniffi-bindgen generate src/bdk.udl --no-format --out-dir bindings/bdk-swift/ --language swift
swiftc -module-name bdk -emit-library -o libbdkffi.dylib -emit-module -emit-module-path ./bindings/bdk-swift/ -parse-as-library -L ./target/debug/ -lbdkffi -Xcc -fmodule-map-file=./bindings/bdk-swift/bdkFFI.modulemap ./bindings/bdk-swift/bdk.swift
TARGETDIR=target
RELDIR=debug
STATIC_LIB_NAME=libbdkffi.a
# We can't use cargo lipo because we can't link to universal libraries :(
# https://github.com/rust-lang/rust/issues/55235
LIBS_ARCHS=("x86_64" "arm64")
IOS_TRIPLES=("x86_64-apple-ios" "aarch64-apple-ios")
for i in "${!LIBS_ARCHS[@]}"; do
cargo build --target "${IOS_TRIPLES[${i}]}"
done
UNIVERSAL_BINARY=./${TARGETDIR}/ios/universal/${RELDIR}/${STATIC_LIB_NAME}
NEED_LIPO=
# if the universal binary doesnt exist, or if it's older than the static libs,
# we need to run `lipo` again.
if [[ ! -f "${UNIVERSAL_BINARY}" ]]; then
NEED_LIPO=1
elif [[ "$(stat -f "%m" "./${TARGETDIR}/x86_64-apple-ios/${RELDIR}/${STATIC_LIB_NAME}")" -gt "$(stat -f "%m" "${UNIVERSAL_BINARY}")" ]]; then
NEED_LIPO=1
elif [[ "$(stat -f "%m" "./${TARGETDIR}/aarch64-apple-ios/${RELDIR}/${STATIC_LIB_NAME}")" -gt "$(stat -f "%m" "${UNIVERSAL_BINARY}")" ]]; then
NEED_LIPO=1
fi
if [[ "${NEED_LIPO}" = "1" ]]; then
mkdir -p "${TARGETDIR}/ios/universal/${RELDIR}"
lipo -create -output "${UNIVERSAL_BINARY}" \
"${TARGETDIR}/x86_64-apple-ios/${RELDIR}/${STATIC_LIB_NAME}" \
"${TARGETDIR}/aarch64-apple-ios/${RELDIR}/${STATIC_LIB_NAME}"
fi
}
## rust android
build_android() {
build_kotlin
# If ANDROID_NDK_HOME is not set then set it to github actions default
[ -z "$ANDROID_NDK_HOME" ] && export ANDROID_NDK_HOME=$ANDROID_HOME/ndk-bundle
# Update this line accordingly if you are not building *from* darwin-x86_64 or linux-x86_64
export PATH=$PATH:$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/`uname | tr '[:upper:]' '[:lower:]'`-x86_64/bin
# Required for 'ring' dependency to cross-compile to Android platform, must be at least 21
export CFLAGS="-D__ANDROID_API__=21"
# IMPORTANT: make sure every target is not a substring of a different one. We check for them with grep later on
BUILD_TARGETS="${BUILD_TARGETS:-aarch64,x86_64,i686}"
mkdir -p bindings/bdk-kotlin/android/src/main/jniLibs/ bindings/bdk-kotlin/android/src/main/jniLibs/arm64-v8a bindings/bdk-kotlin/android/src/main/jniLibs/x86_64 bindings/bdk-kotlin/android/src/main/jniLibs/x86
if echo $BUILD_TARGETS | grep "aarch64"; then
CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="aarch64-linux-android21-clang" CC="aarch64-linux-android21-clang" cargo build --target=aarch64-linux-android
cp target/aarch64-linux-android/debug/libbdkffi.so bindings/bdk-kotlin/android/src/main/jniLibs/arm64-v8a
fi
if echo $BUILD_TARGETS | grep "x86_64"; then
CARGO_TARGET_X86_64_LINUX_ANDROID_LINKER="x86_64-linux-android21-clang" CC="x86_64-linux-android21-clang" cargo build --target=x86_64-linux-android
cp target/x86_64-linux-android/debug/libbdkffi.so bindings/bdk-kotlin/android/src/main/jniLibs/x86_64
fi
if echo $BUILD_TARGETS | grep "i686"; then
CARGO_TARGET_I686_LINUX_ANDROID_LINKER="i686-linux-android21-clang" CC="i686-linux-android21-clang" cargo build --target=i686-linux-android
cp target/i686-linux-android/debug/libbdkffi.so bindings/bdk-kotlin/android/src/main/jniLibs/x86
fi
# copy sources
cp -R bindings/bdk-kotlin/jvm/src/main/kotlin bindings/bdk-kotlin/android/src/main
# bdk-kotlin aar
(cd bindings/bdk-kotlin && ./gradlew :android:build)
}
OS=$(uname)
if [ "$1" == "-h" ]
then
help
else
build_rust
while [ -n "$1" ]; do # while loop starts
case "$1" in
-a) build_android ;;
-k) build_kotlin ;;
-s) build_swift ;;
-h) help ;;
*) echo "Option $1 not recognized" ;;
esac
shift
done
fi

View File

@@ -1,6 +1,6 @@
namespace bdk {
[Throws=BdkError]
ExtendedKeyInfo generate_extended_key(Network network, MnemonicType mnemonic_type, string? password);
ExtendedKeyInfo generate_extended_key(Network network, WordCount word_count, string? password);
[Throws=BdkError]
ExtendedKeyInfo restore_extended_key(Network network, string mnemonic, string? password);
};
@@ -46,6 +46,7 @@ enum BdkError {
"Electrum",
"Esplora",
"Sled",
"Rusqlite",
};
enum Network {
@@ -60,20 +61,25 @@ dictionary SledDbConfiguration {
string tree_name;
};
dictionary SqliteDbConfiguration {
string path;
};
[Enum]
interface DatabaseConfig {
Memory(string junk);
Memory();
Sled(SledDbConfiguration config);
Sqlite(SqliteDbConfiguration config);
};
dictionary TransactionDetails {
u64? fees;
u64? fee;
u64 received;
u64 sent;
string id;
string txid;
};
dictionary Confirmation {
dictionary BlockTime {
u32 height;
u64 timestamp;
};
@@ -81,22 +87,7 @@ dictionary Confirmation {
[Enum]
interface Transaction {
Unconfirmed(TransactionDetails details);
Confirmed(TransactionDetails details, Confirmation confirmation);
};
interface OfflineWallet {
[Throws=BdkError]
constructor(string descriptor, Network network, DatabaseConfig database_config);
// OfflineWalletOperations
string get_new_address();
string get_last_unused_address();
[Throws=BdkError]
u64 get_balance();
[Throws=BdkError]
void sign([ByRef] PartiallySignedBitcoinTransaction psbt);
[Throws=BdkError]
sequence<Transaction> get_transactions();
Confirmed(TransactionDetails details, BlockTime confirmation);
};
dictionary ElectrumConfig {
@@ -110,9 +101,9 @@ dictionary ElectrumConfig {
dictionary EsploraConfig {
string base_url;
string? proxy;
u64 timeout_read;
u64 timeout_write;
u8? concurrency;
u64 stop_gap;
u64? timeout;
};
[Enum]
@@ -121,15 +112,20 @@ interface BlockchainConfig {
Esplora(EsploraConfig config);
};
callback interface BdkProgress {
interface Blockchain {
[Throws=BdkError]
constructor(BlockchainConfig config);
[Throws=BdkError]
void broadcast([ByRef] PartiallySignedBitcoinTransaction psbt);
};
callback interface Progress {
void update(f32 progress, string? message);
};
interface OnlineWallet {
interface Wallet {
[Throws=BdkError]
constructor(string descriptor, string? change_descriptor, Network network, DatabaseConfig database_config, BlockchainConfig blockchain_config);
// OfflineWalletOperations
constructor(string descriptor, string? change_descriptor, Network network, DatabaseConfig database_config);
string get_new_address();
string get_last_unused_address();
[Throws=BdkError]
@@ -138,18 +134,37 @@ interface OnlineWallet {
void sign([ByRef] PartiallySignedBitcoinTransaction psbt);
[Throws=BdkError]
sequence<Transaction> get_transactions();
// OnlineWalletInterface
Network get_network();
[Throws=BdkError]
void sync(BdkProgress progress_update, u32? max_address_param);
[Throws=BdkError]
Transaction broadcast([ByRef] PartiallySignedBitcoinTransaction psbt);
void sync([ByRef] Blockchain blockchain, Progress? progress);
};
interface PartiallySignedBitcoinTransaction {
[Throws=BdkError]
constructor([ByRef] OnlineWallet wallet, string recipient, u64 amount, float? fee_rate);
constructor(string psbt_base64);
string serialize();
string txid();
};
interface TxBuilder {
constructor();
TxBuilder add_recipient(string address, u64 amount);
TxBuilder fee_rate(float sat_per_vbyte);
TxBuilder drain_wallet();
TxBuilder drain_to(string address);
TxBuilder enable_rbf();
TxBuilder enable_rbf_with_sequence(u32 nsequence);
[Throws=BdkError]
PartiallySignedBitcoinTransaction finish([ByRef] Wallet wallet);
};
interface BumpFeeTxBuilder {
constructor(string txid, float new_fee_rate);
BumpFeeTxBuilder allow_shrinking(string address);
BumpFeeTxBuilder enable_rbf();
BumpFeeTxBuilder enable_rbf_with_sequence(u32 nsequence);
[Throws=BdkError]
PartiallySignedBitcoinTransaction finish([ByRef] Wallet wallet);
};
dictionary ExtendedKeyInfo {
@@ -158,7 +173,7 @@ dictionary ExtendedKeyInfo {
string fingerprint;
};
enum MnemonicType {
enum WordCount {
"Words12",
"Words15",
"Words18",

View File

@@ -1,29 +1,35 @@
use bdk::bitcoin::hashes::hex::ToHex;
use bdk::bitcoin::secp256k1::Secp256k1;
use bdk::bitcoin::util::psbt::PartiallySignedTransaction;
use bdk::bitcoin::{Address, Network};
use bdk::bitcoin::{Address, Network, Script, Txid};
use bdk::blockchain::any::{AnyBlockchain, AnyBlockchainConfig};
use bdk::blockchain::Progress;
use bdk::blockchain::{
electrum::ElectrumBlockchainConfig, esplora::EsploraBlockchainConfig, ConfigurableBlockchain,
};
use bdk::database::any::{AnyDatabase, SledDbConfiguration};
use bdk::blockchain::{Blockchain as BdkBlockchain, Progress as BdkProgress};
use bdk::database::any::{AnyDatabase, SledDbConfiguration, SqliteDbConfiguration};
use bdk::database::{AnyDatabaseConfig, ConfigurableDatabase};
use bdk::keys::bip39::{Language, Mnemonic, MnemonicType};
use bdk::keys::bip39::{Language, Mnemonic, WordCount};
use bdk::keys::{DerivableKey, ExtendedKey, GeneratableKey, GeneratedKey};
use bdk::miniscript::BareCtx;
use bdk::wallet::AddressIndex;
use bdk::{ConfirmationTime, Error, FeeRate, SignOptions, Wallet};
use bdk::{
BlockTime, Error, FeeRate, SignOptions, SyncOptions as BdkSyncOptions, Wallet as BdkWallet,
};
use std::convert::TryFrom;
use std::fmt;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::{Mutex, MutexGuard};
use std::sync::{Arc, Mutex, MutexGuard};
uniffi_macros::include_scaffolding!("bdk");
type BdkError = Error;
pub enum DatabaseConfig {
Memory { junk: String },
Memory,
Sled { config: SledDbConfiguration },
Sqlite { config: SqliteDbConfiguration },
}
pub struct ElectrumConfig {
@@ -37,9 +43,9 @@ pub struct ElectrumConfig {
pub struct EsploraConfig {
pub base_url: String,
pub proxy: Option<String>,
pub timeout_read: u64,
pub timeout_write: u64,
pub concurrency: Option<u8>,
pub stop_gap: u64,
pub timeout: Option<u64>,
}
pub enum BlockchainConfig {
@@ -47,30 +53,14 @@ pub enum BlockchainConfig {
Esplora { config: EsploraConfig },
}
trait WalletHolder<B> {
fn get_wallet(&self) -> MutexGuard<Wallet<B, AnyDatabase>>;
}
struct OfflineWallet {
wallet: Mutex<Wallet<(), AnyDatabase>>,
}
impl WalletHolder<()> for OfflineWallet {
fn get_wallet(&self) -> MutexGuard<Wallet<(), AnyDatabase>> {
self.wallet.lock().unwrap()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TransactionDetails {
pub fees: Option<u64>,
pub fee: Option<u64>,
pub received: u64,
pub sent: u64,
pub id: String,
pub txid: String,
}
type Confirmation = ConfirmationTime;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Transaction {
Unconfirmed {
@@ -78,15 +68,15 @@ pub enum Transaction {
},
Confirmed {
details: TransactionDetails,
confirmation: Confirmation,
confirmation: BlockTime,
},
}
impl From<&bdk::TransactionDetails> for TransactionDetails {
fn from(x: &bdk::TransactionDetails) -> TransactionDetails {
TransactionDetails {
fees: x.fee,
id: x.txid.to_string(),
fee: x.fee,
txid: x.txid.to_string(),
received: x.received,
sent: x.sent,
}
@@ -96,9 +86,9 @@ impl From<&bdk::TransactionDetails> for TransactionDetails {
impl From<&bdk::TransactionDetails> for Transaction {
fn from(x: &bdk::TransactionDetails) -> Transaction {
match x.confirmation_time.clone() {
Some(confirmation) => Transaction::Confirmed {
Some(block_time) => Transaction::Confirmed {
details: TransactionDetails::from(x),
confirmation,
confirmation: block_time,
},
None => Transaction::Unconfirmed {
details: TransactionDetails::from(x),
@@ -107,7 +97,144 @@ impl From<&bdk::TransactionDetails> for Transaction {
}
}
trait OfflineWalletOperations<B>: WalletHolder<B> {
struct Blockchain {
blockchain_mutex: Mutex<AnyBlockchain>,
}
impl Blockchain {
fn new(blockchain_config: BlockchainConfig) -> Result<Self, BdkError> {
let any_blockchain_config = match blockchain_config {
BlockchainConfig::Electrum { config } => {
AnyBlockchainConfig::Electrum(ElectrumBlockchainConfig {
retry: config.retry,
socks5: config.socks5,
timeout: config.timeout,
url: config.url,
stop_gap: usize::try_from(config.stop_gap).unwrap(),
})
}
BlockchainConfig::Esplora { config } => {
AnyBlockchainConfig::Esplora(EsploraBlockchainConfig {
base_url: config.base_url,
proxy: config.proxy,
concurrency: config.concurrency,
stop_gap: usize::try_from(config.stop_gap).unwrap(),
timeout: config.timeout,
})
}
};
let blockchain = AnyBlockchain::from_config(&any_blockchain_config)?;
Ok(Self {
blockchain_mutex: Mutex::new(blockchain),
})
}
fn get_blockchain(&self) -> MutexGuard<AnyBlockchain> {
self.blockchain_mutex.lock().expect("blockchain")
}
fn broadcast(&self, psbt: &PartiallySignedBitcoinTransaction) -> Result<(), Error> {
let tx = psbt.internal.lock().unwrap().clone().extract_tx();
self.get_blockchain().broadcast(&tx)
}
}
struct Wallet {
wallet_mutex: Mutex<BdkWallet<AnyDatabase>>,
}
pub trait Progress: Send + Sync + 'static {
fn update(&self, progress: f32, message: Option<String>);
}
struct ProgressHolder {
progress: Box<dyn Progress>,
}
impl BdkProgress for ProgressHolder {
fn update(&self, progress: f32, message: Option<String>) -> Result<(), Error> {
self.progress.update(progress, message);
Ok(())
}
}
impl fmt::Debug for ProgressHolder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProgressHolder").finish_non_exhaustive()
}
}
#[derive(Debug)]
struct PartiallySignedBitcoinTransaction {
internal: Mutex<PartiallySignedTransaction>,
}
impl PartiallySignedBitcoinTransaction {
fn new(psbt_base64: String) -> Result<Self, Error> {
let psbt: PartiallySignedTransaction = PartiallySignedTransaction::from_str(&psbt_base64)?;
Ok(PartiallySignedBitcoinTransaction {
internal: Mutex::new(psbt),
})
}
fn serialize(&self) -> String {
let psbt = self.internal.lock().unwrap().clone();
psbt.to_string()
}
fn txid(&self) -> String {
let tx = self.internal.lock().unwrap().clone().extract_tx();
let txid = tx.txid();
txid.to_hex()
}
}
impl Wallet {
fn new(
descriptor: String,
change_descriptor: Option<String>,
network: Network,
database_config: DatabaseConfig,
) -> Result<Self, BdkError> {
let any_database_config = match database_config {
DatabaseConfig::Memory => AnyDatabaseConfig::Memory(()),
DatabaseConfig::Sled { config } => AnyDatabaseConfig::Sled(config),
DatabaseConfig::Sqlite { config } => AnyDatabaseConfig::Sqlite(config),
};
let database = AnyDatabase::from_config(&any_database_config)?;
let wallet_mutex = Mutex::new(BdkWallet::new(
&descriptor,
change_descriptor.as_ref(),
network,
database,
)?);
Ok(Wallet { wallet_mutex })
}
fn get_wallet(&self) -> MutexGuard<BdkWallet<AnyDatabase>> {
self.wallet_mutex.lock().expect("wallet")
}
fn get_network(&self) -> Network {
self.get_wallet().network()
}
fn sync(
&self,
blockchain: &Blockchain,
progress: Option<Box<dyn Progress>>,
) -> Result<(), BdkError> {
let bdk_sync_opts = BdkSyncOptions {
progress: progress.map(|p| {
Box::new(ProgressHolder { progress: p })
as Box<(dyn bdk::blockchain::Progress + 'static)>
}),
};
let blockchain = blockchain.get_blockchain();
self.get_wallet().sync(blockchain.deref(), bdk_sync_opts)
}
fn get_new_address(&self) -> String {
self.get_wallet()
.get_address(AddressIndex::New)
@@ -128,7 +255,7 @@ trait OfflineWalletOperations<B>: WalletHolder<B> {
self.get_wallet().get_balance()
}
fn sign<'a>(&self, psbt: &'a PartiallySignedBitcoinTransaction) -> Result<(), Error> {
fn sign(&self, psbt: &PartiallySignedBitcoinTransaction) -> Result<(), Error> {
let mut psbt = psbt.internal.lock().unwrap();
let finalized = self.get_wallet().sign(&mut psbt, SignOptions::default())?;
match finalized {
@@ -146,156 +273,6 @@ trait OfflineWalletOperations<B>: WalletHolder<B> {
}
}
impl OfflineWallet {
fn new(
descriptor: String,
network: Network,
database_config: DatabaseConfig,
) -> Result<Self, BdkError> {
let any_database_config = match database_config {
DatabaseConfig::Memory { .. } => AnyDatabaseConfig::Memory(()),
DatabaseConfig::Sled { config } => AnyDatabaseConfig::Sled(config),
};
let database = AnyDatabase::from_config(&any_database_config)?;
let wallet = Mutex::new(Wallet::new_offline(&descriptor, None, network, database)?);
Ok(OfflineWallet { wallet })
}
}
impl OfflineWalletOperations<()> for OfflineWallet {}
struct OnlineWallet {
wallet: Mutex<Wallet<AnyBlockchain, AnyDatabase>>,
}
pub trait BdkProgress: Send + Sync {
fn update(&self, progress: f32, message: Option<String>);
}
struct BdkProgressHolder {
progress_update: Box<dyn BdkProgress>,
}
impl Progress for BdkProgressHolder {
fn update(&self, progress: f32, message: Option<String>) -> Result<(), Error> {
self.progress_update.update(progress, message);
Ok(())
}
}
struct PartiallySignedBitcoinTransaction {
internal: Mutex<PartiallySignedTransaction>,
details: bdk::TransactionDetails,
}
impl PartiallySignedBitcoinTransaction {
fn new(
online_wallet: &OnlineWallet,
recipient: String,
amount: u64,
fee_rate: Option<f32>, // satoshis per vbyte
) -> Result<Self, Error> {
let wallet = online_wallet.get_wallet();
match Address::from_str(&recipient) {
Ok(address) => {
let (psbt, details) = {
let mut builder = wallet.build_tx();
builder.add_recipient(address.script_pubkey(), amount);
if let Some(sat_per_vb) = fee_rate {
builder.fee_rate(FeeRate::from_sat_per_vb(sat_per_vb));
}
builder.finish()?
};
Ok(PartiallySignedBitcoinTransaction {
internal: Mutex::new(psbt),
details,
})
}
Err(..) => Err(BdkError::Generic(
"failed to read wallet address".to_string(),
)),
}
}
}
impl OnlineWallet {
fn new(
descriptor: String,
change_descriptor: Option<String>,
network: Network,
database_config: DatabaseConfig,
blockchain_config: BlockchainConfig,
) -> Result<Self, BdkError> {
let any_database_config = match database_config {
DatabaseConfig::Memory { .. } => AnyDatabaseConfig::Memory(()),
DatabaseConfig::Sled { config } => AnyDatabaseConfig::Sled(config),
};
let any_blockchain_config = match blockchain_config {
BlockchainConfig::Electrum { config } => {
AnyBlockchainConfig::Electrum(ElectrumBlockchainConfig {
retry: config.retry,
socks5: config.socks5,
timeout: config.timeout,
url: config.url,
stop_gap: usize::try_from(config.stop_gap).unwrap(),
})
}
BlockchainConfig::Esplora { config } => {
AnyBlockchainConfig::Esplora(EsploraBlockchainConfig {
base_url: config.base_url,
proxy: config.proxy,
timeout_read: config.timeout_read,
timeout_write: config.timeout_write,
stop_gap: usize::try_from(config.stop_gap).unwrap(),
})
}
};
let database = AnyDatabase::from_config(&any_database_config)?;
let blockchain = AnyBlockchain::from_config(&any_blockchain_config)?;
let wallet = Mutex::new(Wallet::new(
&descriptor,
change_descriptor.to_owned().as_ref(),
network,
database,
blockchain,
)?);
Ok(OnlineWallet { wallet })
}
fn get_network(&self) -> Network {
self.wallet.lock().unwrap().network()
}
fn sync(
&self,
progress_update: Box<dyn BdkProgress>,
max_address_param: Option<u32>,
) -> Result<(), BdkError> {
progress_update.update(21.0, Some("message".to_string()));
self.wallet
.lock()
.unwrap()
.sync(BdkProgressHolder { progress_update }, max_address_param)
}
fn broadcast<'a>(
&self,
psbt: &'a PartiallySignedBitcoinTransaction,
) -> Result<Transaction, Error> {
let tx = psbt.internal.lock().unwrap().clone().extract_tx();
self.get_wallet().broadcast(tx)?;
Ok(Transaction::from(&psbt.details))
}
}
impl WalletHolder<AnyBlockchain> for OnlineWallet {
fn get_wallet(&self) -> MutexGuard<Wallet<AnyBlockchain, AnyDatabase>> {
self.wallet.lock().unwrap()
}
}
impl OfflineWalletOperations<AnyBlockchain> for OnlineWallet {}
pub struct ExtendedKeyInfo {
mnemonic: String,
xprv: String,
@@ -304,11 +281,11 @@ pub struct ExtendedKeyInfo {
fn generate_extended_key(
network: Network,
mnemonic_type: MnemonicType,
word_count: WordCount,
password: Option<String>,
) -> Result<ExtendedKeyInfo, Error> {
let mnemonic: GeneratedKey<_, BareCtx> =
Mnemonic::generate((mnemonic_type, Language::English)).unwrap();
Mnemonic::generate((word_count, Language::English)).unwrap();
let mnemonic = mnemonic.into_key();
let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?;
let xprv = xkey.into_xprv(network).unwrap();
@@ -325,7 +302,7 @@ fn restore_extended_key(
mnemonic: String,
password: Option<String>,
) -> Result<ExtendedKeyInfo, Error> {
let mnemonic = Mnemonic::from_phrase(mnemonic.as_ref(), Language::English).unwrap();
let mnemonic = Mnemonic::parse_in(Language::English, mnemonic).unwrap();
let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?;
let xprv = xkey.into_xprv(network).unwrap();
let fingerprint = xprv.fingerprint(&Secp256k1::new());
@@ -336,5 +313,205 @@ fn restore_extended_key(
})
}
uniffi::deps::static_assertions::assert_impl_all!(OfflineWallet: Sync, Send);
uniffi::deps::static_assertions::assert_impl_all!(OnlineWallet: Sync, Send);
fn to_script_pubkey(address: &str) -> Result<Script, BdkError> {
Address::from_str(address)
.map(|x| x.script_pubkey())
.map_err(|e| BdkError::Generic(e.to_string()))
}
#[derive(Clone)]
enum RbfValue {
Default,
Value(u32),
}
struct TxBuilder {
recipients: Vec<(String, u64)>,
fee_rate: Option<f32>,
drain_wallet: bool,
drain_to: Option<String>,
rbf: Option<RbfValue>,
}
impl TxBuilder {
fn new() -> Self {
TxBuilder {
recipients: Vec::new(),
fee_rate: None,
drain_wallet: false,
drain_to: None,
rbf: None,
}
}
fn add_recipient(&self, recipient: String, amount: u64) -> Arc<Self> {
let mut recipients = self.recipients.to_vec();
recipients.append(&mut vec![(recipient, amount)]);
Arc::new(TxBuilder {
recipients,
fee_rate: self.fee_rate,
drain_wallet: self.drain_wallet,
drain_to: self.drain_to.clone(),
rbf: self.rbf.clone(),
})
}
fn fee_rate(&self, sat_per_vb: f32) -> Arc<Self> {
Arc::new(TxBuilder {
recipients: self.recipients.to_vec(),
fee_rate: Some(sat_per_vb),
drain_wallet: self.drain_wallet,
drain_to: self.drain_to.clone(),
rbf: self.rbf.clone(),
})
}
fn drain_wallet(&self) -> Arc<Self> {
Arc::new(TxBuilder {
recipients: self.recipients.to_vec(),
fee_rate: self.fee_rate,
drain_wallet: true,
drain_to: self.drain_to.clone(),
rbf: self.rbf.clone(),
})
}
fn drain_to(&self, address: String) -> Arc<Self> {
Arc::new(TxBuilder {
recipients: self.recipients.to_vec(),
fee_rate: self.fee_rate,
drain_wallet: self.drain_wallet,
drain_to: Some(address),
rbf: self.rbf.clone(),
})
}
fn enable_rbf(&self) -> Arc<Self> {
Arc::new(TxBuilder {
recipients: self.recipients.to_vec(),
fee_rate: self.fee_rate,
drain_wallet: self.drain_wallet,
drain_to: self.drain_to.clone(),
rbf: Some(RbfValue::Default),
})
}
fn enable_rbf_with_sequence(&self, nsequence: u32) -> Arc<Self> {
Arc::new(TxBuilder {
recipients: self.recipients.to_vec(),
fee_rate: self.fee_rate,
drain_wallet: self.drain_wallet,
drain_to: self.drain_to.clone(),
rbf: Some(RbfValue::Value(nsequence)),
})
}
fn finish(&self, wallet: &Wallet) -> Result<Arc<PartiallySignedBitcoinTransaction>, Error> {
let wallet = wallet.get_wallet();
let mut tx_builder = wallet.build_tx();
for (address, amount) in &self.recipients {
tx_builder.add_recipient(to_script_pubkey(address)?, *amount);
}
if let Some(sat_per_vb) = self.fee_rate {
tx_builder.fee_rate(FeeRate::from_sat_per_vb(sat_per_vb));
}
if self.drain_wallet {
tx_builder.drain_wallet();
}
if let Some(address) = &self.drain_to {
tx_builder.drain_to(to_script_pubkey(address)?);
}
if let Some(rbf) = &self.rbf {
match *rbf {
RbfValue::Default => {
tx_builder.enable_rbf();
}
RbfValue::Value(nsequence) => {
tx_builder.enable_rbf_with_sequence(nsequence);
}
}
}
tx_builder
.finish()
.map(|(psbt, _)| PartiallySignedBitcoinTransaction {
internal: Mutex::new(psbt),
})
.map(Arc::new)
}
}
struct BumpFeeTxBuilder {
txid: String,
fee_rate: f32,
allow_shrinking: Option<String>,
rbf: Option<RbfValue>,
}
impl BumpFeeTxBuilder {
fn new(txid: String, fee_rate: f32) -> Self {
Self {
txid,
fee_rate,
allow_shrinking: None,
rbf: None,
}
}
fn allow_shrinking(&self, address: String) -> Arc<Self> {
Arc::new(Self {
txid: self.txid.clone(),
fee_rate: self.fee_rate,
allow_shrinking: Some(address),
rbf: self.rbf.clone(),
})
}
fn enable_rbf(&self) -> Arc<Self> {
Arc::new(Self {
txid: self.txid.clone(),
fee_rate: self.fee_rate,
allow_shrinking: self.allow_shrinking.clone(),
rbf: Some(RbfValue::Default),
})
}
fn enable_rbf_with_sequence(&self, nsequence: u32) -> Arc<Self> {
Arc::new(Self {
txid: self.txid.clone(),
fee_rate: self.fee_rate,
allow_shrinking: self.allow_shrinking.clone(),
rbf: Some(RbfValue::Value(nsequence)),
})
}
fn finish(&self, wallet: &Wallet) -> Result<Arc<PartiallySignedBitcoinTransaction>, Error> {
let wallet = wallet.get_wallet();
let txid = Txid::from_str(self.txid.as_str())?;
let mut tx_builder = wallet.build_fee_bump(txid)?;
tx_builder.fee_rate(FeeRate::from_sat_per_vb(self.fee_rate));
if let Some(allow_shrinking) = &self.allow_shrinking {
let address =
Address::from_str(allow_shrinking).map_err(|e| Error::Generic(e.to_string()))?;
let script = address.script_pubkey();
tx_builder.allow_shrinking(script)?;
}
if let Some(rbf) = &self.rbf {
match *rbf {
RbfValue::Default => {
tx_builder.enable_rbf();
}
RbfValue::Value(nsequence) => {
tx_builder.enable_rbf_with_sequence(nsequence);
}
}
}
tx_builder
.finish()
.map(|(psbt, _)| PartiallySignedBitcoinTransaction {
internal: Mutex::new(psbt),
})
.map(Arc::new)
}
}
uniffi::deps::static_assertions::assert_impl_all!(Wallet: Sync, Send);

44
test.sh
View File

@@ -1,44 +0,0 @@
#!/usr/bin/env bash
set -eo pipefail
# functions
## help
help()
{
# Display Help
echo "Test bdk-uniffi and related libraries."
echo
echo "Syntax: build [-a|h|k]"
echo "options:"
echo "-a Android connected device tests."
echo "-h Print this Help."
echo "-k Kotlin tests."
echo
}
test_kotlin() {
(cd bindings/bdk-kotlin && ./gradlew :jvm:test -Djna.debug_load=true)
}
test_android() {
(cd bindings/bdk-kotlin && ./gradlew :android:connectedDebugAndroidTest)
}
if [ $1 = "-h" ]
then
help
else
cargo test
# optional tests
while [ -n "$1" ]; do # while loop starts
case "$1" in
-a) test_android ;;
-h) help ;;
-k) test_kotlin ;;
*) echo "Option $1 not recognized" ;;
esac
shift
done
fi