Compare commits

..

2 Commits

Author SHA1 Message Date
thunderbiscuit
77463fa629 chore: add bdk team author and email to libraries 2023-11-20 12:19:27 -05:00
thunderbiscuit
9df6f6dbc1 chore: update libraries to official release versions 2023-11-20 10:37:47 -05:00
50 changed files with 1497 additions and 2463 deletions

View File

@@ -1,7 +1,7 @@
---
name: Release
about: Create a new release [for release managers only]
title: 'Release MAJOR.MINOR.PATCH'
name: Minor Release
about: Create a new minor release [for release managers only]
title: 'Release MAJOR.MINOR+1.0'
labels: 'release'
assignees: ''
---
@@ -16,8 +16,6 @@ assignees: ''
3. - [ ] Update the API docs to reflect the changes in the API
4. - [ ] Delete the `target` directory in bdk-ffi and all previous artifacts to make sure you're building the library from scratch.
5. - [ ] Build the library and run the tests, and adjust if necessary.
1. - [ ] Delete the `target` directory in bdk-ffi and all `build` directories (in root, `lib`, and `plugins`) in bdk-android directory to make sure you're building the library from scratch.
2. - [ ] Build the library and run the offline and live tests, and adjust them if necessary (note that you'll need an Android emulator running).
```shell
# start an emulator prior to running the tests
cd ./bdk-android/
@@ -25,32 +23,26 @@ cd ./bdk-android/
./gradlew connectedAndroidTest
```
6. - [ ] Update the readme if necessary
1. - [ ] Update the readme if necessary
#### _JVM_
7. - [ ] Update the API docs to reflect the changes in the API
8. - [ ] Delete the `target` directory in bdk-ffi and all previous artifacts to make sure you're building the library from scratch
9. - [ ] Build the library and run the tests, and adjust if necessary
2. - [ ] Delete the `target` directory in bdk-ffi and all `build` directories (in root, `lib`, and `plugins`) in bdk-android directory to make sure you're building the library from scratch.
3. - [ ] Build the library and run the tests, and adjust if necessary
```shell
cd ./bdk-jvm/
./gradlew buildJvmLib
./gradlew test
```
10. - [ ] Update the readme if necessary
1. - [ ] Update the readme if necessary
#### _Swift_
11. - [ ] Run the tests and adjust if necessary
1. - [ ] Run the tests and adjust if necessary
```shell
./bdk-swift/build-local-swift.sh
cd ./bdk-swift/
swift test
```
12. - [ ] Update the readme if necessary
1. - [ ] Update the readme if necessary
#### _Python_
13. - [ ] Delete the `dist`, `build`, and `bdkpython.egg-info` and rust `target` directories to make sure you are building the library from scratch without any caches
13. - [ ] Delete the `.tox`, `dist`, `build`, and `bdkpython.egg-info` and rust `target` directories to make sure you are building the library from scratch without any caches
14. - [ ] Build the library
```shell
cd ./bdk-python/
@@ -58,12 +50,12 @@ pip3 install --requirement requirements.txt
bash ./scripts/generate-macos-arm64.sh # run the script for your particular platform
python3 setup.py --verbose bdist_wheel
```
1. - [ ] Run the tests and adjust if necessary
15. - [ ] Run the tests and adjust if necessary
```shell
pip3 install ./dist/bdkpython-<yourversion>-py3-none-any.whl --force-reinstall
python -m unittest --verbose
python -m unittest --verbose tests/test_bdk.py
```
1. - [ ] Update the readme and `setup.py` if necessary
16. - [ ] Update the readme and `setup.py` if necessary
### Release Workflow
17. - [ ] Update the Android, JVM, Python, and Swift libraries as per the _Specific Libraries' Workflows_ section above. Open a single PR on master for all of these changes called `Prepare language bindings libraries for 0.X release`. See [example PR here](https://github.com/bitcoindevkit/bdk-ffi/pull/315).
@@ -85,5 +77,11 @@ git push upstream v0.6.0
29. - [ ] Apply changes to the minor_release and patch_release issue templates if they need any
30. - [ ] Open a PR on master with the changes in steps 29, 30, and 31. See [example PR here](https://github.com/bitcoindevkit/bdk-ffi/pull/317). Get a review and merge the PR.
31. - [ ] Make release on GitHub (set as pre-release and generate auto release notes between the previous tag and the new one)
32. - [ ] Post in the announcement channel
33. - [ ] Tweet about the library
32. - [ ] Build and publish API docs for JVM, Android, and Java on the website
```shell
./gradlew dokkaHtml # bdk-jvm (Dokka)
./gradlew dokkaJavadoc # bdk-jvm (java-style documentation)
./gradlew dokkaHtml # bdk-android (Dokka)
```
33. - [ ] Post in the announcement channel
34. - [ ] Tweet about the library

View File

@@ -56,7 +56,7 @@ jobs:
run: cargo clippy --all-targets --features "uniffi/bindgen-tests" -- -D warnings
- name: "Test"
run: CLASSPATH=./tests/jna/jna-5.14.0.jar cargo test --features uniffi/bindgen-tests
run: CLASSPATH=./tests/jna/jna-5.8.0.jar cargo test --features uniffi/bindgen-tests
fmt:
name: "Rust fmt"

View File

@@ -1,27 +1,8 @@
# Changelog
Changelog information can also be found in each release's git tag (which can be viewed with `git tag -ln100 "v*"`), as well as on the [GitHub releases](https://github.com/bitcoindevkit/bdk-ffi/releases) page. See [DEVELOPMENT_CYCLE.md](DEVELOPMENT_CYCLE.md) for more details.
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).
## [1.0.0-alpha.2a]
This release is the first alpha release of the 1.0 API for the bindings libraries. Here is what is now available:
- Create and recover wallets using descriptors, including the four descriptor templates
- Sync a wallet using a blocking Esplora client
- Query the wallet for balance and addresses
- Create and sign transactions using the transaction builder
- Broadcast transactions
## [0.31.0]
This release updates the bindings libraries to bdk version 0.29.0, updating rust-bitcoin to version 0.30.2.
- APIs Changed:
- `BumpFeeTxBuilder.allow_shrinking()` now takes a `Script` as its argument [#443]
- The `Address` constructor now takes a `Network` argument [#443]
- The `Payload::PubkeyHash` and `Payload::ScriptHash` now have string arguments instead of byte arrays [#443]
- APIs Added:
- The `Address` type now has the `is_valid_for_network()` method [#443]
[#443]: https://github.com/bitcoindevkit/bdk-ffi/pull/443
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).
## [0.30.0]
This release has a new API and a few internal optimizations and refactorings.
@@ -242,7 +223,6 @@ Changelog
[BIP 0174]:https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#encoding
[v0.31.0]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.30.0...v0.31.0
[v0.30.0]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.29.0...v0.30.0
[v0.29.0]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.28.0...v0.29.0
[v0.28.0]: https://github.com/bitcoindevkit/bdk-ffi/compare/v0.27.1...v0.28.0

View File

@@ -8,7 +8,7 @@
</p>
## 🚨 Warning 🚨
The `master` branch of this repository is being migrated to the [bdk 1.0 API](https://github.com/bitcoindevkit/bdk) and is incomplete. For production-ready libraries, use the [`0.31.X`](https://github.com/bitcoindevkit/bdk-ffi/tree/release/0.30) releases.
The `master` branch of this repository is being migrated to the [bdk 1.0 API](https://github.com/bitcoindevkit/bdk) and is incomplete. For production-ready libraries, use the [`0.30.X`](https://github.com/bitcoindevkit/bdk-ffi/tree/release/0.30) releases.
## Readme
The workspace in this repository creates the `libbdkffi` multi-language library for the Rust-based

View File

@@ -22,21 +22,12 @@ import org.bitcoindevkit.*
val externalDescriptor = Descriptor("wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)", Network.TESTNET)
val internalDescriptor = Descriptor("wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/1/*)", Network.TESTNET)
val esploraClient: EsploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
val wallet: Wallet = Wallet(
descriptor = externalDescriptor,
changeDescriptor = internalDescriptor,
persistenceBackendPath = "./bdkwallet.db",
network = Network.TESTNET
)
val update = esploraClient.fullScan(
wallet = wallet,
stopGap = 10uL,
parallelRequests = 1uL
)
wallet.applyUpdate(update)
val databaseConfig = DatabaseConfig.Memory
val blockchainConfig = BlockchainConfig.Electrum(
ElectrumConfig("ssl://electrum.blockstream.info:60002", null, 5u, null, 10u, true)
)
val wallet = Wallet(externalDescriptor, internalDescriptor, Network.TESTNET, databaseConfig, blockchainConfig)
val newAddress = wallet.getAddress(AddressIndex.LastUnused)
```
@@ -87,7 +78,7 @@ export ANDROID_NDK_ROOT=$ANDROID_SDK_ROOT/ndk/25.2.9519653
cd bdk-android
./gradlew buildAndroidLib
```
1. Start android emulator and run tests
8. Start android emulator (must be x86_64) and run tests
```sh
./gradlew connectedAndroidTest
```

View File

@@ -2,4 +2,4 @@ org.gradle.jvmargs=-Xmx1536m
android.useAndroidX=true
android.enableJetifier=true
kotlin.code.style=official
libraryVersion=1.0.0-alpha.7
libraryVersion=1.0.0-alpha.2-rc1

View File

@@ -19,11 +19,11 @@ repositories {
}
android {
compileSdk = 33
compileSdk = 31
defaultConfig {
minSdk = 21
targetSdk = 33
targetSdk = 31
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")
}
@@ -44,7 +44,7 @@ android {
}
dependencies {
implementation("net.java.dev.jna:jna:5.14.0@aar")
implementation("net.java.dev.jna:jna:5.8.0@aar")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7")
implementation("androidx.appcompat:appcompat:1.4.0")
implementation("androidx.core:core-ktx:1.7.0")

View File

@@ -1,74 +1,30 @@
package org.bitcoindevkit
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.runner.RunWith
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.assertTrue
@RunWith(AndroidJUnit4::class)
class LiveTxBuilderTest {
private val persistenceFilePath = InstrumentationRegistry
.getInstrumentation().targetContext.filesDir.path + "/bdk_persistence.db"
@AfterTest
fun cleanup() {
val file = File(persistenceFilePath)
if (file.exists()) {
file.delete()
}
}
@Test
fun testTxBuilder() {
val descriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)", Network.TESTNET)
val wallet = Wallet(descriptor, null, persistenceFilePath, Network.TESTNET)
val esploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
val update = esploraClient.fullScan(wallet, 10uL, 1uL)
val wallet = Wallet.newNoPersist(descriptor, null, Network.TESTNET)
val esploraClient = EsploraClient("https://mempool.space/testnet/api")
val update = esploraClient.scan(wallet, 10uL, 1uL)
wallet.applyUpdate(update)
println("Balance: ${wallet.getBalance().total}")
println("Balance: ${wallet.getBalance().total()}")
assert(wallet.getBalance().total > 0uL)
assert(wallet.getBalance().total() > 0uL)
val recipient: Address = Address("tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989", Network.TESTNET)
val psbt: PartiallySignedTransaction = TxBuilder()
.addRecipient(recipient.scriptPubkey(), 4200uL)
.feeRate(FeeRate.fromSatPerVb(2.0f))
.feeRate(2.0f)
.finish(wallet)
println(psbt.serialize())
assertTrue(psbt.serialize().startsWith("cHNi"), "PSBT should start with 'cHNi'")
}
@Test
fun complexTxBuilder() {
val externalDescriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)", Network.TESTNET)
val changeDescriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/1/*)", Network.TESTNET)
val wallet = Wallet(externalDescriptor, changeDescriptor, persistenceFilePath, Network.TESTNET)
val esploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
val update = esploraClient.fullScan(wallet, 10uL, 1uL)
wallet.applyUpdate(update)
println("Balance: ${wallet.getBalance().total}")
assert(wallet.getBalance().total > 0uL)
val recipient1: Address = Address("tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989", Network.TESTNET)
val recipient2: Address = Address("tb1qw2c3lxufxqe2x9s4rdzh65tpf4d7fssjgh8nv6", Network.TESTNET)
val allRecipients: List<ScriptAmount> = listOf(
ScriptAmount(recipient1.scriptPubkey(), 4200uL),
ScriptAmount(recipient2.scriptPubkey(), 4200uL),
)
val psbt: PartiallySignedTransaction = TxBuilder()
.setRecipients(allRecipients)
.feeRate(FeeRate.fromSatPerVb(4.0f))
.changePolicy(ChangeSpendPolicy.CHANGE_FORBIDDEN)
.enableRbf()
.finish(wallet)
wallet.sign(psbt)
assertTrue(psbt.serialize().startsWith("cHNi"), "PSBT should start with 'cHNi'")
}
}

View File

@@ -2,60 +2,38 @@ package org.bitcoindevkit
import org.junit.Test
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.runner.RunWith
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.assertTrue
@RunWith(AndroidJUnit4::class)
class LiveWalletTest {
private val persistenceFilePath = InstrumentationRegistry
.getInstrumentation().targetContext.filesDir.path + "/bdk_persistence.db"
@AfterTest
fun cleanup() {
val file = File(persistenceFilePath)
if (file.exists()) {
file.delete()
}
}
@Test
fun testSyncedBalance() {
val descriptor: Descriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)", Network.TESTNET)
val wallet: Wallet = Wallet(descriptor, null, persistenceFilePath, Network.TESTNET)
val esploraClient: EsploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
val update = esploraClient.fullScan(wallet, 10uL, 1uL)
val wallet: Wallet = Wallet.newNoPersist(descriptor, null, Network.TESTNET)
val esploraClient: EsploraClient = EsploraClient("https://mempool.space/testnet/api")
// val esploraClient = EsploraClient("https://blockstream.info/testnet/api")
val update = esploraClient.scan(wallet, 10uL, 1uL)
wallet.applyUpdate(update)
println("Balance: ${wallet.getBalance().total}")
println("Balance: ${wallet.getBalance().total()}")
val balance: Balance = wallet.getBalance()
println("Balance: $balance")
assert(wallet.getBalance().total > 0uL)
println("Transactions count: ${wallet.transactions().count()}")
val transactions = wallet.transactions().take(3)
for (tx in transactions) {
val sentAndReceived = wallet.sentAndReceived(tx)
println("Transaction: ${tx.txid()}")
println("Sent ${sentAndReceived.sent}")
println("Received ${sentAndReceived.received}")
}
assert(wallet.getBalance().total() > 0uL)
}
@Test
fun testBroadcastTransaction() {
val descriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)", Network.TESTNET)
val wallet = Wallet(descriptor, null, persistenceFilePath, Network.TESTNET)
val esploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
val update = esploraClient.fullScan(wallet, 10uL, 1uL)
val wallet = Wallet.newNoPersist(descriptor, null, Network.TESTNET)
val esploraClient = EsploraClient("https://mempool.space/testnet/api")
val update = esploraClient.scan(wallet, 10uL, 1uL)
wallet.applyUpdate(update)
println("Balance: ${wallet.getBalance().total}")
println("Balance: ${wallet.getBalance().total()}")
println("New address: ${wallet.getAddress(AddressIndex.New).address}")
assert(wallet.getBalance().total > 0uL) {
assert(wallet.getBalance().total() > 0uL) {
"Wallet balance must be greater than 0! Please send funds to ${wallet.getAddress(AddressIndex.New).address} and try again."
}
@@ -63,7 +41,7 @@ class LiveWalletTest {
val psbt: PartiallySignedTransaction = TxBuilder()
.addRecipient(recipient.scriptPubkey(), 4200uL)
.feeRate(FeeRate.fromSatPerVb(4.0f))
.feeRate(4.0f)
.finish(wallet)
println(psbt.serialize())
@@ -73,14 +51,8 @@ class LiveWalletTest {
assertTrue(walletDidSign)
val tx: Transaction = psbt.extractTx()
println("Txid is: ${tx.txid()}")
val txFee: ULong = wallet.calculateFee(tx)
println("Tx fee is: ${txFee}")
val feeRate: FeeRate = wallet.calculateFeeRate(tx)
println("Tx fee rate is: ${feeRate.asSatPerVb()} sat/vB")
esploraClient.broadcast(tx)
}
}

View File

@@ -4,6 +4,7 @@ import kotlin.test.Test
import kotlin.test.assertEquals
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.runner.RunWith
import kotlin.test.assertEquals
@RunWith(AndroidJUnit4::class)
class OfflineDescriptorTest {

View File

@@ -3,26 +3,11 @@ package org.bitcoindevkit
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.assertFalse
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.runner.RunWith
import java.io.File
import kotlin.test.AfterTest
@RunWith(AndroidJUnit4::class)
class OfflineWalletTest {
private val persistenceFilePath = InstrumentationRegistry
.getInstrumentation().targetContext.filesDir.path + "/bdk_persistence.db"
@AfterTest
fun cleanup() {
val file = File(persistenceFilePath)
if (file.exists()) {
file.delete()
}
}
@Test
fun testDescriptorBip86() {
val mnemonic: Mnemonic = Mnemonic(WordCount.WORDS12)
@@ -38,19 +23,13 @@ class OfflineWalletTest {
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
Network.TESTNET
)
val wallet: Wallet = Wallet(
val wallet: Wallet = Wallet.newNoPersist(
descriptor,
null,
persistenceFilePath,
Network.TESTNET
)
val addressInfo: AddressInfo = wallet.getAddress(AddressIndex.New)
assertTrue(addressInfo.address.isValidForNetwork(Network.TESTNET), "Address is not valid for testnet network")
assertTrue(addressInfo.address.isValidForNetwork(Network.SIGNET), "Address is not valid for signet network")
assertFalse(addressInfo.address.isValidForNetwork(Network.REGTEST), "Address is valid for regtest network, but it shouldn't be")
assertFalse(addressInfo.address.isValidForNetwork(Network.BITCOIN), "Address is valid for bitcoin network, but it shouldn't be")
assertEquals(
expected = "tb1qzg4mckdh50nwdm9hkzq06528rsu73hjxxzem3e",
actual = addressInfo.address.asString()
@@ -63,16 +42,15 @@ class OfflineWalletTest {
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
Network.TESTNET
)
val wallet: Wallet = Wallet(
val wallet: Wallet = Wallet.newNoPersist(
descriptor,
null,
persistenceFilePath,
Network.TESTNET
)
assertEquals(
expected = 0uL,
actual = wallet.getBalance().total
actual = wallet.getBalance().total()
)
}
}

View File

@@ -144,7 +144,7 @@ internal class UniFfiAndroidPlugin : Plugin<Project> {
// The code above worked for uniffi 0.24.3 using the --library flag
// The code below works for uniffi 0.23.0
workingDir("${project.projectDir}/../../bdk-ffi")
val cargoArgs: List<String> = listOf("run", "--bin", "uniffi-bindgen", "generate", "src/bdk.udl", "--language", "kotlin", "--config", "uniffi-android.toml", "--out-dir", "../bdk-android/lib/src/main/kotlin", "--no-format")
val cargoArgs: List<String> = listOf("run", "--bin", "uniffi-bindgen", "generate", "src/bdk.udl", "--language", "kotlin", "--out-dir", "../bdk-android/lib/src/main/kotlin", "--no-format")
executable("cargo")
args(cargoArgs)

783
bdk-ffi/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
[package]
name = "bdk-ffi"
version = "1.0.0-alpha.7"
version = "1.0.0-alpha.2"
homepage = "https://bitcoindevkit.org"
repository = "https://github.com/bitcoindevkit/bdk"
edition = "2018"
@@ -18,19 +18,24 @@ path = "uniffi-bindgen.rs"
default = ["uniffi/cli"]
[dependencies]
bdk = { version = "1.0.0-alpha.7", features = ["all-keys", "keys-bip39"] }
bdk_esplora = { version = "0.9.0", default-features = false, features = ["std", "blocking"] }
# bdk_esplora = { version = "0.9.0", default-features = false, features = ["std", "blocking", "async-https-rustls"] }
bdk_file_store = { version = "0.7.0" }
bdk = { version = "1.0.0-alpha.2", features = ["all-keys", "keys-bip39"] }
uniffi = { version = "=0.26.1" }
thiserror = "1.0.58"
# TODO 22: The bdk_esplora crate uses esplora_client which uses reqwest for async. By default it uses the system
# openssl library, which is creating problems for cross-compilation. I'd rather use rustls, but it's hidden
# behind a feature flag. We need to look into whether openssl-sys is really required by bdk or if using rustls
# would work just as well. This here is a temporary workaround which removes the async feature on the bdk_esplora crate.
# See PR #1179 https://github.com/bitcoindevkit/bdk/pull/1179 for the fix in bdk.
# bdk = { git = "https://github.com/thunderbiscuit/bdk.git", branch = "test-rust-tls", version = "1.0.0-alpha.2", features = ["all-keys", "keys-bip39"] }
# bdk_esplora = { git = "https://github.com/thunderbiscuit/bdk.git", branch = "test-rust-tls", version = "0.4.0", package = "bdk_esplora", default-features = false, features = ["std", "blocking", "async-https-rustls"] }
bdk_esplora = { version = "0.4.0", default-features = false, features = ["std", "blocking"] }
uniffi = { version = "=0.25.1" }
[build-dependencies]
uniffi = { version = "=0.26.1", features = ["build"] }
uniffi = { version = "=0.25.1", features = ["build"] }
[dev-dependencies]
uniffi = { version = "=0.26.1", features = ["bindgen-tests"] }
uniffi = { version = "=0.25.1", features = ["bindgen-tests"] }
assert_matches = "1.5.0"
[profile.release-smaller]

View File

@@ -1,49 +1,7 @@
namespace bdk {};
// ------------------------------------------------------------------------
// bdk crate - error module
// ------------------------------------------------------------------------
[Error]
enum Alpha3Error {
"Generic"
};
[Error]
interface CalculateFeeError {
MissingTxOut(sequence<OutPoint> out_points);
NegativeFee(i64 fee);
};
[Error]
interface WalletCreationError {
Io(string e);
InvalidMagicBytes(sequence<u8> got, sequence<u8> expected);
Descriptor();
Write();
Load();
NotInitialized();
LoadedGenesisDoesNotMatch();
LoadedNetworkDoesNotMatch(Network expected, Network? got);
};
[Error]
interface EsploraError {
Ureq(string error_message);
UreqTransport(string error_message);
Http(u16 status_code);
Io(string error_message);
NoHeader();
Parsing(string error_message);
BitcoinEncoding(string error_message);
Hex(string error_message);
TransactionNotFound();
HeaderHeightNotFound(u32 height);
HeaderHashNotFound();
};
// ------------------------------------------------------------------------
// bdk crate - types module
// bdk crate - root module
// ------------------------------------------------------------------------
enum KeychainKind {
@@ -51,6 +9,60 @@ enum KeychainKind {
"Internal",
};
// ------------------------------------------------------------------------
// bdk crate - wallet module
// ------------------------------------------------------------------------
[Error]
enum BdkError {
"Generic",
"NoRecipients",
"NoUtxosSelected",
"OutputBelowDustLimit",
"InsufficientFunds",
"BnBTotalTriesExceeded",
"BnBNoExactMatch",
"UnknownUtxo",
"TransactionNotFound",
"TransactionConfirmed",
"IrreplaceableTransaction",
"FeeRateTooLow",
"FeeTooLow",
"FeeRateUnavailable",
"MissingKeyOrigin",
"Key",
"ChecksumMismatch",
"SpendingPolicyRequired",
"InvalidPolicyPathError",
"Signer",
"InvalidOutpoint",
"Descriptor",
"Miniscript",
"MiniscriptPsbt",
"Bip32",
"Psbt",
};
enum ChangeSpendPolicy {
"ChangeAllowed",
"OnlyChange",
"ChangeForbidden"
};
interface Balance {
u64 immature();
u64 trusted_pending();
u64 untrusted_pending();
u64 confirmed();
u64 trusted_spendable();
u64 total();
};
dictionary AddressInfo {
u32 index;
Address address;
@@ -64,84 +76,25 @@ interface AddressIndex {
Peek(u32 index);
};
dictionary Balance {
u64 immature;
u64 trusted_pending;
u64 untrusted_pending;
u64 confirmed;
u64 trusted_spendable;
u64 total;
};
dictionary LocalOutput {
OutPoint outpoint;
TxOut txout;
KeychainKind keychain;
boolean is_spent;
};
dictionary TxOut {
u64 value;
Script script_pubkey;
};
// ------------------------------------------------------------------------
// bdk crate - wallet module
// ------------------------------------------------------------------------
interface FeeRate {
[Name=from_sat_per_vb]
constructor(f32 sat_per_vb);
[Name=from_sat_per_kwu]
constructor(f32 sat_per_kwu);
f32 as_sat_per_vb();
f32 sat_per_kwu();
};
enum ChangeSpendPolicy {
"ChangeAllowed",
"OnlyChange",
"ChangeForbidden"
};
interface Wallet {
[Throws=WalletCreationError]
constructor(Descriptor descriptor, Descriptor? change_descriptor, string persistence_backend_path, Network network);
[Name=new_no_persist, Throws=BdkError]
constructor(Descriptor descriptor, Descriptor? change_descriptor, Network network);
AddressInfo get_address(AddressIndex address_index);
[Throws=Alpha3Error]
AddressInfo try_get_internal_address(AddressIndex address_index);
AddressInfo get_internal_address(AddressIndex address_index);
Network network();
Balance get_balance();
[Throws=Alpha3Error]
boolean is_mine(Script script);
[Throws=BdkError]
void apply_update(Update update);
boolean is_mine([ByRef] Script script);
[Throws=Alpha3Error]
[Throws=BdkError]
boolean sign(PartiallySignedTransaction psbt);
SentAndReceivedValues sent_and_received([ByRef] Transaction tx);
sequence<Transaction> transactions();
[Throws=CalculateFeeError]
u64 calculate_fee([ByRef] Transaction tx);
[Throws=CalculateFeeError]
FeeRate calculate_fee_rate([ByRef] Transaction tx);
};
interface Update {};
@@ -149,14 +102,12 @@ interface Update {};
interface TxBuilder {
constructor();
TxBuilder add_recipient([ByRef] Script script, u64 amount);
TxBuilder add_recipient(Script script, u64 amount);
TxBuilder set_recipients(sequence<ScriptAmount> recipients);
TxBuilder set_recipients(sequence<ScriptAmount> script_amount);
TxBuilder add_unspendable(OutPoint unspendable);
TxBuilder unspendable(sequence<OutPoint> unspendable);
TxBuilder add_utxo(OutPoint outpoint);
TxBuilder change_policy(ChangeSpendPolicy change_policy);
@@ -167,32 +118,11 @@ interface TxBuilder {
TxBuilder manually_selected_only();
TxBuilder fee_rate([ByRef] FeeRate fee_rate);
TxBuilder fee_absolute(u64 fee);
TxBuilder fee_rate(float sat_per_vbyte);
TxBuilder drain_wallet();
TxBuilder drain_to([ByRef] Script script);
TxBuilder enable_rbf();
TxBuilder enable_rbf_with_sequence(u32 nsequence);
[Throws=Alpha3Error]
PartiallySignedTransaction finish([ByRef] Wallet wallet);
};
interface BumpFeeTxBuilder {
constructor(string txid, f32 fee_rate);
BumpFeeTxBuilder allow_shrinking(Script script_pubkey);
BumpFeeTxBuilder enable_rbf();
BumpFeeTxBuilder enable_rbf_with_sequence(u32 nsequence);
[Throws=Alpha3Error]
[Throws=BdkError]
PartiallySignedTransaction finish([ByRef] Wallet wallet);
};
@@ -203,31 +133,31 @@ interface BumpFeeTxBuilder {
interface Mnemonic {
constructor(WordCount word_count);
[Name=from_string, Throws=Alpha3Error]
[Name=from_string, Throws=BdkError]
constructor(string mnemonic);
[Name=from_entropy, Throws=Alpha3Error]
[Name=from_entropy, Throws=BdkError]
constructor(sequence<u8> entropy);
string as_string();
};
interface DerivationPath {
[Throws=Alpha3Error]
[Throws=BdkError]
constructor(string path);
};
interface DescriptorSecretKey {
constructor(Network network, [ByRef] Mnemonic mnemonic, string? password);
constructor(Network network, Mnemonic mnemonic, string? password);
[Name=from_string, Throws=Alpha3Error]
[Name=from_string, Throws=BdkError]
constructor(string secret_key);
[Throws=Alpha3Error]
DescriptorSecretKey derive([ByRef] DerivationPath path);
[Throws=BdkError]
DescriptorSecretKey derive(DerivationPath path);
[Throws=Alpha3Error]
DescriptorSecretKey extend([ByRef] DerivationPath path);
[Throws=BdkError]
DescriptorSecretKey extend(DerivationPath path);
DescriptorPublicKey as_public();
@@ -237,45 +167,45 @@ interface DescriptorSecretKey {
};
interface DescriptorPublicKey {
[Name=from_string, Throws=Alpha3Error]
[Name=from_string, Throws=BdkError]
constructor(string public_key);
[Throws=Alpha3Error]
DescriptorPublicKey derive([ByRef] DerivationPath path);
[Throws=BdkError]
DescriptorPublicKey derive(DerivationPath path);
[Throws=Alpha3Error]
DescriptorPublicKey extend([ByRef] DerivationPath path);
[Throws=BdkError]
DescriptorPublicKey extend(DerivationPath path);
string as_string();
};
interface Descriptor {
[Throws=Alpha3Error]
[Throws=BdkError]
constructor(string descriptor, Network network);
[Name=new_bip44]
constructor([ByRef] DescriptorSecretKey secret_key, KeychainKind keychain, Network network);
constructor(DescriptorSecretKey secret_key, KeychainKind keychain, Network network);
[Name=new_bip44_public]
constructor([ByRef] DescriptorPublicKey public_key, string fingerprint, KeychainKind keychain, Network network);
constructor(DescriptorPublicKey public_key, string fingerprint, KeychainKind keychain, Network network);
[Name=new_bip49]
constructor([ByRef] DescriptorSecretKey secret_key, KeychainKind keychain, Network network);
constructor(DescriptorSecretKey secret_key, KeychainKind keychain, Network network);
[Name=new_bip49_public]
constructor([ByRef] DescriptorPublicKey public_key, string fingerprint, KeychainKind keychain, Network network);
constructor(DescriptorPublicKey public_key, string fingerprint, KeychainKind keychain, Network network);
[Name=new_bip84]
constructor([ByRef] DescriptorSecretKey secret_key, KeychainKind keychain, Network network);
constructor(DescriptorSecretKey secret_key, KeychainKind keychain, Network network);
[Name=new_bip84_public]
constructor([ByRef] DescriptorPublicKey public_key, string fingerprint, KeychainKind keychain, Network network);
constructor(DescriptorPublicKey public_key, string fingerprint, KeychainKind keychain, Network network);
[Name=new_bip86]
constructor([ByRef] DescriptorSecretKey secret_key, KeychainKind keychain, Network network);
constructor(DescriptorSecretKey secret_key, KeychainKind keychain, Network network);
[Name=new_bip86_public]
constructor([ByRef] DescriptorPublicKey public_key, string fingerprint, KeychainKind keychain, Network network);
constructor(DescriptorPublicKey public_key, string fingerprint, KeychainKind keychain, Network network);
string as_string();
@@ -289,11 +219,11 @@ interface Descriptor {
interface EsploraClient {
constructor(string url);
[Throws=EsploraError]
Update full_scan(Wallet wallet, u64 stop_gap, u64 parallel_requests);
[Throws=BdkError]
Update scan(Wallet wallet, u64 stop_gap, u64 parallel_requests);
[Throws=Alpha3Error]
void broadcast([ByRef] Transaction transaction);
[Throws=BdkError]
void broadcast(Transaction transaction);
};
// ------------------------------------------------------------------------
@@ -305,11 +235,6 @@ dictionary ScriptAmount {
u64 amount;
};
dictionary SentAndReceivedValues {
u64 sent;
u64 received;
};
// ------------------------------------------------------------------------
// bdk crate - bitcoin re-exports
// ------------------------------------------------------------------------
@@ -320,7 +245,6 @@ interface Script {
sequence<u8> to_bytes();
};
[NonExhaustive]
enum Network {
"Bitcoin",
"Testnet",
@@ -337,7 +261,7 @@ enum WordCount {
};
interface Address {
[Throws=Alpha3Error]
[Throws=BdkError]
constructor(string address, Network network);
Network network();
@@ -347,12 +271,10 @@ interface Address {
string to_qr_uri();
string as_string();
boolean is_valid_for_network(Network network);
};
interface Transaction {
[Throws=Alpha3Error]
[Throws=BdkError]
constructor(sequence<u8> transaction_bytes);
string txid();
@@ -371,7 +293,7 @@ interface Transaction {
};
interface PartiallySignedTransaction {
[Throws=Alpha3Error]
[Throws=BdkError]
constructor(string psbt_base64);
string serialize();

View File

@@ -1,19 +1,19 @@
use bdk::bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bdk::bitcoin::blockdata::script::ScriptBuf as BdkScriptBuf;
use bdk::bitcoin::blockdata::transaction::TxOut as BdkTxOut;
use bdk::bitcoin::consensus::Decodable;
use bdk::bitcoin::network::constants::Network as BdkNetwork;
use bdk::bitcoin::psbt::PartiallySignedTransaction as BdkPartiallySignedTransaction;
use bdk::bitcoin::Address as BdkAddress;
use bdk::bitcoin::Network;
use bdk::bitcoin::OutPoint as BdkOutPoint;
use bdk::bitcoin::Transaction as BdkTransaction;
use bdk::bitcoin::Txid;
use bdk::Error as BdkError;
use crate::error::Alpha3Error;
use std::io::Cursor;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
/// A Bitcoin script.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Script(pub(crate) BdkScriptBuf);
@@ -34,20 +34,55 @@ impl From<BdkScriptBuf> for Script {
}
}
pub enum Network {
/// Mainnet Bitcoin.
Bitcoin,
/// Bitcoin's testnet network.
Testnet,
/// Bitcoin's signet network.
Signet,
/// Bitcoin's regtest network.
Regtest,
}
impl From<Network> for BdkNetwork {
fn from(network: Network) -> Self {
match network {
Network::Bitcoin => BdkNetwork::Bitcoin,
Network::Testnet => BdkNetwork::Testnet,
Network::Signet => BdkNetwork::Signet,
Network::Regtest => BdkNetwork::Regtest,
}
}
}
impl From<BdkNetwork> for Network {
fn from(network: BdkNetwork) -> Self {
match network {
BdkNetwork::Bitcoin => Network::Bitcoin,
BdkNetwork::Testnet => Network::Testnet,
BdkNetwork::Signet => Network::Signet,
BdkNetwork::Regtest => Network::Regtest,
_ => panic!("Network {} not supported", network),
}
}
}
/// A Bitcoin address.
#[derive(Debug, PartialEq, Eq)]
pub struct Address {
inner: BdkAddress<NetworkChecked>,
}
impl Address {
pub fn new(address: String, network: Network) -> Result<Self, Alpha3Error> {
pub fn new(address: String, network: Network) -> Result<Self, BdkError> {
let parsed_address = address
.parse::<bdk::bitcoin::Address<NetworkUnchecked>>()
.map_err(|_| Alpha3Error::Generic)?;
.map_err(|e| BdkError::Generic(e.to_string()))?;
let network_checked_address = parsed_address
.require_network(network)
.map_err(|_| Alpha3Error::Generic)?;
.require_network(network.into())
.map_err(|e| BdkError::Generic(e.to_string()))?;
Ok(Address {
inner: network_checked_address,
@@ -77,7 +112,7 @@ impl Address {
// }
pub fn network(&self) -> Network {
self.inner.network
self.inner.network.into()
}
pub fn script_pubkey(&self) -> Arc<Script> {
@@ -91,15 +126,6 @@ impl Address {
pub fn as_string(&self) -> String {
self.inner.to_string()
}
pub fn is_valid_for_network(&self, network: Network) -> bool {
let address_str = self.inner.to_string();
if let Ok(unchecked_address) = address_str.parse::<BdkAddress<NetworkUnchecked>>() {
unchecked_address.is_valid_for_network(network)
} else {
false
}
}
}
impl From<Address> for BdkAddress {
@@ -114,16 +140,17 @@ impl From<BdkAddress> for Address {
}
}
/// A Bitcoin transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Transaction {
inner: BdkTransaction,
}
impl Transaction {
pub fn new(transaction_bytes: Vec<u8>) -> Result<Self, Alpha3Error> {
pub fn new(transaction_bytes: Vec<u8>) -> Result<Self, BdkError> {
let mut decoder = Cursor::new(transaction_bytes);
let tx: BdkTransaction =
BdkTransaction::consensus_decode(&mut decoder).map_err(|_| Alpha3Error::Generic)?;
let tx: BdkTransaction = BdkTransaction::consensus_decode(&mut decoder)
.map_err(|e| BdkError::Generic(e.to_string()))?;
Ok(Transaction { inner: tx })
}
@@ -182,15 +209,9 @@ impl From<BdkTransaction> for Transaction {
}
}
impl From<&BdkTransaction> for Transaction {
fn from(tx: &BdkTransaction) -> Self {
Transaction { inner: tx.clone() }
}
}
impl From<&Transaction> for BdkTransaction {
fn from(tx: &Transaction) -> Self {
tx.inner.clone()
impl From<Transaction> for BdkTransaction {
fn from(tx: Transaction) -> Self {
tx.inner
}
}
@@ -199,10 +220,10 @@ pub struct PartiallySignedTransaction {
}
impl PartiallySignedTransaction {
pub(crate) fn new(psbt_base64: String) -> Result<Self, Alpha3Error> {
pub(crate) fn new(psbt_base64: String) -> Result<Self, BdkError> {
let psbt: BdkPartiallySignedTransaction =
BdkPartiallySignedTransaction::from_str(&psbt_base64)
.map_err(|_| Alpha3Error::Generic)?;
.map_err(|e| BdkError::Generic(e.to_string()))?;
Ok(PartiallySignedTransaction {
inner: Mutex::new(psbt),
@@ -220,6 +241,7 @@ impl PartiallySignedTransaction {
// txid.to_hex()
// }
/// Return the transaction.
pub(crate) fn extract_tx(&self) -> Arc<Transaction> {
let tx = self.inner.lock().unwrap().clone().extract_tx();
Arc::new(tx.into())
@@ -270,9 +292,12 @@ impl From<BdkPartiallySignedTransaction> for PartiallySignedTransaction {
}
}
/// A reference to a transaction output.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct OutPoint {
/// The referenced transaction's txid.
pub txid: String,
/// The index of the referenced output in its transaction's vout.
pub vout: u32,
}
@@ -284,378 +309,3 @@ impl From<&OutPoint> for BdkOutPoint {
}
}
}
impl From<&BdkOutPoint> for OutPoint {
fn from(outpoint: &BdkOutPoint) -> Self {
OutPoint {
txid: outpoint.txid.to_string(),
vout: outpoint.vout,
}
}
}
#[derive(Debug, Clone)]
pub struct TxOut {
pub value: u64,
pub script_pubkey: Arc<Script>,
}
impl From<&BdkTxOut> for TxOut {
fn from(tx_out: &BdkTxOut) -> Self {
TxOut {
value: tx_out.value,
script_pubkey: Arc::new(Script(tx_out.script_pubkey.clone())),
}
}
}
#[cfg(test)]
mod tests {
use crate::bitcoin::Address;
use crate::bitcoin::Network;
#[test]
fn test_is_valid_for_network() {
// ====Docs tests====
// https://docs.rs/bitcoin/0.29.2/src/bitcoin/util/address.rs.html#798-802
let docs_address_testnet_str = "2N83imGV3gPwBzKJQvWJ7cRUY2SpUyU6A5e";
let docs_address_testnet =
Address::new(docs_address_testnet_str.to_string(), Network::Testnet).unwrap();
assert!(
docs_address_testnet.is_valid_for_network(Network::Testnet),
"Address should be valid for Testnet"
);
assert!(
docs_address_testnet.is_valid_for_network(Network::Signet),
"Address should be valid for Signet"
);
assert!(
docs_address_testnet.is_valid_for_network(Network::Regtest),
"Address should be valid for Regtest"
);
assert_ne!(
docs_address_testnet.network(),
Network::Bitcoin,
"Address should not be parsed as Bitcoin"
);
let docs_address_mainnet_str = "32iVBEu4dxkUQk9dJbZUiBiQdmypcEyJRf";
let docs_address_mainnet =
Address::new(docs_address_mainnet_str.to_string(), Network::Bitcoin).unwrap();
assert!(
docs_address_mainnet.is_valid_for_network(Network::Bitcoin),
"Address should be valid for Bitcoin"
);
assert_ne!(
docs_address_mainnet.network(),
Network::Testnet,
"Address should not be valid for Testnet"
);
assert_ne!(
docs_address_mainnet.network(),
Network::Signet,
"Address should not be valid for Signet"
);
assert_ne!(
docs_address_mainnet.network(),
Network::Regtest,
"Address should not be valid for Regtest"
);
// ====Bech32====
// | Network | Prefix | Address Type |
// |-----------------|---------|--------------|
// | Bitcoin Mainnet | `bc1` | Bech32 |
// | Bitcoin Testnet | `tb1` | Bech32 |
// | Bitcoin Signet | `tb1` | Bech32 |
// | Bitcoin Regtest | `bcrt1` | Bech32 |
// Bech32 - Bitcoin
// Valid for:
// - Bitcoin
// Not valid for:
// - Testnet
// - Signet
// - Regtest
let bitcoin_mainnet_bech32_address_str = "bc1qxhmdufsvnuaaaer4ynz88fspdsxq2h9e9cetdj";
let bitcoin_mainnet_bech32_address = Address::new(
bitcoin_mainnet_bech32_address_str.to_string(),
Network::Bitcoin,
)
.unwrap();
assert!(
bitcoin_mainnet_bech32_address.is_valid_for_network(Network::Bitcoin),
"Address should be valid for Bitcoin"
);
assert!(
!bitcoin_mainnet_bech32_address.is_valid_for_network(Network::Testnet),
"Address should not be valid for Testnet"
);
assert!(
!bitcoin_mainnet_bech32_address.is_valid_for_network(Network::Signet),
"Address should not be valid for Signet"
);
assert!(
!bitcoin_mainnet_bech32_address.is_valid_for_network(Network::Regtest),
"Address should not be valid for Regtest"
);
// Bech32 - Testnet
// Valid for:
// - Testnet
// - Regtest
// Not valid for:
// - Bitcoin
// - Regtest
let bitcoin_testnet_bech32_address_str =
"tb1p4nel7wkc34raczk8c4jwk5cf9d47u2284rxn98rsjrs4w3p2sheqvjmfdh";
let bitcoin_testnet_bech32_address = Address::new(
bitcoin_testnet_bech32_address_str.to_string(),
Network::Testnet,
)
.unwrap();
assert!(
!bitcoin_testnet_bech32_address.is_valid_for_network(Network::Bitcoin),
"Address should not be valid for Bitcoin"
);
assert!(
bitcoin_testnet_bech32_address.is_valid_for_network(Network::Testnet),
"Address should be valid for Testnet"
);
assert!(
bitcoin_testnet_bech32_address.is_valid_for_network(Network::Signet),
"Address should be valid for Signet"
);
assert!(
!bitcoin_testnet_bech32_address.is_valid_for_network(Network::Regtest),
"Address should not not be valid for Regtest"
);
// Bech32 - Signet
// Valid for:
// - Signet
// - Testnet
// Not valid for:
// - Bitcoin
// - Regtest
let bitcoin_signet_bech32_address_str =
"tb1pwzv7fv35yl7ypwj8w7al2t8apd6yf4568cs772qjwper74xqc99sk8x7tk";
let bitcoin_signet_bech32_address = Address::new(
bitcoin_signet_bech32_address_str.to_string(),
Network::Signet,
)
.unwrap();
assert!(
!bitcoin_signet_bech32_address.is_valid_for_network(Network::Bitcoin),
"Address should not be valid for Bitcoin"
);
assert!(
bitcoin_signet_bech32_address.is_valid_for_network(Network::Testnet),
"Address should be valid for Testnet"
);
assert!(
bitcoin_signet_bech32_address.is_valid_for_network(Network::Signet),
"Address should be valid for Signet"
);
assert!(
!bitcoin_signet_bech32_address.is_valid_for_network(Network::Regtest),
"Address should not not be valid for Regtest"
);
// Bech32 - Regtest
// Valid for:
// - Regtest
// Not valid for:
// - Bitcoin
// - Testnet
// - Signet
let bitcoin_regtest_bech32_address_str = "bcrt1q39c0vrwpgfjkhasu5mfke9wnym45nydfwaeems";
let bitcoin_regtest_bech32_address = Address::new(
bitcoin_regtest_bech32_address_str.to_string(),
Network::Regtest,
)
.unwrap();
assert!(
!bitcoin_regtest_bech32_address.is_valid_for_network(Network::Bitcoin),
"Address should not be valid for Bitcoin"
);
assert!(
!bitcoin_regtest_bech32_address.is_valid_for_network(Network::Testnet),
"Address should not be valid for Testnet"
);
assert!(
!bitcoin_regtest_bech32_address.is_valid_for_network(Network::Signet),
"Address should not be valid for Signet"
);
assert!(
bitcoin_regtest_bech32_address.is_valid_for_network(Network::Regtest),
"Address should be valid for Regtest"
);
// ====P2PKH====
// | Network | Prefix for P2PKH | Prefix for P2SH |
// |------------------------------------|------------------|-----------------|
// | Bitcoin Mainnet | `1` | `3` |
// | Bitcoin Testnet, Regtest, Signet | `m` or `n` | `2` |
// P2PKH - Bitcoin
// Valid for:
// - Bitcoin
// Not valid for:
// - Testnet
// - Regtest
let bitcoin_mainnet_p2pkh_address_str = "1FfmbHfnpaZjKFvyi1okTjJJusN455paPH";
let bitcoin_mainnet_p2pkh_address = Address::new(
bitcoin_mainnet_p2pkh_address_str.to_string(),
Network::Bitcoin,
)
.unwrap();
assert!(
bitcoin_mainnet_p2pkh_address.is_valid_for_network(Network::Bitcoin),
"Address should be valid for Bitcoin"
);
assert!(
!bitcoin_mainnet_p2pkh_address.is_valid_for_network(Network::Testnet),
"Address should not be valid for Testnet"
);
assert!(
!bitcoin_mainnet_p2pkh_address.is_valid_for_network(Network::Regtest),
"Address should not be valid for Regtest"
);
// P2PKH - Testnet
// Valid for:
// - Testnet
// - Regtest
// Not valid for:
// - Bitcoin
let bitcoin_testnet_p2pkh_address_str = "mucFNhKMYoBQYUAEsrFVscQ1YaFQPekBpg";
let bitcoin_testnet_p2pkh_address = Address::new(
bitcoin_testnet_p2pkh_address_str.to_string(),
Network::Testnet,
)
.unwrap();
assert!(
!bitcoin_testnet_p2pkh_address.is_valid_for_network(Network::Bitcoin),
"Address should not be valid for Bitcoin"
);
assert!(
bitcoin_testnet_p2pkh_address.is_valid_for_network(Network::Testnet),
"Address should be valid for Testnet"
);
assert!(
bitcoin_testnet_p2pkh_address.is_valid_for_network(Network::Regtest),
"Address should be valid for Regtest"
);
// P2PKH - Regtest
// Valid for:
// - Testnet
// - Regtest
// Not valid for:
// - Bitcoin
let bitcoin_regtest_p2pkh_address_str = "msiGFK1PjCk8E6FXeoGkQPTscmcpyBdkgS";
let bitcoin_regtest_p2pkh_address = Address::new(
bitcoin_regtest_p2pkh_address_str.to_string(),
Network::Regtest,
)
.unwrap();
assert!(
!bitcoin_regtest_p2pkh_address.is_valid_for_network(Network::Bitcoin),
"Address should not be valid for Bitcoin"
);
assert!(
bitcoin_regtest_p2pkh_address.is_valid_for_network(Network::Testnet),
"Address should be valid for Testnet"
);
assert!(
bitcoin_regtest_p2pkh_address.is_valid_for_network(Network::Regtest),
"Address should be valid for Regtest"
);
// ====P2SH====
// | Network | Prefix for P2PKH | Prefix for P2SH |
// |------------------------------------|------------------|-----------------|
// | Bitcoin Mainnet | `1` | `3` |
// | Bitcoin Testnet, Regtest, Signet | `m` or `n` | `2` |
// P2SH - Bitcoin
// Valid for:
// - Bitcoin
// Not valid for:
// - Testnet
// - Regtest
let bitcoin_mainnet_p2sh_address_str = "3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy";
let bitcoin_mainnet_p2sh_address = Address::new(
bitcoin_mainnet_p2sh_address_str.to_string(),
Network::Bitcoin,
)
.unwrap();
assert!(
bitcoin_mainnet_p2sh_address.is_valid_for_network(Network::Bitcoin),
"Address should be valid for Bitcoin"
);
assert!(
!bitcoin_mainnet_p2sh_address.is_valid_for_network(Network::Testnet),
"Address should not be valid for Testnet"
);
assert!(
!bitcoin_mainnet_p2sh_address.is_valid_for_network(Network::Regtest),
"Address should not be valid for Regtest"
);
// P2SH - Testnet
// Valid for:
// - Testnet
// - Regtest
// Not valid for:
// - Bitcoin
let bitcoin_testnet_p2sh_address_str = "2NFUBBRcTJbYc1D4HSCbJhKZp6YCV4PQFpQ";
let bitcoin_testnet_p2sh_address = Address::new(
bitcoin_testnet_p2sh_address_str.to_string(),
Network::Testnet,
)
.unwrap();
assert!(
!bitcoin_testnet_p2sh_address.is_valid_for_network(Network::Bitcoin),
"Address should not be valid for Bitcoin"
);
assert!(
bitcoin_testnet_p2sh_address.is_valid_for_network(Network::Testnet),
"Address should be valid for Testnet"
);
assert!(
bitcoin_testnet_p2sh_address.is_valid_for_network(Network::Regtest),
"Address should be valid for Regtest"
);
// P2SH - Regtest
// Valid for:
// - Testnet
// - Regtest
// Not valid for:
// - Bitcoin
let bitcoin_regtest_p2sh_address_str = "2NEb8N5B9jhPUCBchz16BB7bkJk8VCZQjf3";
let bitcoin_regtest_p2sh_address = Address::new(
bitcoin_regtest_p2sh_address_str.to_string(),
Network::Regtest,
)
.unwrap();
assert!(
!bitcoin_regtest_p2sh_address.is_valid_for_network(Network::Bitcoin),
"Address should not be valid for Bitcoin"
);
assert!(
bitcoin_regtest_p2sh_address.is_valid_for_network(Network::Testnet),
"Address should be valid for Testnet"
);
assert!(
bitcoin_regtest_p2sh_address.is_valid_for_network(Network::Regtest),
"Address should be valid for Regtest"
);
}
}

View File

@@ -1,10 +1,9 @@
use crate::error::Alpha3Error;
use crate::keys::DescriptorPublicKey;
use crate::keys::DescriptorSecretKey;
use crate::Network;
use bdk::bitcoin::bip32::Fingerprint;
use bdk::bitcoin::key::Secp256k1;
use bdk::bitcoin::Network;
use bdk::descriptor::{ExtendedDescriptor, IntoWalletDescriptor};
use bdk::keys::DescriptorPublicKey as BdkDescriptorPublicKey;
use bdk::keys::{DescriptorSecretKey as BdkDescriptorSecretKey, KeyMap};
@@ -12,9 +11,11 @@ use bdk::template::{
Bip44, Bip44Public, Bip49, Bip49Public, Bip84, Bip84Public, Bip86, Bip86Public,
DescriptorTemplate,
};
use bdk::Error as BdkError;
use bdk::KeychainKind;
use std::str::FromStr;
use std::sync::Arc;
#[derive(Debug)]
pub struct Descriptor {
@@ -23,9 +24,10 @@ pub struct Descriptor {
}
impl Descriptor {
pub(crate) fn new(descriptor: String, network: Network) -> Result<Self, Alpha3Error> {
pub(crate) fn new(descriptor: String, network: Network) -> Result<Self, BdkError> {
let secp = Secp256k1::new();
let (extended_descriptor, key_map) = descriptor.into_wallet_descriptor(&secp, network)?;
let (extended_descriptor, key_map) =
descriptor.into_wallet_descriptor(&secp, network.into())?;
Ok(Self {
extended_descriptor,
key_map,
@@ -33,7 +35,7 @@ impl Descriptor {
}
pub(crate) fn new_bip44(
secret_key: &DescriptorSecretKey,
secret_key: Arc<DescriptorSecretKey>,
keychain_kind: KeychainKind,
network: Network,
) -> Self {
@@ -45,8 +47,9 @@ impl Descriptor {
}
BdkDescriptorSecretKey::XPrv(descriptor_x_key) => {
let derivable_key = descriptor_x_key.xkey;
let (extended_descriptor, key_map, _) =
Bip44(derivable_key, keychain_kind).build(network).unwrap();
let (extended_descriptor, key_map, _) = Bip44(derivable_key, keychain_kind)
.build(network.into())
.unwrap();
Self {
extended_descriptor,
key_map,
@@ -59,7 +62,7 @@ impl Descriptor {
}
pub(crate) fn new_bip44_public(
public_key: &DescriptorPublicKey,
public_key: Arc<DescriptorPublicKey>,
fingerprint: String,
keychain_kind: KeychainKind,
network: Network,
@@ -75,7 +78,7 @@ impl Descriptor {
let derivable_key = descriptor_x_key.xkey;
let (extended_descriptor, key_map, _) =
Bip44Public(derivable_key, fingerprint, keychain_kind)
.build(network)
.build(network.into())
.unwrap();
Self {
@@ -90,7 +93,7 @@ impl Descriptor {
}
pub(crate) fn new_bip49(
secret_key: &DescriptorSecretKey,
secret_key: Arc<DescriptorSecretKey>,
keychain_kind: KeychainKind,
network: Network,
) -> Self {
@@ -102,8 +105,9 @@ impl Descriptor {
}
BdkDescriptorSecretKey::XPrv(descriptor_x_key) => {
let derivable_key = descriptor_x_key.xkey;
let (extended_descriptor, key_map, _) =
Bip49(derivable_key, keychain_kind).build(network).unwrap();
let (extended_descriptor, key_map, _) = Bip49(derivable_key, keychain_kind)
.build(network.into())
.unwrap();
Self {
extended_descriptor,
key_map,
@@ -116,7 +120,7 @@ impl Descriptor {
}
pub(crate) fn new_bip49_public(
public_key: &DescriptorPublicKey,
public_key: Arc<DescriptorPublicKey>,
fingerprint: String,
keychain_kind: KeychainKind,
network: Network,
@@ -132,7 +136,7 @@ impl Descriptor {
let derivable_key = descriptor_x_key.xkey;
let (extended_descriptor, key_map, _) =
Bip49Public(derivable_key, fingerprint, keychain_kind)
.build(network)
.build(network.into())
.unwrap();
Self {
@@ -147,7 +151,7 @@ impl Descriptor {
}
pub(crate) fn new_bip84(
secret_key: &DescriptorSecretKey,
secret_key: Arc<DescriptorSecretKey>,
keychain_kind: KeychainKind,
network: Network,
) -> Self {
@@ -159,8 +163,9 @@ impl Descriptor {
}
BdkDescriptorSecretKey::XPrv(descriptor_x_key) => {
let derivable_key = descriptor_x_key.xkey;
let (extended_descriptor, key_map, _) =
Bip84(derivable_key, keychain_kind).build(network).unwrap();
let (extended_descriptor, key_map, _) = Bip84(derivable_key, keychain_kind)
.build(network.into())
.unwrap();
Self {
extended_descriptor,
key_map,
@@ -173,7 +178,7 @@ impl Descriptor {
}
pub(crate) fn new_bip84_public(
public_key: &DescriptorPublicKey,
public_key: Arc<DescriptorPublicKey>,
fingerprint: String,
keychain_kind: KeychainKind,
network: Network,
@@ -189,7 +194,7 @@ impl Descriptor {
let derivable_key = descriptor_x_key.xkey;
let (extended_descriptor, key_map, _) =
Bip84Public(derivable_key, fingerprint, keychain_kind)
.build(network)
.build(network.into())
.unwrap();
Self {
@@ -204,7 +209,7 @@ impl Descriptor {
}
pub(crate) fn new_bip86(
secret_key: &DescriptorSecretKey,
secret_key: Arc<DescriptorSecretKey>,
keychain_kind: KeychainKind,
network: Network,
) -> Self {
@@ -216,8 +221,9 @@ impl Descriptor {
}
BdkDescriptorSecretKey::XPrv(descriptor_x_key) => {
let derivable_key = descriptor_x_key.xkey;
let (extended_descriptor, key_map, _) =
Bip86(derivable_key, keychain_kind).build(network).unwrap();
let (extended_descriptor, key_map, _) = Bip86(derivable_key, keychain_kind)
.build(network.into())
.unwrap();
Self {
extended_descriptor,
key_map,
@@ -230,7 +236,7 @@ impl Descriptor {
}
pub(crate) fn new_bip86_public(
public_key: &DescriptorPublicKey,
public_key: Arc<DescriptorPublicKey>,
fingerprint: String,
keychain_kind: KeychainKind,
network: Network,
@@ -246,7 +252,7 @@ impl Descriptor {
let derivable_key = descriptor_x_key.xkey;
let (extended_descriptor, key_map, _) =
Bip86Public(derivable_key, fingerprint, keychain_kind)
.build(network)
.build(network.into())
.unwrap();
Self {
@@ -271,80 +277,91 @@ impl Descriptor {
}
}
// // The goal of these tests to to ensure `bdk-ffi` intermediate code correctly calls `bdk` APIs.
// // These tests should not be used to verify `bdk` behavior that is already tested in the `bdk`
// // crate.
#[cfg(test)]
mod test {
use crate::*;
use assert_matches::assert_matches;
use crate::Alpha3Error;
use bdk::descriptor::DescriptorError::Key;
use bdk::keys::KeyError::InvalidNetwork;
fn get_descriptor_secret_key() -> DescriptorSecretKey {
let mnemonic = Mnemonic::from_string("chaos fabric time speed sponsor all flat solution wisdom trophy crack object robot pave observe combine where aware bench orient secret primary cable detect".to_string()).unwrap();
DescriptorSecretKey::new(Network::Testnet, &mnemonic, None)
DescriptorSecretKey::new(Network::Testnet, Arc::new(mnemonic), None)
}
#[test]
fn test_descriptor_templates() {
let master: DescriptorSecretKey = get_descriptor_secret_key();
let master: Arc<DescriptorSecretKey> = Arc::new(get_descriptor_secret_key());
println!("Master: {:?}", master.as_string());
// tprv8ZgxMBicQKsPdWuqM1t1CDRvQtQuBPyfL6GbhQwtxDKgUAVPbxmj71pRA8raTqLrec5LyTs5TqCxdABcZr77bt2KyWA5bizJHnC4g4ysm4h
let handmade_public_44 = master
.derive(&DerivationPath::new("m/44h/1h/0h".to_string()).unwrap())
.derive(Arc::new(
DerivationPath::new("m/44h/1h/0h".to_string()).unwrap(),
))
.unwrap()
.as_public();
println!("Public 44: {}", handmade_public_44.as_string());
// Public 44: [d1d04177/44'/1'/0']tpubDCoPjomfTqh1e7o1WgGpQtARWtkueXQAepTeNpWiitS3Sdv8RKJ1yvTrGHcwjDXp2SKyMrTEca4LoN7gEUiGCWboyWe2rz99Kf4jK4m2Zmx/*
let handmade_public_49 = master
.derive(&DerivationPath::new("m/49h/1h/0h".to_string()).unwrap())
.derive(Arc::new(
DerivationPath::new("m/49h/1h/0h".to_string()).unwrap(),
))
.unwrap()
.as_public();
println!("Public 49: {}", handmade_public_49.as_string());
// Public 49: [d1d04177/49'/1'/0']tpubDC65ZRvk1NDddHrVAUAZrUPJ772QXzooNYmPywYF9tMyNLYKf5wpKE7ZJvK9kvfG3FV7rCsHBNXy1LVKW95jrmC7c7z4hq7a27aD2sRrAhR/*
let handmade_public_84 = master
.derive(&DerivationPath::new("m/84h/1h/0h".to_string()).unwrap())
.derive(Arc::new(
DerivationPath::new("m/84h/1h/0h".to_string()).unwrap(),
))
.unwrap()
.as_public();
println!("Public 84: {}", handmade_public_84.as_string());
// Public 84: [d1d04177/84'/1'/0']tpubDDNxbq17egjFk2edjv8oLnzxk52zny9aAYNv9CMqTzA4mQDiQq818sEkNe9Gzmd4QU8558zftqbfoVBDQorG3E4Wq26tB2JeE4KUoahLkx6/*
let handmade_public_86 = master
.derive(&DerivationPath::new("m/86h/1h/0h".to_string()).unwrap())
.derive(Arc::new(
DerivationPath::new("m/86h/1h/0h".to_string()).unwrap(),
))
.unwrap()
.as_public();
println!("Public 86: {}", handmade_public_86.as_string());
// Public 86: [d1d04177/86'/1'/0']tpubDCJzjbcGbdEfXMWaL6QmgVmuSfXkrue7m2YNoacWwyc7a2XjXaKojRqNEbo41CFL3PyYmKdhwg2fkGpLX4SQCbQjCGxAkWHJTw9WEeenrJb/*
let template_private_44 =
Descriptor::new_bip44(&master, KeychainKind::External, Network::Testnet);
Descriptor::new_bip44(master.clone(), KeychainKind::External, Network::Testnet);
let template_private_49 =
Descriptor::new_bip49(&master, KeychainKind::External, Network::Testnet);
Descriptor::new_bip49(master.clone(), KeychainKind::External, Network::Testnet);
let template_private_84 =
Descriptor::new_bip84(&master, KeychainKind::External, Network::Testnet);
Descriptor::new_bip84(master.clone(), KeychainKind::External, Network::Testnet);
let template_private_86 =
Descriptor::new_bip86(&master, KeychainKind::External, Network::Testnet);
Descriptor::new_bip86(master, KeychainKind::External, Network::Testnet);
// the extended public keys are the same when creating them manually as they are with the templates
println!("Template 49: {}", template_private_49.as_string());
println!("Template 44: {}", template_private_44.as_string());
println!("Template 84: {}", template_private_84.as_string());
println!("Template 86: {}", template_private_86.as_string());
let template_public_44 = Descriptor::new_bip44_public(
&handmade_public_44,
handmade_public_44,
"d1d04177".to_string(),
KeychainKind::External,
Network::Testnet,
);
let template_public_49 = Descriptor::new_bip49_public(
&handmade_public_49,
handmade_public_49,
"d1d04177".to_string(),
KeychainKind::External,
Network::Testnet,
);
let template_public_84 = Descriptor::new_bip84_public(
&handmade_public_84,
handmade_public_84,
"d1d04177".to_string(),
KeychainKind::External,
Network::Testnet,
);
let template_public_86 = Descriptor::new_bip86_public(
&handmade_public_86,
handmade_public_86,
"d1d04177".to_string(),
KeychainKind::External,
Network::Testnet,
@@ -394,6 +411,9 @@ mod test {
let descriptor2 = Descriptor::new("wpkh(tprv8hwWMmPE4BVNxGdVt3HhEERZhondQvodUY7Ajyseyhudr4WabJqWKWLr4Wi2r26CDaNCQhhxEftEaNzz7dPGhWuKFU4VULesmhEfZYyBXdE/0/*)".to_string(), Network::Bitcoin);
// Creating a Descriptor using an extended key that doesn't match the network provided will throw and InvalidNetwork Error
assert!(descriptor1.is_ok());
assert_matches!(descriptor2.unwrap_err(), Alpha3Error::Generic)
assert_matches!(
descriptor2.unwrap_err(),
bdk::Error::Descriptor(Key(InvalidNetwork))
)
}
}

View File

@@ -1,320 +0,0 @@
use crate::bitcoin::OutPoint;
use bdk::chain::tx_graph::CalculateFeeError as BdkCalculateFeeError;
use bdk_esplora::esplora_client::Error as BdkEsploraError;
use bdk::bitcoin::Network;
use bdk::descriptor::DescriptorError;
use bdk::wallet::error::{BuildFeeBumpError, CreateTxError};
use bdk::wallet::tx_builder::{AddUtxoError, AllowShrinkingError};
use bdk::wallet::{NewError, NewOrLoadError};
use bdk_file_store::FileError as BdkFileError;
use bdk_file_store::IterError;
use std::convert::Infallible;
#[derive(Debug, thiserror::Error)]
pub enum Alpha3Error {
#[error("generic error in ffi")]
Generic,
}
#[derive(Debug, thiserror::Error)]
pub enum CalculateFeeError {
#[error("missing transaction output: {out_points:?}")]
MissingTxOut { out_points: Vec<OutPoint> },
#[error("negative fee value: {fee}")]
NegativeFee { fee: i64 },
}
#[derive(Debug, thiserror::Error)]
pub enum WalletCreationError {
// Errors coming from the FileError enum
#[error("io error trying to read file: {e}")]
Io { e: String },
#[error("file has invalid magic bytes: expected={expected:?} got={got:?}")]
InvalidMagicBytes { got: Vec<u8>, expected: Vec<u8> },
// Errors coming from the NewOrLoadError enum
#[error("error with descriptor")]
Descriptor,
#[error("failed to write to persistence")]
Write,
#[error("failed to load from persistence")]
Load,
#[error("wallet is not initialized, persistence backend is empty")]
NotInitialized,
#[error("loaded genesis hash does not match the expected one")]
LoadedGenesisDoesNotMatch,
#[error("loaded network type is not {expected}, got {got:?}")]
LoadedNetworkDoesNotMatch {
expected: Network,
got: Option<Network>,
},
}
#[derive(Debug, thiserror::Error)]
pub enum EsploraError {
#[error("ureq error: {error_message}")]
Ureq { error_message: String },
#[error("ureq transport error: {error_message}")]
UreqTransport { error_message: String },
#[error("http error with status code: {status_code}")]
Http { status_code: u16 },
#[error("io error: {error_message}")]
Io { error_message: String },
#[error("no header found in the response")]
NoHeader,
#[error("parsing error: {error_message}")]
Parsing { error_message: String },
#[error("bitcoin encoding error: {error_message}")]
BitcoinEncoding { error_message: String },
#[error("hex decoding error: {error_message}")]
Hex { error_message: String },
#[error("transaction not found")]
TransactionNotFound,
#[error("header height {height} not found")]
HeaderHeightNotFound { height: u32 },
#[error("header hash not found")]
HeaderHashNotFound,
}
impl From<BdkFileError> for WalletCreationError {
fn from(error: BdkFileError) -> Self {
match error {
BdkFileError::Io(e) => WalletCreationError::Io { e: e.to_string() },
BdkFileError::InvalidMagicBytes { got, expected } => {
WalletCreationError::InvalidMagicBytes { got, expected }
}
}
}
}
impl From<NewOrLoadError<std::io::Error, IterError>> for WalletCreationError {
fn from(error: NewOrLoadError<std::io::Error, IterError>) -> Self {
match error {
NewOrLoadError::Descriptor(_) => WalletCreationError::Descriptor,
NewOrLoadError::Write(_) => WalletCreationError::Write,
NewOrLoadError::Load(_) => WalletCreationError::Load,
NewOrLoadError::NotInitialized => WalletCreationError::NotInitialized,
NewOrLoadError::LoadedGenesisDoesNotMatch { .. } => {
WalletCreationError::LoadedGenesisDoesNotMatch
}
NewOrLoadError::LoadedNetworkDoesNotMatch { expected, got } => {
WalletCreationError::LoadedNetworkDoesNotMatch { expected, got }
}
}
}
}
impl From<DescriptorError> for Alpha3Error {
fn from(_: DescriptorError) -> Self {
Alpha3Error::Generic
}
}
impl From<AllowShrinkingError> for Alpha3Error {
fn from(_: AllowShrinkingError) -> Self {
Alpha3Error::Generic
}
}
impl From<BuildFeeBumpError> for Alpha3Error {
fn from(_: BuildFeeBumpError) -> Self {
Alpha3Error::Generic
}
}
impl From<CreateTxError<Infallible>> for Alpha3Error {
fn from(_: CreateTxError<Infallible>) -> Self {
Alpha3Error::Generic
}
}
impl From<AddUtxoError> for Alpha3Error {
fn from(_: AddUtxoError) -> Self {
Alpha3Error::Generic
}
}
impl From<bdk::bitcoin::bip32::Error> for Alpha3Error {
fn from(_: bdk::bitcoin::bip32::Error) -> Self {
Alpha3Error::Generic
}
}
impl From<NewError<std::io::Error>> for Alpha3Error {
fn from(_: NewError<std::io::Error>) -> Self {
Alpha3Error::Generic
}
}
impl From<CreateTxError<std::io::Error>> for Alpha3Error {
fn from(_: CreateTxError<std::io::Error>) -> Self {
Alpha3Error::Generic
}
}
impl From<BdkCalculateFeeError> for CalculateFeeError {
fn from(error: BdkCalculateFeeError) -> Self {
match error {
BdkCalculateFeeError::MissingTxOut(out_points) => CalculateFeeError::MissingTxOut {
out_points: out_points.iter().map(|op| op.into()).collect(),
},
BdkCalculateFeeError::NegativeFee(fee) => CalculateFeeError::NegativeFee { fee },
}
}
}
impl From<BdkEsploraError> for EsploraError {
fn from(error: BdkEsploraError) -> Self {
match error {
BdkEsploraError::Ureq(e) => EsploraError::Ureq {
error_message: e.to_string(),
},
BdkEsploraError::UreqTransport(e) => EsploraError::UreqTransport {
error_message: e.to_string(),
},
BdkEsploraError::HttpResponse(code) => EsploraError::Http { status_code: code },
BdkEsploraError::Io(e) => EsploraError::Io {
error_message: e.to_string(),
},
BdkEsploraError::NoHeader => EsploraError::NoHeader,
BdkEsploraError::Parsing(e) => EsploraError::Parsing {
error_message: e.to_string(),
},
BdkEsploraError::BitcoinEncoding(e) => EsploraError::BitcoinEncoding {
error_message: e.to_string(),
},
BdkEsploraError::Hex(e) => EsploraError::Hex {
error_message: e.to_string(),
},
BdkEsploraError::TransactionNotFound(_) => EsploraError::TransactionNotFound,
BdkEsploraError::HeaderHeightNotFound(height) => {
EsploraError::HeaderHeightNotFound { height }
}
BdkEsploraError::HeaderHashNotFound(_) => EsploraError::HeaderHashNotFound,
}
}
}
#[cfg(test)]
mod test {
use crate::error::EsploraError;
use crate::CalculateFeeError;
use crate::OutPoint;
#[test]
fn test_error_missing_tx_out() {
let out_points: Vec<OutPoint> = vec![
OutPoint {
txid: "0000000000000000000000000000000000000000000000000000000000000001"
.to_string(),
vout: 0,
},
OutPoint {
txid: "0000000000000000000000000000000000000000000000000000000000000002"
.to_string(),
vout: 1,
},
];
let error = CalculateFeeError::MissingTxOut { out_points };
let expected_message: String = format!(
"missing transaction output: [{:?}, {:?}]",
OutPoint {
txid: "0000000000000000000000000000000000000000000000000000000000000001"
.to_string(),
vout: 0
},
OutPoint {
txid: "0000000000000000000000000000000000000000000000000000000000000002"
.to_string(),
vout: 1
}
);
assert_eq!(error.to_string(), expected_message);
}
#[test]
fn test_error_negative_fee() {
let error = CalculateFeeError::NegativeFee { fee: -100 };
assert_eq!(error.to_string(), "negative fee value: -100");
}
#[test]
fn test_esplora_errors() {
let cases = vec![
(
EsploraError::Ureq {
error_message: "Network error".to_string(),
},
"ureq error: Network error",
),
(
EsploraError::UreqTransport {
error_message: "Timeout occurred".to_string(),
},
"ureq transport error: Timeout occurred",
),
(
EsploraError::Http { status_code: 404 },
"http error with status code: 404",
),
(
EsploraError::Io {
error_message: "File not found".to_string(),
},
"io error: File not found",
),
(EsploraError::NoHeader, "no header found in the response"),
(
EsploraError::Parsing {
error_message: "Invalid JSON".to_string(),
},
"parsing error: Invalid JSON",
),
(
EsploraError::BitcoinEncoding {
error_message: "Bad format".to_string(),
},
"bitcoin encoding error: Bad format",
),
(
EsploraError::Hex {
error_message: "Invalid hex".to_string(),
},
"hex decoding error: Invalid hex",
),
(EsploraError::TransactionNotFound, "transaction not found"),
(
EsploraError::HeaderHeightNotFound { height: 123456 },
"header height 123456 not found",
),
(EsploraError::HeaderHashNotFound, "header hash not found"),
];
for (error, expected_message) in cases {
assert_eq!(error.to_string(), expected_message);
}
}
}

View File

@@ -1,12 +1,11 @@
use crate::error::{Alpha3Error, EsploraError};
use crate::wallet::{Update, Wallet};
use std::ops::Deref;
use bdk::bitcoin::Transaction as BdkTransaction;
use bdk::wallet::Update as BdkUpdate;
use bdk::Error as BdkError;
use bdk_esplora::esplora_client::{BlockingClient, Builder};
use bdk_esplora::EsploraExt;
use crate::bitcoin::Transaction;
use std::sync::Arc;
pub struct EsploraClient(BlockingClient);
@@ -19,27 +18,33 @@ impl EsploraClient {
// This is a temporary solution for scanning. The long-term solution involves not passing
// the wallet to the client at all.
pub fn full_scan(
pub fn scan(
&self,
wallet: Arc<Wallet>,
stop_gap: u64,
parallel_requests: u64,
) -> Result<Arc<Update>, EsploraError> {
) -> Result<Arc<Update>, BdkError> {
let wallet = wallet.get_wallet();
let previous_tip = wallet.latest_checkpoint();
let keychain_spks = wallet.all_unbounded_spk_iters().into_iter().collect();
let keychain_spks = wallet.spks_of_all_keychains().into_iter().collect();
let (update_graph, last_active_indices) = self
.0
.full_scan(keychain_spks, stop_gap as usize, parallel_requests as usize)
.map_err(|e| EsploraError::from(*e))?;
.scan_txs_with_keychains(
keychain_spks,
None,
None,
stop_gap as usize,
parallel_requests as usize,
)
.unwrap();
let missing_heights = update_graph.missing_heights(wallet.local_chain());
let chain_update = self
.0
.update_local_chain(previous_tip, missing_heights)
.map_err(|e| EsploraError::from(*e))?;
.unwrap();
let update = BdkUpdate {
last_active_indices,
@@ -52,11 +57,11 @@ impl EsploraClient {
// pub fn sync();
pub fn broadcast(&self, transaction: &Transaction) -> Result<(), Alpha3Error> {
let bdk_transaction: BdkTransaction = transaction.into();
pub fn broadcast(&self, transaction: Arc<crate::bitcoin::Transaction>) -> Result<(), BdkError> {
let bdk_transaction: bdk::bitcoin::Transaction = transaction.deref().clone().into();
self.0
.broadcast(&bdk_transaction)
.map_err(|_| Alpha3Error::Generic)
.map_err(|e| BdkError::Generic(e.to_string()))
}
// pub fn estimate_fee();

View File

@@ -1,10 +1,9 @@
use crate::error::Alpha3Error;
use crate::Network;
use bdk::bitcoin::bip32::DerivationPath as BdkDerivationPath;
use bdk::bitcoin::key::Secp256k1;
use bdk::bitcoin::secp256k1::rand;
use bdk::bitcoin::secp256k1::rand::Rng;
use bdk::bitcoin::Network;
use bdk::keys::bip39::WordCount;
use bdk::keys::bip39::{Language, Mnemonic as BdkMnemonic};
use bdk::keys::{
@@ -13,16 +12,20 @@ use bdk::keys::{
};
use bdk::miniscript::descriptor::{DescriptorXKey, Wildcard};
use bdk::miniscript::BareCtx;
use bdk::Error as BdkError;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
/// Mnemonic phrases are a human-readable version of the private keys.
/// Supported number of words are 12, 15, 18, 21 and 24.
pub(crate) struct Mnemonic {
inner: BdkMnemonic,
}
impl Mnemonic {
/// Generates Mnemonic with a random entropy
pub(crate) fn new(word_count: WordCount) -> Self {
// TODO 4: I DON'T KNOW IF THIS IS A DECENT WAY TO GENERATE ENTROPY PLEASE CONFIRM
let mut rng = rand::thread_rng();
@@ -35,18 +38,22 @@ impl Mnemonic {
Mnemonic { inner: mnemonic }
}
pub(crate) fn from_string(mnemonic: String) -> Result<Self, Alpha3Error> {
/// Parse a Mnemonic with given string
pub(crate) fn from_string(mnemonic: String) -> Result<Self, BdkError> {
BdkMnemonic::from_str(&mnemonic)
.map(|m| Mnemonic { inner: m })
.map_err(|_| Alpha3Error::Generic)
.map_err(|e| BdkError::Generic(e.to_string()))
}
pub(crate) fn from_entropy(entropy: Vec<u8>) -> Result<Self, Alpha3Error> {
/// Create a new Mnemonic in the specified language from the given entropy.
/// Entropy must be a multiple of 32 bits (4 bytes) and 128-256 bits in length.
pub(crate) fn from_entropy(entropy: Vec<u8>) -> Result<Self, BdkError> {
BdkMnemonic::from_entropy(entropy.as_slice())
.map(|m| Mnemonic { inner: m })
.map_err(|_| Alpha3Error::Generic)
.map_err(|e| BdkError::Generic(e.to_string()))
}
/// Returns Mnemonic as string
pub(crate) fn as_string(&self) -> String {
self.inner.to_string()
}
@@ -57,12 +64,12 @@ pub(crate) struct DerivationPath {
}
impl DerivationPath {
pub(crate) fn new(path: String) -> Result<Self, Alpha3Error> {
pub(crate) fn new(path: String) -> Result<Self, BdkError> {
BdkDerivationPath::from_str(&path)
.map(|x| DerivationPath {
inner_mutex: Mutex::new(x),
})
.map_err(|_| Alpha3Error::Generic)
.map_err(|e| BdkError::Generic(e.to_string()))
}
}
@@ -72,12 +79,12 @@ pub struct DescriptorSecretKey {
}
impl DescriptorSecretKey {
pub(crate) fn new(network: Network, mnemonic: &Mnemonic, password: Option<String>) -> Self {
pub(crate) fn new(network: Network, mnemonic: Arc<Mnemonic>, password: Option<String>) -> Self {
let mnemonic = mnemonic.inner.clone();
let xkey: ExtendedKey = (mnemonic, password).into_extended_key().unwrap();
let descriptor_secret_key = BdkDescriptorSecretKey::XPrv(DescriptorXKey {
origin: None,
xkey: xkey.into_xprv(network).unwrap(),
xkey: xkey.into_xprv(network.into()).unwrap(),
derivation_path: BdkDerivationPath::master(),
wildcard: Wildcard::Unhardened,
});
@@ -86,20 +93,22 @@ impl DescriptorSecretKey {
}
}
pub(crate) fn from_string(private_key: String) -> Result<Self, Alpha3Error> {
pub(crate) fn from_string(private_key: String) -> Result<Self, BdkError> {
let descriptor_secret_key = BdkDescriptorSecretKey::from_str(private_key.as_str())
.map_err(|_| Alpha3Error::Generic)?;
.map_err(|e| BdkError::Generic(e.to_string()))?;
Ok(Self {
inner: descriptor_secret_key,
})
}
pub(crate) fn derive(&self, path: &DerivationPath) -> Result<Arc<Self>, Alpha3Error> {
pub(crate) fn derive(&self, path: Arc<DerivationPath>) -> Result<Arc<Self>, BdkError> {
let secp = Secp256k1::new();
let descriptor_secret_key = &self.inner;
let path = path.inner_mutex.lock().unwrap().deref().clone();
match descriptor_secret_key {
BdkDescriptorSecretKey::Single(_) => Err(Alpha3Error::Generic),
BdkDescriptorSecretKey::Single(_) => Err(BdkError::Generic(
"Cannot derive from a single key".to_string(),
)),
BdkDescriptorSecretKey::XPrv(descriptor_x_key) => {
let derived_xprv = descriptor_x_key.xkey.derive_priv(&secp, &path)?;
let key_source = match descriptor_x_key.origin.clone() {
@@ -116,15 +125,19 @@ impl DescriptorSecretKey {
inner: derived_descriptor_secret_key,
}))
}
BdkDescriptorSecretKey::MultiXPrv(_) => Err(Alpha3Error::Generic),
BdkDescriptorSecretKey::MultiXPrv(_) => Err(BdkError::Generic(
"Cannot derive from a multi key".to_string(),
)),
}
}
pub(crate) fn extend(&self, path: &DerivationPath) -> Result<Arc<Self>, Alpha3Error> {
pub(crate) fn extend(&self, path: Arc<DerivationPath>) -> Result<Arc<Self>, BdkError> {
let descriptor_secret_key = &self.inner;
let path = path.inner_mutex.lock().unwrap().deref().clone();
match descriptor_secret_key {
BdkDescriptorSecretKey::Single(_) => Err(Alpha3Error::Generic),
BdkDescriptorSecretKey::Single(_) => Err(BdkError::Generic(
"Cannot extend from a single key".to_string(),
)),
BdkDescriptorSecretKey::XPrv(descriptor_x_key) => {
let extended_path = descriptor_x_key.derivation_path.extend(path);
let extended_descriptor_secret_key = BdkDescriptorSecretKey::XPrv(DescriptorXKey {
@@ -137,7 +150,9 @@ impl DescriptorSecretKey {
inner: extended_descriptor_secret_key,
}))
}
BdkDescriptorSecretKey::MultiXPrv(_) => Err(Alpha3Error::Generic),
BdkDescriptorSecretKey::MultiXPrv(_) => Err(BdkError::Generic(
"Cannot derive from a multi key".to_string(),
)),
}
}
@@ -149,6 +164,7 @@ impl DescriptorSecretKey {
})
}
/// Get the private key as bytes.
pub(crate) fn secret_bytes(&self) -> Vec<u8> {
let inner = &self.inner;
let secret_bytes: Vec<u8> = match inner {
@@ -177,21 +193,23 @@ pub struct DescriptorPublicKey {
}
impl DescriptorPublicKey {
pub(crate) fn from_string(public_key: String) -> Result<Self, Alpha3Error> {
pub(crate) fn from_string(public_key: String) -> Result<Self, BdkError> {
let descriptor_public_key = BdkDescriptorPublicKey::from_str(public_key.as_str())
.map_err(|_| Alpha3Error::Generic)?;
.map_err(|e| BdkError::Generic(e.to_string()))?;
Ok(Self {
inner: descriptor_public_key,
})
}
pub(crate) fn derive(&self, path: &DerivationPath) -> Result<Arc<Self>, Alpha3Error> {
pub(crate) fn derive(&self, path: Arc<DerivationPath>) -> Result<Arc<Self>, BdkError> {
let secp = Secp256k1::new();
let descriptor_public_key = &self.inner;
let path = path.inner_mutex.lock().unwrap().deref().clone();
match descriptor_public_key {
BdkDescriptorPublicKey::Single(_) => Err(Alpha3Error::Generic),
BdkDescriptorPublicKey::Single(_) => Err(BdkError::Generic(
"Cannot derive from a single key".to_string(),
)),
BdkDescriptorPublicKey::XPub(descriptor_x_key) => {
let derived_xpub = descriptor_x_key.xkey.derive_pub(&secp, &path)?;
let key_source = match descriptor_x_key.origin.clone() {
@@ -208,15 +226,19 @@ impl DescriptorPublicKey {
inner: derived_descriptor_public_key,
}))
}
BdkDescriptorPublicKey::MultiXPub(_) => Err(Alpha3Error::Generic),
BdkDescriptorPublicKey::MultiXPub(_) => Err(BdkError::Generic(
"Cannot derive from a multi xpub".to_string(),
)),
}
}
pub(crate) fn extend(&self, path: &DerivationPath) -> Result<Arc<Self>, Alpha3Error> {
pub(crate) fn extend(&self, path: Arc<DerivationPath>) -> Result<Arc<Self>, BdkError> {
let descriptor_public_key = &self.inner;
let path = path.inner_mutex.lock().unwrap().deref().clone();
match descriptor_public_key {
BdkDescriptorPublicKey::Single(_) => Err(Alpha3Error::Generic),
BdkDescriptorPublicKey::Single(_) => Err(BdkError::Generic(
"Cannot extend from a single key".to_string(),
)),
BdkDescriptorPublicKey::XPub(descriptor_x_key) => {
let extended_path = descriptor_x_key.derivation_path.extend(path);
let extended_descriptor_public_key = BdkDescriptorPublicKey::XPub(DescriptorXKey {
@@ -229,7 +251,9 @@ impl DescriptorPublicKey {
inner: extended_descriptor_public_key,
}))
}
BdkDescriptorPublicKey::MultiXPub(_) => Err(Alpha3Error::Generic),
BdkDescriptorPublicKey::MultiXPub(_) => Err(BdkError::Generic(
"Cannot derive from a multi xpub".to_string(),
)),
}
}
@@ -237,50 +261,53 @@ impl DescriptorPublicKey {
self.inner.to_string()
}
}
//
// // The goal of these tests to to ensure `bdk-ffi` intermediate code correctly calls `bdk` APIs.
// // These tests should not be used to verify `bdk` behavior that is already tested in the `bdk`
// // crate.
#[cfg(test)]
mod test {
use crate::keys::{DerivationPath, DescriptorPublicKey, DescriptorSecretKey, Mnemonic};
use crate::BdkError;
// use bdk::bitcoin::hashes::hex::ToHex;
use crate::error::Alpha3Error;
use bdk::bitcoin::Network;
use std::sync::Arc;
fn get_inner() -> DescriptorSecretKey {
let mnemonic = Mnemonic::from_string("chaos fabric time speed sponsor all flat solution wisdom trophy crack object robot pave observe combine where aware bench orient secret primary cable detect".to_string()).unwrap();
DescriptorSecretKey::new(Network::Testnet, &mnemonic, None)
DescriptorSecretKey::new(Network::Testnet.into(), Arc::new(mnemonic), None)
}
fn derive_dsk(
key: &DescriptorSecretKey,
path: &str,
) -> Result<Arc<DescriptorSecretKey>, Alpha3Error> {
let path = DerivationPath::new(path.to_string()).unwrap();
key.derive(&path)
) -> Result<Arc<DescriptorSecretKey>, BdkError> {
let path = Arc::new(DerivationPath::new(path.to_string()).unwrap());
key.derive(path)
}
fn extend_dsk(
key: &DescriptorSecretKey,
path: &str,
) -> Result<Arc<DescriptorSecretKey>, Alpha3Error> {
let path = DerivationPath::new(path.to_string()).unwrap();
key.extend(&path)
) -> Result<Arc<DescriptorSecretKey>, BdkError> {
let path = Arc::new(DerivationPath::new(path.to_string()).unwrap());
key.extend(path)
}
fn derive_dpk(
key: &DescriptorPublicKey,
path: &str,
) -> Result<Arc<DescriptorPublicKey>, Alpha3Error> {
let path = DerivationPath::new(path.to_string()).unwrap();
key.derive(&path)
) -> Result<Arc<DescriptorPublicKey>, BdkError> {
let path = Arc::new(DerivationPath::new(path.to_string()).unwrap());
key.derive(path)
}
fn extend_dpk(
key: &DescriptorPublicKey,
path: &str,
) -> Result<Arc<DescriptorPublicKey>, Alpha3Error> {
let path = DerivationPath::new(path.to_string()).unwrap();
key.extend(&path)
) -> Result<Arc<DescriptorPublicKey>, BdkError> {
let path = Arc::new(DerivationPath::new(path.to_string()).unwrap());
key.extend(path)
}
#[test]
@@ -320,7 +347,7 @@ mod test {
assert_eq!(extended_dpk.as_string(), "tpubD6NzVbkrYhZ4WywdEfYbbd62yuvqLjAZuPsNyvzCNV85JekAEMbKHWSHLF9h3j45SxewXDcLv328B1SEZrxg4iwGfmdt1pDFjZiTkGiFqGa/0/*");
let wif = "L2wTu6hQrnDMiFNWA5na6jB12ErGQqtXwqpSL7aWquJaZG8Ai3ch";
let extended_key = DescriptorSecretKey::from_string(wif.to_string()).unwrap();
let result = extended_key.derive(&DerivationPath::new("m/0".to_string()).unwrap());
let result = extended_key.derive(Arc::new(DerivationPath::new("m/0".to_string()).unwrap()));
dbg!(&result);
assert!(result.is_err());
}

View File

@@ -1,44 +1,385 @@
mod bitcoin;
mod descriptor;
mod error;
mod esplora;
mod keys;
mod types;
mod wallet;
// TODO 6: Why are these imports required?
use crate::bitcoin::Address;
use crate::bitcoin::Network;
use crate::bitcoin::OutPoint;
use crate::bitcoin::PartiallySignedTransaction;
use crate::bitcoin::Script;
use crate::bitcoin::Transaction;
use crate::bitcoin::TxOut;
use crate::descriptor::Descriptor;
use crate::error::Alpha3Error;
use crate::error::CalculateFeeError;
use crate::error::EsploraError;
use crate::esplora::EsploraClient;
use crate::keys::DerivationPath;
use crate::keys::DescriptorPublicKey;
use crate::keys::DescriptorSecretKey;
use crate::keys::Mnemonic;
use crate::types::AddressIndex;
use crate::types::AddressInfo;
use crate::types::Balance;
use crate::types::FeeRate;
use crate::types::LocalOutput;
use crate::types::ScriptAmount;
use crate::wallet::BumpFeeTxBuilder;
use crate::wallet::SentAndReceivedValues;
use crate::wallet::TxBuilder;
use crate::wallet::Update;
use crate::wallet::Wallet;
use crate::error::WalletCreationError;
use bdk::bitcoin::Network;
use bdk::keys::bip39::WordCount;
use bdk::wallet::tx_builder::ChangeSpendPolicy;
use bdk::wallet::AddressIndex as BdkAddressIndex;
use bdk::wallet::AddressInfo as BdkAddressInfo;
use bdk::wallet::Balance as BdkBalance;
use bdk::Error as BdkError;
use bdk::KeychainKind;
use std::sync::Arc;
uniffi::include_scaffolding!("bdk");
// TODO: TxIn, Payload
/// A output script and an amount of satoshis.
pub struct ScriptAmount {
pub script: Arc<Script>,
pub amount: u64,
}
/// A derived address and the index it was found at.
pub struct AddressInfo {
/// Child index of this address.
pub index: u32,
/// Address.
pub address: Arc<Address>,
/// Type of keychain.
pub keychain: KeychainKind,
}
impl From<BdkAddressInfo> for AddressInfo {
fn from(address_info: BdkAddressInfo) -> Self {
AddressInfo {
index: address_info.index,
address: Arc::new(address_info.address.into()),
keychain: address_info.keychain,
}
}
}
/// The address index selection strategy to use to derived an address from the wallet's external
/// descriptor.
pub enum AddressIndex {
/// Return a new address after incrementing the current descriptor index.
New,
/// Return the address for the current descriptor index if it has not been used in a received
/// transaction. Otherwise return a new address as with AddressIndex::New.
/// Use with caution, if the wallet has not yet detected an address has been used it could
/// return an already used address. This function is primarily meant for situations where the
/// caller is untrusted; for example when deriving donation addresses on-demand for a public
/// web page.
LastUnused,
/// Return the address for a specific descriptor index. Does not change the current descriptor
/// index used by `AddressIndex::New` and `AddressIndex::LastUsed`.
/// Use with caution, if an index is given that is less than the current descriptor index
/// then the returned address may have already been used.
Peek { index: u32 },
}
impl From<AddressIndex> for BdkAddressIndex {
fn from(address_index: AddressIndex) -> Self {
match address_index {
AddressIndex::New => BdkAddressIndex::New,
AddressIndex::LastUnused => BdkAddressIndex::LastUnused,
AddressIndex::Peek { index } => BdkAddressIndex::Peek(index),
}
}
}
// TODO 9: Peek is not correctly implemented
impl From<&AddressIndex> for BdkAddressIndex {
fn from(address_index: &AddressIndex) -> Self {
match address_index {
AddressIndex::New => BdkAddressIndex::New,
AddressIndex::LastUnused => BdkAddressIndex::LastUnused,
AddressIndex::Peek { index } => BdkAddressIndex::Peek(*index),
}
}
}
impl From<BdkAddressIndex> for AddressIndex {
fn from(address_index: BdkAddressIndex) -> Self {
match address_index {
BdkAddressIndex::New => AddressIndex::New,
BdkAddressIndex::LastUnused => AddressIndex::LastUnused,
_ => panic!("Mmmm not working"),
}
}
}
impl From<&BdkAddressIndex> for AddressIndex {
fn from(address_index: &BdkAddressIndex) -> Self {
match address_index {
BdkAddressIndex::New => AddressIndex::New,
BdkAddressIndex::LastUnused => AddressIndex::LastUnused,
_ => panic!("Mmmm not working"),
}
}
}
// /// A wallet transaction
// #[derive(Debug, Clone, PartialEq, Eq, Default)]
// pub struct TransactionDetails {
// pub transaction: Option<Arc<Transaction>>,
// /// Transaction id.
// pub txid: String,
// /// Received value (sats)
// /// Sum of owned outputs of this transaction.
// pub received: u64,
// /// Sent value (sats)
// /// Sum of owned inputs of this transaction.
// pub sent: u64,
// /// Fee value (sats) if confirmed.
// /// The availability of the fee depends on the backend. It's never None with an Electrum
// /// Server backend, but it could be None with a Bitcoin RPC node without txindex that receive
// /// funds while offline.
// pub fee: Option<u64>,
// /// If the transaction is confirmed, contains height and timestamp of the block containing the
// /// transaction, unconfirmed transaction contains `None`.
// pub confirmation_time: Option<BlockTime>,
// }
//
// impl From<BdkTransactionDetails> for TransactionDetails {
// fn from(tx_details: BdkTransactionDetails) -> Self {
// let optional_tx: Option<Arc<Transaction>> =
// tx_details.transaction.map(|tx| Arc::new(tx.into()));
//
// TransactionDetails {
// transaction: optional_tx,
// fee: tx_details.fee,
// txid: tx_details.txid.to_string(),
// received: tx_details.received,
// sent: tx_details.sent,
// confirmation_time: tx_details.confirmation_time,
// }
// }
// }
//
// /// A reference to a transaction output.
// #[derive(Clone, Debug, PartialEq, Eq, Hash)]
// pub struct OutPoint {
// /// The referenced transaction's txid.
// txid: String,
// /// The index of the referenced output in its transaction's vout.
// vout: u32,
// }
//
// impl From<&OutPoint> for BdkOutPoint {
// fn from(outpoint: &OutPoint) -> Self {
// BdkOutPoint {
// txid: Txid::from_str(&outpoint.txid).unwrap(),
// vout: outpoint.vout,
// }
// }
// }
pub struct Balance {
pub inner: BdkBalance,
}
impl Balance {
/// All coinbase outputs not yet matured.
fn immature(&self) -> u64 {
self.inner.immature
}
/// Unconfirmed UTXOs generated by a wallet tx.
fn trusted_pending(&self) -> u64 {
self.inner.trusted_pending
}
/// Unconfirmed UTXOs received from an external wallet.
fn untrusted_pending(&self) -> u64 {
self.inner.untrusted_pending
}
/// Confirmed and immediately spendable balance.
fn confirmed(&self) -> u64 {
self.inner.confirmed
}
/// Get sum of trusted_pending and confirmed coins.
fn trusted_spendable(&self) -> u64 {
self.inner.trusted_spendable()
}
/// Get the whole balance visible to the wallet.
fn total(&self) -> u64 {
self.inner.total()
}
}
// impl From<BdkBalance> for Balance {
// fn from(bdk_balance: BdkBalance) -> Self {
// Balance { inner: bdk_balance }
// }
// }
// /// A transaction output, which defines new coins to be created from old ones.
// #[derive(Debug, Clone)]
// pub struct TxOut {
// /// The value of the output, in satoshis.
// value: u64,
// /// The address of the output.
// script_pubkey: Arc<Script>,
// }
//
// impl From<&BdkTxOut> for TxOut {
// fn from(tx_out: &BdkTxOut) -> Self {
// TxOut {
// value: tx_out.value,
// script_pubkey: Arc::new(Script {
// inner: tx_out.script_pubkey.clone(),
// }),
// }
// }
// }
//
// pub struct LocalUtxo {
// outpoint: OutPoint,
// txout: TxOut,
// keychain: KeychainKind,
// is_spent: bool,
// }
//
// impl From<BdkLocalUtxo> for LocalUtxo {
// fn from(local_utxo: BdkLocalUtxo) -> Self {
// LocalUtxo {
// outpoint: OutPoint {
// txid: local_utxo.outpoint.txid.to_string(),
// vout: local_utxo.outpoint.vout,
// },
// txout: TxOut {
// value: local_utxo.txout.value,
// script_pubkey: Arc::new(Script {
// inner: local_utxo.txout.script_pubkey,
// }),
// },
// keychain: local_utxo.keychain,
// is_spent: local_utxo.is_spent,
// }
// }
// }
//
// /// Trait that logs at level INFO every update received (if any).
// pub trait Progress: Send + Sync + 'static {
// /// Send a new progress update. The progress value should be in the range 0.0 - 100.0, and the message value is an
// /// optional text message that can be displayed to the user.
// 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<(), BdkError> {
// self.progress.update(progress, message);
// Ok(())
// }
// }
//
// impl Debug for ProgressHolder {
// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// f.debug_struct("ProgressHolder").finish_non_exhaustive()
// }
// }
//
// #[derive(Debug, Clone)]
// pub struct TxIn {
// pub previous_output: OutPoint,
// pub script_sig: Arc<Script>,
// pub sequence: u32,
// pub witness: Vec<Vec<u8>>,
// }
//
// impl From<&BdkTxIn> for TxIn {
// fn from(tx_in: &BdkTxIn) -> Self {
// TxIn {
// previous_output: OutPoint {
// txid: tx_in.previous_output.txid.to_string(),
// vout: tx_in.previous_output.vout,
// },
// script_sig: Arc::new(Script {
// inner: tx_in.script_sig.clone(),
// }),
// sequence: tx_in.sequence.0,
// witness: tx_in.witness.to_vec(),
// }
// }
// }
// /// The method used to produce an address.
// #[derive(Debug)]
// pub enum Payload {
// /// P2PKH address.
// PubkeyHash { pubkey_hash: Vec<u8> },
// /// P2SH address.
// ScriptHash { script_hash: Vec<u8> },
// /// Segwit address.
// WitnessProgram {
// /// The witness program version.
// version: WitnessVersion,
// /// The witness program.
// program: Vec<u8>,
// },
// }
// impl From<BdkScript> for Script {
// fn from(bdk_script: BdkScript) -> Self {
// Script { inner: bdk_script }
// }
// }
//
// #[derive(Clone, Debug)]
// enum RbfValue {
// Default,
// Value(u32),
// }
//
// /// The result after calling the TxBuilder finish() function. Contains unsigned PSBT and
// /// transaction details.
// pub struct TxBuilderResult {
// pub(crate) psbt: Arc<PartiallySignedTransaction>,
// pub transaction_details: TransactionDetails,
// }
//
// uniffi::deps::static_assertions::assert_impl_all!(Wallet: Sync, Send);
//
// // The goal of these tests to to ensure `bdk-ffi` intermediate code correctly calls `bdk` APIs.
// // These tests should not be used to verify `bdk` behavior that is already tested in the `bdk`
// // crate.
// #[cfg(test)]
// mod test {
// use super::Transaction;
// use crate::Network::Regtest;
// use crate::{Address, Payload};
// use assert_matches::assert_matches;
// use bdk::bitcoin::hashes::hex::FromHex;
// use bdk::bitcoin::util::address::WitnessVersion;
//
// // Verify that bdk-ffi Transaction can be created from valid bytes and serialized back into the same bytes.
// #[test]
// fn test_transaction_serde() {
// let test_tx_bytes = Vec::from_hex("020000000001031cfbc8f54fbfa4a33a30068841371f80dbfe166211242213188428f437445c91000000006a47304402206fbcec8d2d2e740d824d3d36cc345b37d9f65d665a99f5bd5c9e8d42270a03a8022013959632492332200c2908459547bf8dbf97c65ab1a28dec377d6f1d41d3d63e012103d7279dfb90ce17fe139ba60a7c41ddf605b25e1c07a4ddcb9dfef4e7d6710f48feffffff476222484f5e35b3f0e43f65fc76e21d8be7818dd6a989c160b1e5039b7835fc00000000171600140914414d3c94af70ac7e25407b0689e0baa10c77feffffffa83d954a62568bbc99cc644c62eb7383d7c2a2563041a0aeb891a6a4055895570000000017160014795d04cc2d4f31480d9a3710993fbd80d04301dffeffffff06fef72f000000000017a91476fd7035cd26f1a32a5ab979e056713aac25796887a5000f00000000001976a914b8332d502a529571c6af4be66399cd33379071c588ac3fda0500000000001976a914fc1d692f8de10ae33295f090bea5fe49527d975c88ac522e1b00000000001976a914808406b54d1044c429ac54c0e189b0d8061667e088ac6eb68501000000001976a914dfab6085f3a8fb3e6710206a5a959313c5618f4d88acbba20000000000001976a914eb3026552d7e3f3073457d0bee5d4757de48160d88ac0002483045022100bee24b63212939d33d513e767bc79300051f7a0d433c3fcf1e0e3bf03b9eb1d70220588dc45a9ce3a939103b4459ce47500b64e23ab118dfc03c9caa7d6bfc32b9c601210354fd80328da0f9ae6eef2b3a81f74f9a6f66761fadf96f1d1d22b1fd6845876402483045022100e29c7e3a5efc10da6269e5fc20b6a1cb8beb92130cc52c67e46ef40aaa5cac5f0220644dd1b049727d991aece98a105563416e10a5ac4221abac7d16931842d5c322012103960b87412d6e169f30e12106bdf70122aabb9eb61f455518322a18b920a4dfa887d30700").unwrap();
// let new_tx_from_bytes = Transaction::new(test_tx_bytes.clone()).unwrap();
// let serialized_tx_to_bytes = new_tx_from_bytes.serialize();
// assert_eq!(test_tx_bytes, serialized_tx_to_bytes);
// }
//
// // Verify that bdk-ffi Address.payload includes expected WitnessProgram variant, version and program bytes.
// #[test]
// fn test_address_witness_program() {
// let address =
// Address::new("bcrt1qqjn9gky9mkrm3c28e5e87t5akd3twg6xezp0tv".to_string()).unwrap();
// let payload = address.payload();
// assert_matches!(payload, Payload::WitnessProgram { version, program } => {
// assert_eq!(version,WitnessVersion::V0);
// assert_eq!(program, Vec::from_hex("04a6545885dd87b8e147cd327f2e9db362b72346").unwrap());
// });
// assert_eq!(address.network(), Regtest);
// }
// }

View File

@@ -1,147 +0,0 @@
use crate::bitcoin::{Address, OutPoint, Script, TxOut};
use bdk::wallet::AddressIndex as BdkAddressIndex;
use bdk::wallet::AddressInfo as BdkAddressInfo;
use bdk::wallet::Balance as BdkBalance;
use bdk::KeychainKind;
use bdk::LocalOutput as BdkLocalOutput;
use bdk::FeeRate as BdkFeeRate;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct FeeRate(pub BdkFeeRate);
impl FeeRate {
pub fn from_sat_per_vb(sat_per_vb: f32) -> Self {
FeeRate(BdkFeeRate::from_sat_per_vb(sat_per_vb))
}
pub fn from_sat_per_kwu(sat_per_kwu: f32) -> Self {
FeeRate(BdkFeeRate::from_sat_per_kwu(sat_per_kwu))
}
pub fn as_sat_per_vb(&self) -> f32 {
self.0.as_sat_per_vb()
}
pub fn sat_per_kwu(&self) -> f32 {
self.0.sat_per_kwu()
}
}
pub struct ScriptAmount {
pub script: Arc<Script>,
pub amount: u64,
}
pub struct AddressInfo {
pub index: u32,
pub address: Arc<Address>,
pub keychain: KeychainKind,
}
impl From<BdkAddressInfo> for AddressInfo {
fn from(address_info: BdkAddressInfo) -> Self {
AddressInfo {
index: address_info.index,
address: Arc::new(address_info.address.into()),
keychain: address_info.keychain,
}
}
}
pub enum AddressIndex {
New,
LastUnused,
Peek { index: u32 },
}
impl From<AddressIndex> for BdkAddressIndex {
fn from(address_index: AddressIndex) -> Self {
match address_index {
AddressIndex::New => BdkAddressIndex::New,
AddressIndex::LastUnused => BdkAddressIndex::LastUnused,
AddressIndex::Peek { index } => BdkAddressIndex::Peek(index),
}
}
}
impl From<BdkAddressIndex> for AddressIndex {
fn from(address_index: BdkAddressIndex) -> Self {
match address_index {
BdkAddressIndex::New => AddressIndex::New,
BdkAddressIndex::LastUnused => AddressIndex::LastUnused,
_ => panic!("Mmmm not working"),
}
}
}
// TODO 9: Peek is not correctly implemented
impl From<&AddressIndex> for BdkAddressIndex {
fn from(address_index: &AddressIndex) -> Self {
match address_index {
AddressIndex::New => BdkAddressIndex::New,
AddressIndex::LastUnused => BdkAddressIndex::LastUnused,
AddressIndex::Peek { index } => BdkAddressIndex::Peek(*index),
}
}
}
impl From<&BdkAddressIndex> for AddressIndex {
fn from(address_index: &BdkAddressIndex) -> Self {
match address_index {
BdkAddressIndex::New => AddressIndex::New,
BdkAddressIndex::LastUnused => AddressIndex::LastUnused,
_ => panic!("Mmmm not working"),
}
}
}
pub struct Balance {
pub immature: u64,
pub trusted_pending: u64,
pub untrusted_pending: u64,
pub confirmed: u64,
pub trusted_spendable: u64,
pub total: u64,
}
impl From<BdkBalance> for Balance {
fn from(bdk_balance: BdkBalance) -> Self {
Balance {
immature: bdk_balance.immature,
trusted_pending: bdk_balance.trusted_pending,
untrusted_pending: bdk_balance.untrusted_pending,
confirmed: bdk_balance.confirmed,
trusted_spendable: bdk_balance.trusted_spendable(),
total: bdk_balance.total(),
}
}
}
pub struct LocalOutput {
pub outpoint: OutPoint,
pub txout: TxOut,
pub keychain: KeychainKind,
pub is_spent: bool,
}
impl From<BdkLocalOutput> for LocalOutput {
fn from(local_utxo: BdkLocalOutput) -> Self {
LocalOutput {
outpoint: OutPoint {
txid: local_utxo.outpoint.txid.to_string(),
vout: local_utxo.outpoint.vout,
},
txout: TxOut {
value: local_utxo.txout.value,
script_pubkey: Arc::new(Script(local_utxo.txout.script_pubkey)),
},
keychain: local_utxo.keychain,
is_spent: local_utxo.is_spent,
}
}
}

View File

@@ -1,134 +1,97 @@
use crate::bitcoin::{OutPoint, PartiallySignedTransaction, Transaction};
use crate::bitcoin::{OutPoint, PartiallySignedTransaction};
use crate::descriptor::Descriptor;
use crate::error::{Alpha3Error, CalculateFeeError, WalletCreationError};
use crate::types::ScriptAmount;
use crate::types::{Balance, FeeRate};
use crate::Script;
use crate::{AddressIndex, AddressInfo};
use crate::{AddressIndex, AddressInfo, Network, ScriptAmount};
use crate::{Balance, Script};
use std::collections::HashSet;
use bdk::bitcoin::blockdata::script::ScriptBuf as BdkScriptBuf;
use bdk::bitcoin::psbt::PartiallySignedTransaction as BdkPartiallySignedTransaction;
use bdk::bitcoin::Network;
use bdk::bitcoin::{OutPoint as BdkOutPoint, Sequence, Txid};
use bdk::wallet::tx_builder::ChangeSpendPolicy;
use bdk::wallet::{ChangeSet, Update as BdkUpdate};
use bdk::Wallet as BdkWallet;
use bdk::{FeeRate as BdkFeeRate, SignOptions};
use bdk_file_store::Store;
use bdk::bitcoin::OutPoint as BdkOutPoint;
use bdk::wallet::Update as BdkUpdate;
use bdk::{Error as BdkError, FeeRate};
use bdk::{SignOptions, Wallet as BdkWallet};
use std::collections::HashSet;
use std::str::FromStr;
use bdk::wallet::tx_builder::ChangeSpendPolicy;
use std::sync::{Arc, Mutex, MutexGuard};
const MAGIC_BYTES: &[u8] = "bdkffi".as_bytes();
#[derive(Debug)]
pub struct Wallet {
inner_mutex: Mutex<BdkWallet<Store<ChangeSet>>>,
// TODO 8: Do we really need the mutex on the wallet? Could this be an Arc?
inner_mutex: Mutex<BdkWallet>,
}
impl Wallet {
pub fn new(
pub fn new_no_persist(
descriptor: Arc<Descriptor>,
change_descriptor: Option<Arc<Descriptor>>,
persistence_backend_path: String,
network: Network,
) -> Result<Self, WalletCreationError> {
) -> Result<Self, BdkError> {
let descriptor = descriptor.as_string_private();
let change_descriptor = change_descriptor.map(|d| d.as_string_private());
let db = Store::<ChangeSet>::open_or_create_new(MAGIC_BYTES, persistence_backend_path)?;
let wallet: bdk::wallet::Wallet<Store<ChangeSet>> =
BdkWallet::new_or_load(&descriptor, change_descriptor.as_ref(), db, network)?;
let wallet =
BdkWallet::new_no_persist(&descriptor, change_descriptor.as_ref(), network.into())?;
Ok(Wallet {
inner_mutex: Mutex::new(wallet),
})
}
pub(crate) fn get_wallet(&self) -> MutexGuard<BdkWallet<Store<ChangeSet>>> {
// TODO 10: Do we need this mutex
pub(crate) fn get_wallet(&self) -> MutexGuard<BdkWallet> {
self.inner_mutex.lock().expect("wallet")
}
pub fn get_address(&self, address_index: AddressIndex) -> AddressInfo {
self.get_wallet()
.try_get_address(address_index.into())
.unwrap()
.into()
}
pub fn apply_update(&self, update: Arc<Update>) -> Result<(), Alpha3Error> {
self.get_wallet()
.apply_update(update.0.clone())
.map_err(|_| Alpha3Error::Generic)
}
// TODO: This is the fallible version of get_internal_address; should I rename it to get_internal_address?
// It's a slight change of the API, the other option is to rename the get_address to try_get_address
pub fn try_get_internal_address(
&self,
address_index: AddressIndex,
) -> Result<AddressInfo, Alpha3Error> {
self.get_wallet()
.try_get_internal_address(address_index.into())
.map_or_else(
|_| Err(Alpha3Error::Generic),
|address_info| Ok(address_info.into()),
)
self.get_wallet().get_address(address_index.into()).into()
}
pub fn network(&self) -> Network {
self.get_wallet().network()
self.get_wallet().network().into()
}
pub fn get_balance(&self) -> Balance {
let bdk_balance: bdk::wallet::Balance = self.get_wallet().get_balance();
Balance::from(bdk_balance)
pub fn get_internal_address(&self, address_index: AddressIndex) -> AddressInfo {
self.get_wallet()
.get_internal_address(address_index.into())
.into()
}
pub fn is_mine(&self, script: &Script) -> bool {
// TODO 16: Why is the Arc required here?
pub fn get_balance(&self) -> Arc<Balance> {
let bdk_balance = self.get_wallet().get_balance();
let balance = Balance { inner: bdk_balance };
Arc::new(balance)
}
pub fn apply_update(&self, update: Arc<Update>) -> Result<(), BdkError> {
self.get_wallet()
.apply_update(update.0.clone())
.map_err(|e| BdkError::Generic(e.to_string()))
}
pub fn is_mine(&self, script: Arc<Script>) -> bool {
// TODO: Both of the following lines work. Which is better?
self.get_wallet().is_mine(&script.0)
// self.get_wallet().is_mine(script.0.clone().as_script())
}
/// Sign a transaction with all the wallet's signers, in the order specified by every signer's
/// [`SignerOrdering`]. This function returns the `Result` type with an encapsulated `bool` that
/// has the value true if the PSBT was finalized, or false otherwise.
///
/// The [`SignOptions`] can be used to tweak the behavior of the software signers, and the way
/// the transaction is finalized at the end. Note that it can't be guaranteed that *every*
/// signers will follow the options, but the "software signers" (WIF keys and `xprv`) defined
/// in this library will.
pub(crate) fn sign(
&self,
psbt: Arc<PartiallySignedTransaction>,
// sign_options: Option<SignOptions>,
) -> Result<bool, Alpha3Error> {
) -> Result<bool, BdkError> {
let mut psbt = psbt.inner.lock().unwrap();
self.get_wallet()
.sign(&mut psbt, SignOptions::default())
.map_err(|_| Alpha3Error::Generic)
.map_err(|e| BdkError::Generic(e.to_string()))
}
pub fn sent_and_received(&self, tx: &Transaction) -> SentAndReceivedValues {
let (sent, received): (u64, u64) = self.get_wallet().sent_and_received(&tx.into());
SentAndReceivedValues { sent, received }
}
pub fn transactions(&self) -> Vec<Arc<Transaction>> {
self.get_wallet()
.transactions()
.map(|tx| Arc::new(tx.tx_node.tx.into()))
.collect()
}
pub fn calculate_fee(&self, tx: &Transaction) -> Result<u64, CalculateFeeError> {
self.get_wallet()
.calculate_fee(&tx.into())
.map_err(|e| e.into())
}
pub fn calculate_fee_rate(&self, tx: &Transaction) -> Result<Arc<FeeRate>, CalculateFeeError> {
self.get_wallet()
.calculate_fee_rate(&tx.into())
.map(|bdk_fee_rate| Arc::new(FeeRate(bdk_fee_rate)))
.map_err(|e| e.into())
}
}
pub struct SentAndReceivedValues {
pub sent: u64,
pub received: u64,
}
pub struct Update(pub(crate) BdkUpdate);
@@ -313,7 +276,10 @@ pub struct Update(pub(crate) BdkUpdate);
// }
// }
// }
//
/// A transaction builder.
/// After creating the TxBuilder, you set options on it until finally calling finish to consume the builder and generate the transaction.
/// Each method on the TxBuilder returns an instance of a new TxBuilder with the option set/added.
#[derive(Clone, Debug)]
pub struct TxBuilder {
pub(crate) recipients: Vec<(BdkScriptBuf, u64)>,
@@ -321,11 +287,11 @@ pub struct TxBuilder {
pub(crate) unspendable: HashSet<OutPoint>,
pub(crate) change_policy: ChangeSpendPolicy,
pub(crate) manually_selected_only: bool,
pub(crate) fee_rate: Option<FeeRate>,
pub(crate) fee_absolute: Option<u64>,
pub(crate) fee_rate: Option<f32>,
// pub(crate) fee_absolute: Option<u64>,
pub(crate) drain_wallet: bool,
pub(crate) drain_to: Option<BdkScriptBuf>,
pub(crate) rbf: Option<RbfValue>,
// pub(crate) drain_to: Option<BdkScript>,
// pub(crate) rbf: Option<RbfValue>,
// pub(crate) data: Vec<u8>,
}
@@ -338,15 +304,16 @@ impl TxBuilder {
change_policy: ChangeSpendPolicy::ChangeAllowed,
manually_selected_only: false,
fee_rate: None,
fee_absolute: None,
// fee_absolute: None,
drain_wallet: false,
drain_to: None,
rbf: None,
// drain_to: None,
// rbf: None,
// data: Vec::new(),
}
}
pub(crate) fn add_recipient(&self, script: &Script, amount: u64) -> Arc<Self> {
/// Add a recipient to the internal list.
pub(crate) fn add_recipient(&self, script: Arc<Script>, amount: u64) -> Arc<Self> {
let mut recipients: Vec<(BdkScriptBuf, u64)> = self.recipients.clone();
recipients.append(&mut vec![(script.0.clone(), amount)]);
@@ -367,6 +334,8 @@ impl TxBuilder {
})
}
/// Add a utxo to the internal list of unspendable utxos. Its important to note that the "must-be-spent"
/// utxos added with [TxBuilder.addUtxo] have priority over this. See the Rust docs of the two linked methods for more details.
pub(crate) fn add_unspendable(&self, unspendable: OutPoint) -> Arc<Self> {
let mut unspendable_hash_set = self.unspendable.clone();
unspendable_hash_set.insert(unspendable);
@@ -376,17 +345,15 @@ impl TxBuilder {
})
}
pub(crate) fn unspendable(&self, unspendable: Vec<OutPoint>) -> Arc<Self> {
Arc::new(TxBuilder {
unspendable: unspendable.into_iter().collect(),
..self.clone()
})
}
/// Add an outpoint to the internal list of UTXOs that must be spent. These have priority over the "unspendable"
/// utxos, meaning that if a utxo is present both in the "utxos" and the "unspendable" list, it will be spent.
pub(crate) fn add_utxo(&self, outpoint: OutPoint) -> Arc<Self> {
self.add_utxos(vec![outpoint])
}
/// Add the list of outpoints to the internal list of UTXOs that must be spent. If an error occurs while adding
/// any of the UTXOs then none of them are added and the error is returned. These have priority over the "unspendable"
/// utxos, meaning that if a utxo is present both in the "utxos" and the "unspendable" list, it will be spent.
pub(crate) fn add_utxos(&self, mut outpoints: Vec<OutPoint>) -> Arc<Self> {
let mut utxos = self.utxos.to_vec();
utxos.append(&mut outpoints);
@@ -403,6 +370,7 @@ impl TxBuilder {
})
}
/// Do not spend change outputs. This effectively adds all the change outputs to the "unspendable" list. See TxBuilder.unspendable.
pub(crate) fn do_not_spend_change(&self) -> Arc<Self> {
Arc::new(TxBuilder {
change_policy: ChangeSpendPolicy::ChangeForbidden,
@@ -410,6 +378,7 @@ impl TxBuilder {
})
}
/// Only spend change outputs. This effectively adds all the non-change outputs to the "unspendable" list. See TxBuilder.unspendable.
pub(crate) fn only_spend_change(&self) -> Arc<Self> {
Arc::new(TxBuilder {
change_policy: ChangeSpendPolicy::OnlyChange,
@@ -417,6 +386,8 @@ impl TxBuilder {
})
}
/// Only spend utxos added by [add_utxo]. The wallet will not add additional utxos to the transaction even if they are
/// needed to make the transaction valid.
pub(crate) fn manually_selected_only(&self) -> Arc<Self> {
Arc::new(TxBuilder {
manually_selected_only: true,
@@ -424,20 +395,32 @@ impl TxBuilder {
})
}
pub(crate) fn fee_rate(&self, fee_rate: &FeeRate) -> Arc<Self> {
// /// Replace the internal list of unspendable utxos with a new list. Its important to note that the "must-be-spent" utxos added with
// /// TxBuilder.addUtxo have priority over these. See the Rust docs of the two linked methods for more details.
// pub(crate) fn unspendable(&self, unspendable: Vec<OutPoint>) -> Arc<Self> {
// Arc::new(TxBuilder {
// unspendable: unspendable.into_iter().collect(),
// ..self.clone()
// })
// }
/// Set a custom fee rate.
pub(crate) fn fee_rate(&self, sat_per_vb: f32) -> Arc<Self> {
Arc::new(TxBuilder {
fee_rate: Some(fee_rate.clone()),
fee_rate: Some(sat_per_vb),
..self.clone()
})
}
pub(crate) fn fee_absolute(&self, fee_amount: u64) -> Arc<Self> {
Arc::new(TxBuilder {
fee_absolute: Some(fee_amount),
..self.clone()
})
}
// /// Set an absolute fee.
// pub(crate) fn fee_absolute(&self, fee_amount: u64) -> Arc<Self> {
// Arc::new(TxBuilder {
// fee_absolute: Some(fee_amount),
// ..self.clone()
// })
// }
/// Spend all the available inputs. This respects filters like TxBuilder.unspendable and the change policy.
pub(crate) fn drain_wallet(&self) -> Arc<Self> {
Arc::new(TxBuilder {
drain_wallet: true,
@@ -445,26 +428,38 @@ impl TxBuilder {
})
}
pub(crate) fn drain_to(&self, script: &Script) -> Arc<Self> {
Arc::new(TxBuilder {
drain_to: Some(script.0.clone()),
..self.clone()
})
}
pub(crate) fn enable_rbf(&self) -> Arc<Self> {
Arc::new(TxBuilder {
rbf: Some(RbfValue::Default),
..self.clone()
})
}
pub(crate) fn enable_rbf_with_sequence(&self, nsequence: u32) -> Arc<Self> {
Arc::new(TxBuilder {
rbf: Some(RbfValue::Value(nsequence)),
..self.clone()
})
}
// /// Sets the address to drain excess coins to. Usually, when there are excess coins they are sent to a change address
// /// generated by the wallet. This option replaces the usual change address with an arbitrary ScriptPubKey of your choosing.
// /// Just as with a change output, if the drain output is not needed (the excess coins are too small) it will not be included
// /// in the resulting transaction. The only difference is that it is valid to use drain_to without setting any ordinary recipients
// /// with add_recipient (but it is perfectly fine to add recipients as well). If you choose not to set any recipients, you should
// /// either provide the utxos that the transaction should spend via add_utxos, or set drain_wallet to spend all of them.
// /// When bumping the fees of a transaction made with this option, you probably want to use BumpFeeTxBuilder.allow_shrinking
// /// to allow this output to be reduced to pay for the extra fees.
// pub(crate) fn drain_to(&self, script: Arc<Script>) -> Arc<Self> {
// Arc::new(TxBuilder {
// drain_to: Some(script.inner.clone()),
// ..self.clone()
// })
// }
//
// /// Enable signaling RBF. This will use the default `nsequence` value of `0xFFFFFFFD`.
// pub(crate) fn enable_rbf(&self) -> Arc<Self> {
// Arc::new(TxBuilder {
// rbf: Some(RbfValue::Default),
// ..self.clone()
// })
// }
//
// /// Enable signaling RBF with a specific nSequence value. This can cause conflicts if the wallet's descriptors contain an
// /// "older" (OP_CSV) operator and the given `nsequence` is lower than the CSV value. If the `nsequence` is higher than `0xFFFFFFFD`
// /// an error will be thrown, since it would not be a valid nSequence to signal RBF.
// pub(crate) fn enable_rbf_with_sequence(&self, nsequence: u32) -> Arc<Self> {
// Arc::new(TxBuilder {
// rbf: Some(RbfValue::Value(nsequence)),
// ..self.clone()
// })
// }
/// Add data as an output using OP_RETURN.
// pub(crate) fn add_data(&self, data: Vec<u8>) -> Arc<Self> {
@@ -474,10 +469,11 @@ impl TxBuilder {
// })
// }
/// Finish building the transaction. Returns the BIP174 PSBT.
pub(crate) fn finish(
&self,
wallet: &Arc<Wallet>,
) -> Result<Arc<PartiallySignedTransaction>, Alpha3Error> {
wallet: &Wallet,
) -> Result<Arc<PartiallySignedTransaction>, BdkError> {
// TODO: I had to change the wallet here to be mutable. Why is that now required with the 1.0 API?
let mut wallet = wallet.get_wallet();
let mut tx_builder = wallet.build_tx();
@@ -490,119 +486,134 @@ impl TxBuilder {
let utxos: &[BdkOutPoint] = &bdk_utxos;
tx_builder.add_utxos(utxos)?;
}
if !self.unspendable.is_empty() {
let bdk_unspendable: Vec<BdkOutPoint> =
self.unspendable.iter().map(BdkOutPoint::from).collect();
tx_builder.unspendable(bdk_unspendable);
}
// if !self.unspendable.is_empty() {
// let bdk_unspendable: Vec<BdkOutPoint> =
// self.unspendable.iter().map(BdkOutPoint::from).collect();
// tx_builder.unspendable(bdk_unspendable);
// }
if self.manually_selected_only {
tx_builder.manually_selected_only();
}
if let Some(fee_rate) = &self.fee_rate {
tx_builder.fee_rate(fee_rate.0);
}
if let Some(fee_amount) = self.fee_absolute {
tx_builder.fee_absolute(fee_amount);
if let Some(sat_per_vb) = self.fee_rate {
tx_builder.fee_rate(FeeRate::from_sat_per_vb(sat_per_vb));
}
// if let Some(fee_amount) = self.fee_absolute {
// tx_builder.fee_absolute(fee_amount);
// }
if self.drain_wallet {
tx_builder.drain_wallet();
}
if let Some(script) = &self.drain_to {
tx_builder.drain_to(script.clone());
}
if let Some(rbf) = &self.rbf {
match *rbf {
RbfValue::Default => {
tx_builder.enable_rbf();
}
RbfValue::Value(nsequence) => {
tx_builder.enable_rbf_with_sequence(Sequence(nsequence));
}
}
}
// if let Some(script) = &self.drain_to {
// tx_builder.drain_to(script.clone());
// }
// if let Some(rbf) = &self.rbf {
// match *rbf {
// RbfValue::Default => {
// tx_builder.enable_rbf();
// }
// RbfValue::Value(nsequence) => {
// tx_builder.enable_rbf_with_sequence(Sequence(nsequence));
// }
// }
// }
// if !&self.data.is_empty() {
// tx_builder.add_data(self.data.as_slice());
// }
// tx_builder.finish().map(|psbt| psbt.serialize_hex())
// tx_builder.finish().into()
let psbt = tx_builder.finish()?;
Ok(Arc::new(psbt.into()))
}
}
#[derive(Clone)]
pub(crate) struct BumpFeeTxBuilder {
pub(crate) txid: String,
pub(crate) fee_rate: f32,
pub(crate) allow_shrinking: Option<Arc<Script>>,
pub(crate) rbf: Option<RbfValue>,
}
impl BumpFeeTxBuilder {
pub(crate) fn new(txid: String, fee_rate: f32) -> Self {
Self {
txid,
fee_rate,
allow_shrinking: None,
rbf: None,
}
}
pub(crate) fn allow_shrinking(&self, script_pubkey: Arc<Script>) -> Arc<Self> {
Arc::new(Self {
allow_shrinking: Some(script_pubkey),
..self.clone()
})
}
pub(crate) fn enable_rbf(&self) -> Arc<Self> {
Arc::new(Self {
rbf: Some(RbfValue::Default),
..self.clone()
})
}
pub(crate) fn enable_rbf_with_sequence(&self, nsequence: u32) -> Arc<Self> {
Arc::new(Self {
rbf: Some(RbfValue::Value(nsequence)),
..self.clone()
})
}
pub(crate) fn finish(
&self,
wallet: &Wallet,
) -> Result<Arc<PartiallySignedTransaction>, Alpha3Error> {
let txid = Txid::from_str(self.txid.as_str()).map_err(|_| Alpha3Error::Generic)?;
let mut wallet = wallet.get_wallet();
let mut tx_builder = wallet.build_fee_bump(txid)?;
tx_builder.fee_rate(BdkFeeRate::from_sat_per_vb(self.fee_rate));
if let Some(allow_shrinking) = &self.allow_shrinking {
tx_builder.allow_shrinking(allow_shrinking.0.clone())?;
}
if let Some(rbf) = &self.rbf {
match *rbf {
RbfValue::Default => {
tx_builder.enable_rbf();
}
RbfValue::Value(nsequence) => {
tx_builder.enable_rbf_with_sequence(Sequence(nsequence));
}
}
}
let psbt: BdkPartiallySignedTransaction =
tx_builder.finish().map_err(|_| Alpha3Error::Generic)?;
Ok(Arc::new(psbt.into()))
}
}
#[derive(Clone, Debug)]
pub enum RbfValue {
Default,
Value(u32),
}
// /// The BumpFeeTxBuilder is used to bump the fee on a transaction that has been broadcast and has its RBF flag set to true.
// #[derive(Clone)]
// pub(crate) struct BumpFeeTxBuilder {
// pub(crate) txid: String,
// pub(crate) fee_rate: f32,
// pub(crate) allow_shrinking: Option<String>,
// pub(crate) rbf: Option<RbfValue>,
// }
//
// impl BumpFeeTxBuilder {
// pub(crate) fn new(txid: String, fee_rate: f32) -> Self {
// Self {
// txid,
// fee_rate,
// allow_shrinking: None,
// rbf: None,
// }
// }
//
// /// 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. Note that the output may shrink to below the dust limit and therefore be removed. If it is preserved
// /// then it is currently not guaranteed to be in the same position as it was originally. Returns an error if script_pubkey
// /// cant be found among the recipients of the transaction we are bumping.
// pub(crate) fn allow_shrinking(&self, address: String) -> Arc<Self> {
// Arc::new(Self {
// allow_shrinking: Some(address),
// ..self.clone()
// })
// }
//
// /// Enable signaling RBF. This will use the default `nsequence` value of `0xFFFFFFFD`.
// pub(crate) fn enable_rbf(&self) -> Arc<Self> {
// Arc::new(Self {
// rbf: Some(RbfValue::Default),
// ..self.clone()
// })
// }
//
// /// Enable signaling RBF with a specific nSequence value. This can cause conflicts if the wallet's descriptors contain an
// /// "older" (OP_CSV) operator and the given `nsequence` is lower than the CSV value. If the `nsequence` is higher than `0xFFFFFFFD`
// /// an error will be thrown, since it would not be a valid nSequence to signal RBF.
// pub(crate) fn enable_rbf_with_sequence(&self, nsequence: u32) -> Arc<Self> {
// Arc::new(Self {
// rbf: Some(RbfValue::Value(nsequence)),
// ..self.clone()
// })
// }
//
// /// Finish building the transaction. Returns the BIP174 PSBT.
// pub(crate) fn finish(
// &self,
// wallet: &Wallet,
// ) -> Result<Arc<PartiallySignedTransaction>, BdkError> {
// 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 = BdkAddress::from_str(allow_shrinking)
// .map_err(|e| BdkError::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(Sequence(nsequence));
// }
// }
// }
// tx_builder
// .finish()
// .map(|(psbt, _)| PartiallySignedTransaction {
// inner: Mutex::new(psbt),
// })
// .map(Arc::new)
// }
// }
// // The goal of these tests to to ensure `bdk-ffi` intermediate code correctly calls `bdk` APIs.
// // These tests should not be used to verify `bdk` behavior that is already tested in the `bdk`
// // crate.
// #[cfg(test)]
// mod test {
// use crate::database::DatabaseConfig;

View File

@@ -5,7 +5,7 @@ supported bindings languages.
To skip integration tests and only run unit tests use `cargo test --lib`.
To run all tests including integration tests use `CLASSPATH=./tests/jna/jna-5.14.0.jar cargo test`.
To run all tests including integration tests use `CLASSPATH=./tests/jna/jna-5.8.0.jar cargo test`.
Before running integration tests you must install the following development tools:

Binary file not shown.

Binary file not shown.

View File

@@ -1,3 +0,0 @@
[bindings.kotlin]
android = true
android_cleaner = true

View File

@@ -22,21 +22,12 @@ import org.bitcoindevkit.*
val externalDescriptor = Descriptor("wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)", Network.TESTNET)
val internalDescriptor = Descriptor("wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/1/*)", Network.TESTNET)
val esploraClient: EsploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
val wallet: Wallet = Wallet(
descriptor = externalDescriptor,
changeDescriptor = internalDescriptor,
persistenceBackendPath = "./bdkwallet.db",
network = Network.TESTNET
)
val update = esploraClient.fullScan(
wallet = wallet,
stopGap = 10uL,
parallelRequests = 1uL
)
wallet.applyUpdate(update)
val databaseConfig = DatabaseConfig.Memory
val blockchainConfig = BlockchainConfig.Electrum(
ElectrumConfig("ssl://electrum.blockstream.info:60002", null, 5u, null, 10u, true)
)
val wallet = Wallet(externalDescriptor, internalDescriptor, Network.TESTNET, databaseConfig, blockchainConfig)
val newAddress = wallet.getAddress(AddressIndex.LastUnused)
```

View File

@@ -1,4 +1,4 @@
org.gradle.jvmargs=-Xmx1536m
android.enableJetifier=true
kotlin.code.style=official
libraryVersion=1.0.0-alpha.7
libraryVersion=1.0.0-alpha.2-rc1

View File

@@ -59,12 +59,10 @@ tasks.withType<Test> {
dependencies {
implementation(platform("org.jetbrains.kotlin:kotlin-bom"))
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7")
implementation("net.java.dev.jna:jna:5.14.0")
implementation("net.java.dev.jna:jna:5.8.0")
api("org.slf4j:slf4j-api:1.7.30")
// testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.1")
// testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.10.1")
// testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.8.2")
testImplementation("junit:junit:4.13.2")
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.8.2")
testImplementation("ch.qos.logback:logback-classic:1.2.3")
testImplementation("ch.qos.logback:logback-core:1.2.3")
}

View File

@@ -1,73 +1,29 @@
package org.bitcoindevkit
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class LiveTxBuilderTest {
private val persistenceFilePath = run {
val currentDirectory = System.getProperty("user.dir")
"$currentDirectory/bdk_persistence.db"
}
@AfterTest
fun cleanup() {
val file = File(persistenceFilePath)
if (file.exists()) {
file.delete()
}
}
@Test
fun testTxBuilder() {
val descriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)", Network.TESTNET)
val wallet = Wallet(descriptor, null, persistenceFilePath, Network.TESTNET)
val esploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
val update = esploraClient.fullScan(wallet, 10uL, 1uL)
val wallet = Wallet.newNoPersist(descriptor, null, Network.TESTNET)
val esploraClient = EsploraClient("https://mempool.space/testnet/api")
val update = esploraClient.scan(wallet, 10uL, 1uL)
wallet.applyUpdate(update)
println("Balance: ${wallet.getBalance().total}")
println("Balance: ${wallet.getBalance().total()}")
assert(wallet.getBalance().total > 0uL)
assert(wallet.getBalance().total() > 0uL)
val recipient: Address = Address("tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989", Network.TESTNET)
val psbt: PartiallySignedTransaction = TxBuilder()
.addRecipient(recipient.scriptPubkey(), 4200uL)
.feeRate(FeeRate.fromSatPerVb(2.0f))
.feeRate(2.0f)
.finish(wallet)
println(psbt.serialize())
assertTrue(psbt.serialize().startsWith("cHNi"), "PSBT should start with 'cHNi'")
}
@Test
fun complexTxBuilder() {
val externalDescriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)", Network.TESTNET)
val changeDescriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/1/*)", Network.TESTNET)
val wallet = Wallet(externalDescriptor, changeDescriptor, persistenceFilePath, Network.TESTNET)
val esploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
val update = esploraClient.fullScan(wallet, 10uL, 1uL)
wallet.applyUpdate(update)
println("Balance: ${wallet.getBalance().total}")
assert(wallet.getBalance().total > 0uL)
val recipient1: Address = Address("tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989", Network.TESTNET)
val recipient2: Address = Address("tb1qw2c3lxufxqe2x9s4rdzh65tpf4d7fssjgh8nv6", Network.TESTNET)
val allRecipients: List<ScriptAmount> = listOf(
ScriptAmount(recipient1.scriptPubkey(), 4200uL),
ScriptAmount(recipient2.scriptPubkey(), 4200uL),
)
val psbt: PartiallySignedTransaction = TxBuilder()
.setRecipients(allRecipients)
.feeRate(FeeRate.fromSatPerVb(4.0f))
.changePolicy(ChangeSpendPolicy.CHANGE_FORBIDDEN)
.enableRbf()
.finish(wallet)
wallet.sign(psbt)
assertTrue(psbt.serialize().startsWith("cHNi"), "PSBT should start with 'cHNi'")
}
}

View File

@@ -1,59 +1,34 @@
package org.bitcoindevkit
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertTrue
class LiveWalletTest {
private val persistenceFilePath = run {
val currentDirectory = System.getProperty("user.dir")
"$currentDirectory/bdk_persistence.db"
}
@AfterTest
fun cleanup() {
val file = File(persistenceFilePath)
if (file.exists()) {
file.delete()
}
}
@Test
fun testSyncedBalance() {
val descriptor: Descriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)", Network.TESTNET)
val wallet: Wallet = Wallet(descriptor, null, persistenceFilePath, Network.TESTNET)
val esploraClient: EsploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
// val esploraClient: EsploraClient = EsploraClient("https://mempool.space/testnet/api")
val wallet: Wallet = Wallet.newNoPersist(descriptor, null, Network.TESTNET)
val esploraClient: EsploraClient = EsploraClient("https://mempool.space/testnet/api")
// val esploraClient = EsploraClient("https://blockstream.info/testnet/api")
val update = esploraClient.fullScan(wallet, 10uL, 1uL)
val update = esploraClient.scan(wallet, 10uL, 1uL)
wallet.applyUpdate(update)
println("Balance: ${wallet.getBalance().total}")
println("Balance: ${wallet.getBalance().total()}")
assert(wallet.getBalance().total > 0uL)
println("Transactions count: ${wallet.transactions().count()}")
val transactions = wallet.transactions().take(3)
for (tx in transactions) {
val sentAndReceived = wallet.sentAndReceived(tx)
println("Transaction: ${tx.txid()}")
println("Sent ${sentAndReceived.sent}")
println("Received ${sentAndReceived.received}")
}
assert(wallet.getBalance().total() > 0uL)
}
@Test
fun testBroadcastTransaction() {
val descriptor = Descriptor("wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)", Network.TESTNET)
val wallet: Wallet = Wallet(descriptor, null, persistenceFilePath, Network.TESTNET)
val esploraClient = EsploraClient("https://esplora.testnet.kuutamo.cloud/")
val update = esploraClient.fullScan(wallet, 10uL, 1uL)
val wallet = Wallet.newNoPersist(descriptor, null, Network.TESTNET)
val esploraClient = EsploraClient("https://mempool.space/testnet/api")
val update = esploraClient.scan(wallet, 10uL, 1uL)
wallet.applyUpdate(update)
println("Balance: ${wallet.getBalance().total}")
println("Balance: ${wallet.getBalance().total()}")
println("New address: ${wallet.getAddress(AddressIndex.New).address.asString()}")
assert(wallet.getBalance().total > 0uL) {
assert(wallet.getBalance().total() > 0uL) {
"Wallet balance must be greater than 0! Please send funds to ${wallet.getAddress(AddressIndex.New).address} and try again."
}
@@ -61,7 +36,7 @@ class LiveWalletTest {
val psbt: PartiallySignedTransaction = TxBuilder()
.addRecipient(recipient.scriptPubkey(), 4200uL)
.feeRate(FeeRate.fromSatPerVb(2.0f))
.feeRate(2.0f)
.finish(wallet)
println(psbt.serialize())
@@ -71,14 +46,8 @@ class LiveWalletTest {
assertTrue(walletDidSign)
val tx: Transaction = psbt.extractTx()
println("Txid is: ${tx.txid()}")
val txFee: ULong = wallet.calculateFee(tx)
println("Tx fee is: ${txFee}")
val feeRate: FeeRate = wallet.calculateFeeRate(tx)
println("Tx fee rate is: ${feeRate.asSatPerVb()} sat/vB")
esploraClient.broadcast(tx)
}
}

View File

@@ -1,26 +1,10 @@
package org.bitcoindevkit
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.assertFalse
class OfflineWalletTest {
private val persistenceFilePath = run {
val currentDirectory = System.getProperty("user.dir")
"$currentDirectory/bdk_persistence.db"
}
@AfterTest
fun cleanup() {
val file = File(persistenceFilePath)
if (file.exists()) {
file.delete()
}
}
@Test
fun testDescriptorBip86() {
val mnemonic: Mnemonic = Mnemonic(WordCount.WORDS12)
@@ -36,19 +20,13 @@ class OfflineWalletTest {
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
Network.TESTNET
)
val wallet: Wallet = Wallet(
val wallet: Wallet = Wallet.newNoPersist(
descriptor,
null,
persistenceFilePath,
Network.TESTNET
)
val addressInfo: AddressInfo = wallet.getAddress(AddressIndex.New)
assertTrue(addressInfo.address.isValidForNetwork(Network.TESTNET), "Address is not valid for testnet network")
assertTrue(addressInfo.address.isValidForNetwork(Network.SIGNET), "Address is not valid for signet network")
assertFalse(addressInfo.address.isValidForNetwork(Network.REGTEST), "Address is valid for regtest network, but it shouldn't be")
assertFalse(addressInfo.address.isValidForNetwork(Network.BITCOIN), "Address is valid for bitcoin network, but it shouldn't be")
assertEquals(
expected = "tb1qzg4mckdh50nwdm9hkzq06528rsu73hjxxzem3e",
actual = addressInfo.address.asString()
@@ -61,16 +39,15 @@ class OfflineWalletTest {
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
Network.TESTNET
)
val wallet: Wallet = Wallet(
val wallet: Wallet = Wallet.newNoPersist(
descriptor,
null,
persistenceFilePath,
Network.TESTNET
)
assertEquals(
expected = 0uL,
actual = wallet.getBalance().total
actual = wallet.getBalance().total()
)
}
}

View File

@@ -13,12 +13,11 @@ pip install bdkpython
## Simple example
```python
import bdkpython as bdk
```
"""
setup(
name="bdkpython",
version="1.0.0-alpha7",
version="1.0.0a2.dev1",
description="The Python language bindings for the Bitcoin Development Kit",
long_description=LONG_DESCRIPTION,
long_description_content_type="text/markdown",

View File

@@ -1,86 +1,38 @@
import bdkpython as bdk
import unittest
import os
class LiveTxBuilderTest(unittest.TestCase):
def tearDown(self) -> None:
if os.path.exists("./bdk_persistence.db"):
os.remove("./bdk_persistence.db")
class TestLiveTxBuilder(unittest.TestCase):
def test_tx_builder(self):
descriptor: bdk.Descriptor = bdk.Descriptor(
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
bdk.Network.TESTNET
)
wallet: bdk.Wallet = bdk.Wallet(
wallet: bdk.Wallet = bdk.Wallet.new_no_persist(
descriptor,
None,
"./bdk_persistence.db",
bdk.Network.TESTNET
)
esploraClient: bdk.EsploraClient = bdk.EsploraClient(url = "https://esplora.testnet.kuutamo.cloud/")
update = esploraClient.full_scan(
esploraClient: bdk.EsploraClient = bdk.EsploraClient(url = "https://mempool.space/testnet/api")
update = esploraClient.scan(
wallet = wallet,
stop_gap = 10,
parallel_requests = 1
)
wallet.apply_update(update)
self.assertGreater(wallet.get_balance().total, 0)
self.assertGreater(wallet.get_balance().total(), 0)
recipient = bdk.Address(
address = "tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989",
network = bdk.Network.TESTNET
)
psbt = bdk.TxBuilder().add_recipient(script=recipient.script_pubkey(), amount=4200).fee_rate(fee_rate=bdk.FeeRate.from_sat_per_vb(2.0)).finish(wallet)
psbt = bdk.TxBuilder().add_recipient(script=recipient.script_pubkey(), amount=4200).fee_rate(2.0).finish(wallet)
# print(psbt.serialize())
self.assertTrue(psbt.serialize().startswith("cHNi"), "The PSBT should start with cHNi")
def complex_tx_builder(self):
descriptor: bdk.Descriptor = bdk.Descriptor(
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
bdk.Network.TESTNET
)
change_descriptor: bdk.Descriptor = bdk.Descriptor(
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/1/*)",
bdk.Network.TESTNET
)
wallet: bdk.Wallet = bdk.Wallet(
descriptor,
change_descriptor,
"./bdk_persistence.db",
bdk.Network.TESTNET
)
esploraClient: bdk.EsploraClient = bdk.EsploraClient(url = "https://esplora.testnet.kuutamo.cloud/")
update = esploraClient.full_scan(
wallet = wallet,
stop_gap = 10,
parallel_requests = 1
)
wallet.apply_update(update)
self.assertGreater(wallet.get_balance().total, 0)
recipient1 = bdk.Address(
address = "tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989",
network = bdk.Network.TESTNET
)
recipient2 = bdk.Address(
address = "tb1qw2c3lxufxqe2x9s4rdzh65tpf4d7fssjgh8nv6",
network = bdk.Network.TESTNET
)
all_recipients = list(
bdk.ScriptAmount(recipient1.script_pubkey, 4200),
bdk.ScriptAmount(recipient2.script_pubkey, 4200)
)
psbt: bdk.PartiallySignedTransaction = bdk.TxBuilder().set_recipients(all_recipients).fee_rate(fee_rate=bdk.FeeRate.from_sat_per_vb(2.0)).enable_rbf().finish(wallet)
wallet.sign(psbt)
self.assertTrue(psbt.serialize().startswith("cHNi"), "The PSBT should start with cHNi")
if __name__ == '__main__':
unittest.main()

View File

@@ -1,81 +1,60 @@
import bdkpython as bdk
import unittest
import os
class LiveWalletTest(unittest.TestCase):
def tearDown(self) -> None:
if os.path.exists("./bdk_persistence.db"):
os.remove("./bdk_persistence.db")
class TestLiveWallet(unittest.TestCase):
def test_synced_balance(self):
descriptor: bdk.Descriptor = bdk.Descriptor(
"wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)",
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
bdk.Network.TESTNET
)
wallet: bdk.Wallet = bdk.Wallet(
wallet: bdk.Wallet = bdk.Wallet.new_no_persist(
descriptor,
None,
"./bdk_persistence.db",
bdk.Network.TESTNET
)
esploraClient: bdk.EsploraClient = bdk.EsploraClient(url = "https://esplora.testnet.kuutamo.cloud/")
update = esploraClient.full_scan(
esploraClient: bdk.EsploraClient = bdk.EsploraClient(url = "https://mempool.space/testnet/api")
update = esploraClient.scan(
wallet = wallet,
stop_gap = 10,
parallel_requests = 1
)
wallet.apply_update(update)
self.assertGreater(wallet.get_balance().total, 0)
print(f"Transactions count: {len(wallet.transactions())}")
transactions = wallet.transactions()[:3]
for tx in transactions:
sent_and_received = wallet.sent_and_received(tx)
print(f"Transaction: {tx.txid()}")
print(f"Sent {sent_and_received.sent}")
print(f"Received {sent_and_received.received}")
self.assertGreater(wallet.get_balance().total(), 0)
def test_broadcast_transaction(self):
descriptor: bdk.Descriptor = bdk.Descriptor(
"wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)",
bdk.Network.TESTNET
)
wallet: bdk.Wallet = bdk.Wallet(
wallet: bdk.Wallet = bdk.Wallet.new_no_persist(
descriptor,
None,
"./bdk_persistence.db",
bdk.Network.TESTNET
)
esploraClient: bdk.EsploraClient = bdk.EsploraClient(url = "https://esplora.testnet.kuutamo.cloud/")
update = esploraClient.full_scan(
esploraClient: bdk.EsploraClient = bdk.EsploraClient(url = "https://mempool.space/testnet/api")
update = esploraClient.scan(
wallet = wallet,
stop_gap = 10,
parallel_requests = 1
)
wallet.apply_update(update)
self.assertGreater(wallet.get_balance().total, 0)
self.assertGreater(wallet.get_balance().total(), 0)
recipient = bdk.Address(
address = "tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989",
network = bdk.Network.TESTNET
)
psbt = bdk.TxBuilder().add_recipient(script=recipient.script_pubkey(), amount=4200).fee_rate(fee_rate=bdk.FeeRate.from_sat_per_vb(2.0)).finish(wallet)
psbt = bdk.TxBuilder().add_recipient(script=recipient.script_pubkey(), amount=4200).fee_rate(2.0).finish(wallet)
# print(psbt.serialize())
self.assertTrue(psbt.serialize().startswith("cHNi"), "The PSBT should start with cHNi")
walletDidSign = wallet.sign(psbt)
self.assertTrue(walletDidSign)
tx = psbt.extract_tx()
print(f"Transaction Id: {tx.txid()}")
fee = wallet.calculate_fee(tx)
print(f"Transaction Fee: {fee}")
fee_rate = wallet.calculate_fee_rate(tx)
print(f"Transaction Fee Rate: {fee_rate.as_sat_per_vb()} sat/vB")
esploraClient.broadcast(tx)

View File

@@ -1,7 +1,7 @@
import bdkpython as bdk
import unittest
class OfflineDescriptorTest(unittest.TestCase):
class TestSimpleWallet(unittest.TestCase):
def test_descriptor_bip86(self):
mnemonic: bdk.Mnemonic = bdk.Mnemonic.from_string("space echo position wrist orient erupt relief museum myself grain wisdom tumble")

View File

@@ -1,46 +1,34 @@
import bdkpython as bdk
import unittest
import os
class OfflineWalletTest(unittest.TestCase):
class TestSimpleWallet(unittest.TestCase):
def tearDown(self) -> None:
if os.path.exists("./bdk_persistence.db"):
os.remove("./bdk_persistence.db")
def test_new_address(self):
descriptor: bdk.Descriptor = bdk.Descriptor(
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
bdk.Network.TESTNET
)
wallet: Wallet = bdk.Wallet(
wallet: Wallet = bdk.Wallet.new_no_persist(
descriptor,
None,
"./bdk_persistence.db",
bdk.Network.TESTNET
)
address_info: bdk.AddressInfo = wallet.get_address(bdk.AddressIndex.NEW())
self.assertTrue(address_info.address.is_valid_for_network(bdk.Network.TESTNET), "Address is not valid for testnet network")
self.assertTrue(address_info.address.is_valid_for_network(bdk.Network.SIGNET), "Address is not valid for signet network")
self.assertFalse(address_info.address.is_valid_for_network(bdk.Network.REGTEST), "Address is valid for regtest network, but it shouldn't be")
self.assertFalse(address_info.address.is_valid_for_network(bdk.Network.BITCOIN), "Address is valid for bitcoin network, but it shouldn't be")
self.assertEqual("tb1qzg4mckdh50nwdm9hkzq06528rsu73hjxxzem3e", address_info.address.as_string())
def test_balance(self):
descriptor: bdk.Descriptor = bdk.Descriptor(
"wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
bdk.Network.TESTNET
)
wallet: bdk.Wallet = bdk.Wallet(
wallet: bdk.Wallet = bdk.Wallet.new_no_persist(
descriptor,
None,
"./bdk_persistence.db",
bdk.Network.TESTNET
)
self.assertEqual(wallet.get_balance().total, 0)
self.assertEqual(wallet.get_balance().total(), 0)
if __name__ == '__main__':
unittest.main()

View File

@@ -29,7 +29,8 @@ let package = Package(
.binaryTarget(name: "bdkFFI", path: "./bdkFFI.xcframework"),
.target(
name: "BitcoinDevKit",
dependencies: ["bdkFFI"]
dependencies: ["bdkFFI"],
swiftSettings: [.unsafeFlags(["-suppress-warnings"])]
),
.testTarget(
name: "BitcoinDevKitTests",

View File

@@ -2,99 +2,33 @@ import XCTest
@testable import BitcoinDevKit
final class LiveTxBuilderTests: XCTestCase {
var dbFilePath: URL!
override func setUpWithError() throws {
super.setUp()
let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let uniqueDbFileName = "bdk_persistence_\(UUID().uuidString).db"
dbFilePath = documentDirectory.appendingPathComponent(uniqueDbFileName)
if fileManager.fileExists(atPath: dbFilePath.path) {
try fileManager.removeItem(at: dbFilePath)
}
}
override func tearDownWithError() throws {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: dbFilePath.path) {
try fileManager.removeItem(at: dbFilePath)
}
}
func testTxBuilder() throws {
let descriptor = try Descriptor(
descriptor: "wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)",
network: Network.testnet
)
let wallet = try Wallet(
let wallet = try Wallet.newNoPersist(
descriptor: descriptor,
changeDescriptor: nil,
persistenceBackendPath: dbFilePath.path,
network: .testnet
)
let esploraClient = EsploraClient(url: "https://esplora.testnet.kuutamo.cloud/")
let update = try esploraClient.fullScan(
let esploraClient = EsploraClient(url: "https://mempool.space/testnet/api")
let update = try esploraClient.scan(
wallet: wallet,
stopGap: 10,
parallelRequests: 1
)
try wallet.applyUpdate(update: update)
XCTAssertGreaterThan(wallet.getBalance().total, UInt64(0), "Wallet must have positive balance, please add funds")
XCTAssertGreaterThan(wallet.getBalance().total(), UInt64(0), "Wallet must have positive balance, please add funds")
let recipient: Address = try Address(address: "tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989", network: .testnet)
let psbt: PartiallySignedTransaction = try TxBuilder()
.addRecipient(script: recipient.scriptPubkey(), amount: 4200)
.feeRate(feeRate: FeeRate.fromSatPerVb(satPerVb: 2.0))
.feeRate(satPerVbyte: 2.0)
.finish(wallet: wallet)
print(psbt.serialize())
XCTAssertTrue(psbt.serialize().hasPrefix("cHNi"), "PSBT should start with cHNI")
}
func testComplexTxBuilder() throws {
let descriptor = try Descriptor(
descriptor: "wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)",
network: Network.testnet
)
let changeDescriptor = try Descriptor(
descriptor: "wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/1/*)",
network: Network.testnet
)
let wallet = try Wallet(
descriptor: descriptor,
changeDescriptor: changeDescriptor,
persistenceBackendPath: dbFilePath.path,
network: .testnet
)
let esploraClient = EsploraClient(url: "https://esplora.testnet.kuutamo.cloud/")
let update = try esploraClient.fullScan(
wallet: wallet,
stopGap: 10,
parallelRequests: 1
)
try wallet.applyUpdate(update: update)
XCTAssertGreaterThan(wallet.getBalance().total, UInt64(0), "Wallet must have positive balance, please add funds")
let recipient1: Address = try Address(address: "tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989", network: .testnet)
let recipient2: Address = try Address(address: "tb1qw2c3lxufxqe2x9s4rdzh65tpf4d7fssjgh8nv6", network: .testnet)
let allRecipients: [ScriptAmount] = [
ScriptAmount(script: recipient1.scriptPubkey(), amount: 4200),
ScriptAmount(script: recipient2.scriptPubkey(), amount: 4200)
]
let psbt: PartiallySignedTransaction = try TxBuilder()
.setRecipients(recipients: allRecipients)
.feeRate(feeRate: FeeRate.fromSatPerVb(satPerVb: 4.0))
.changePolicy(changePolicy: ChangeSpendPolicy.changeForbidden)
.enableRbf()
.finish(wallet: wallet)
try! wallet.sign(psbt: psbt)
XCTAssertTrue(psbt.serialize().hasPrefix("cHNi"), "PSBT should start with cHNI")
}
}

View File

@@ -2,56 +2,25 @@ import XCTest
@testable import BitcoinDevKit
final class LiveWalletTests: XCTestCase {
var dbFilePath: URL!
override func setUpWithError() throws {
super.setUp()
let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let uniqueDbFileName = "bdk_persistence_\(UUID().uuidString).db"
dbFilePath = documentDirectory.appendingPathComponent(uniqueDbFileName)
if fileManager.fileExists(atPath: dbFilePath.path) {
try fileManager.removeItem(at: dbFilePath)
}
}
override func tearDownWithError() throws {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: dbFilePath.path) {
try fileManager.removeItem(at: dbFilePath)
}
}
func testSyncedBalance() throws {
let descriptor = try Descriptor(
descriptor: "wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)",
network: Network.testnet
)
let wallet = try Wallet(
let wallet = try Wallet.newNoPersist(
descriptor: descriptor,
changeDescriptor: nil,
persistenceBackendPath: dbFilePath.path,
network: .testnet
)
let esploraClient = EsploraClient(url: "https://esplora.testnet.kuutamo.cloud/")
let update = try esploraClient.fullScan(
let esploraClient = EsploraClient(url: "https://mempool.space/testnet/api")
let update = try esploraClient.scan(
wallet: wallet,
stopGap: 10,
parallelRequests: 1
)
try wallet.applyUpdate(update: update)
XCTAssertGreaterThan(wallet.getBalance().total, UInt64(0))
print("Transactions count: \(wallet.transactions().count)")
let transactions = wallet.transactions().prefix(3)
for tx in transactions {
let sentAndReceived = wallet.sentAndReceived(tx: tx)
print("Transaction: \(tx.txid())")
print("Sent \(sentAndReceived.sent)")
print("Received \(sentAndReceived.received)")
}
XCTAssertGreaterThan(wallet.getBalance().total(), UInt64(0))
}
func testBroadcastTransaction() throws {
@@ -59,44 +28,38 @@ final class LiveWalletTests: XCTestCase {
descriptor: "wpkh(tprv8ZgxMBicQKsPf2qfrEygW6fdYseJDDrVnDv26PH5BHdvSuG6ecCbHqLVof9yZcMoM31z9ur3tTYbSnr1WBqbGX97CbXcmp5H6qeMpyvx35B/84h/1h/0h/0/*)",
network: Network.testnet
)
let wallet = try Wallet(
let wallet = try Wallet.newNoPersist(
descriptor: descriptor,
changeDescriptor: nil,
persistenceBackendPath: dbFilePath.path,
network: .testnet
)
let esploraClient = EsploraClient(url: "https://esplora.testnet.kuutamo.cloud/")
let update = try esploraClient.fullScan(
let esploraClient = EsploraClient(url: "https://mempool.space/testnet/api")
let update = try esploraClient.scan(
wallet: wallet,
stopGap: 10,
parallelRequests: 1
)
try wallet.applyUpdate(update: update)
XCTAssertGreaterThan(wallet.getBalance().total, UInt64(0), "Wallet must have positive balance, please add funds")
print("Balance: \(wallet.getBalance().total)")
XCTAssertGreaterThan(wallet.getBalance().total(), UInt64(0), "Wallet must have positive balance, please add funds")
print("Balance: \(wallet.getBalance().total())")
let recipient: Address = try Address(address: "tb1qrnfslnrve9uncz9pzpvf83k3ukz22ljgees989", network: .testnet)
let psbt: PartiallySignedTransaction = try
TxBuilder()
.addRecipient(script: recipient.scriptPubkey(), amount: 4200)
.feeRate(feeRate: FeeRate.fromSatPerVb(satPerVb: 2.0))
.feeRate(satPerVbyte: 2.0)
.finish(wallet: wallet)
print(psbt.serialize())
XCTAssertTrue(psbt.serialize().hasPrefix("cHNi"), "PSBT should start with cHNI")
let walletDidSign: Bool = try wallet.sign(psbt: psbt)
XCTAssertTrue(walletDidSign, "Wallet did not sign transaction")
let tx: Transaction = psbt.extractTx()
print(tx.txid())
let fee: UInt64 = try wallet.calculateFee(tx: tx)
print("Transaction Fee: \(fee)")
let feeRate: FeeRate = try wallet.calculateFeeRate(tx: tx)
print("Transaction Fee Rate: \(feeRate.asSatPerVb()) sat/vB")
try esploraClient.broadcast(transaction: tx)
}
}

View File

@@ -2,49 +2,18 @@ import XCTest
@testable import BitcoinDevKit
final class OfflineWalletTests: XCTestCase {
var dbFilePath: URL!
override func setUpWithError() throws {
super.setUp()
let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let uniqueDbFileName = "bdk_persistence_\(UUID().uuidString).db"
dbFilePath = documentDirectory.appendingPathComponent(uniqueDbFileName)
if fileManager.fileExists(atPath: dbFilePath.path) {
try fileManager.removeItem(at: dbFilePath)
}
}
override func tearDownWithError() throws {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: dbFilePath.path) {
try fileManager.removeItem(at: dbFilePath)
}
}
func testNewAddress() throws {
let descriptor: Descriptor = try Descriptor(
descriptor: "wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
network: Network.testnet
)
let wallet = try Wallet(
let wallet: Wallet = try Wallet.newNoPersist(
descriptor: descriptor,
changeDescriptor: nil,
persistenceBackendPath: dbFilePath.path,
network: .testnet
)
let addressInfo: AddressInfo = wallet.getAddress(addressIndex: AddressIndex.new)
XCTAssertTrue(addressInfo.address.isValidForNetwork(network: Network.testnet),
"Address is not valid for testnet network")
XCTAssertTrue(addressInfo.address.isValidForNetwork(network: Network.signet),
"Address is not valid for signet network")
XCTAssertFalse(addressInfo.address.isValidForNetwork(network: Network.regtest),
"Address is valid for regtest network, but it shouldn't be")
XCTAssertFalse(addressInfo.address.isValidForNetwork(network: Network.bitcoin),
"Address is valid for bitcoin network, but it shouldn't be")
XCTAssertEqual(addressInfo.address.asString(), "tb1qzg4mckdh50nwdm9hkzq06528rsu73hjxxzem3e")
}
@@ -53,13 +22,12 @@ final class OfflineWalletTests: XCTestCase {
descriptor: "wpkh([c258d2e4/84h/1h/0h]tpubDDYkZojQFQjht8Tm4jsS3iuEmKjTiEGjG6KnuFNKKJb5A6ZUCUZKdvLdSDWofKi4ToRCwb9poe1XdqfUnP4jaJjCB2Zwv11ZLgSbnZSNecE/0/*)",
network: Network.testnet
)
let wallet = try Wallet(
let wallet: Wallet = try Wallet.newNoPersist(
descriptor: descriptor,
changeDescriptor: nil,
persistenceBackendPath: dbFilePath.path,
network: .testnet
)
XCTAssertEqual(wallet.getBalance().total, 0)
XCTAssertEqual(wallet.getBalance().total(), 0)
}
}

View File

@@ -16,8 +16,6 @@
</array>
<key>SupportedPlatform</key>
<string>macos</string>
<key>LSMinimumSystemVersion</key>
<string>12.0</string>
</dict>
<dict>
<key>LibraryIdentifier</key>
@@ -33,8 +31,6 @@
<string>ios</string>
<key>SupportedPlatformVariant</key>
<string>simulator</string>
<key>MinimumOSVersion</key>
<string>15.0</string>
</dict>
<dict>
<key>LibraryIdentifier</key>
@@ -47,8 +43,6 @@
</array>
<key>SupportedPlatform</key>
<string>ios</string>
<key>MinimumOSVersion</key>
<string>15.0</string>
</dict>
</array>
<key>CFBundlePackageType</key>

View File

@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>com.bitcoindevkit.bdkFFI</string>
<key>CFBundleName</key>
<string>bdkFFI</string>
<key>CFBundleVersion</key>
<string>1.0.0</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleExecutable</key>
<string>bdkFFI</string>
<key>MinimumOSVersion</key>
<string>100</string>
</dict>
</plist>

View File

@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>com.bitcoindevkit.bdkFFI</string>
<key>CFBundleName</key>
<string>bdkFFI</string>
<key>CFBundleVersion</key>
<string>1.0.0</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleExecutable</key>
<string>bdkFFI</string>
<key>MinimumOSVersion</key>
<string>15.0</string>
</dict>
</plist>

View File

@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>com.bitcoindevkit.bdkFFI</string>
<key>CFBundleName</key>
<string>bdkFFI</string>
<key>CFBundleVersion</key>
<string>1.0.0</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleExecutable</key>
<string>bdkFFI</string>
<key>LSMinimumSystemVersion</key>
<string>12.0</string>
</dict>
</plist>

View File

@@ -7,11 +7,9 @@
rustup install 1.73.0
rustup component add rust-src
rustup target add aarch64-apple-ios # iOS ARM64
rustup target add x86_64-apple-ios # iOS x86_64
rustup target add aarch64-apple-ios-sim # simulator mac M1
rustup target add aarch64-apple-darwin # mac M1
rustup target add x86_64-apple-darwin # mac x86_64
rustup target add aarch64-apple-ios x86_64-apple-ios
rustup target add aarch64-apple-ios-sim
rustup target add aarch64-apple-darwin x86_64-apple-darwin
pushd bdk-ffi
mkdir -p Sources/BitcoinDevKit

View File

@@ -1,23 +0,0 @@
# Naming convention
Producing language bindings potentially requires renaming a number of types and methods, and this document outlines the approach we have decided to take when thinking through this problem for bdk-ffi libraries.
## Context and Problem Statement
The tool we use to produce language bindings for bdk-ffi libraries is [uniffi]. While the library is powerful, it also comes with some caveats. Some of those include the inability to expose to foreign bindings Rust-specific types like tuples, and the inability to expose generics. This means that at least _some_ wrapping and transforming of certain things are required between the pure Rust code coming from the bdk library and the final language bindings in Swift, Kotlin, and Python.
With wrapping comes (a) the requirement for naming potentially new types, and (b) the ability to "wrap" behaviour that could be useful for end users. This document addresses point (a).
## Decision Drivers
Our main goals are:
1. Keep the multiple language bindings libraries maintainable.
2. Help users of bdk help each other and working with a similarly shaped API across languages.
## Decision Outcome
We decided to try and keep the names of all types the same between the Rust libraries and the bindings, and in cases where new types had to be created, to keep them in the style and spirit of the bdk and rust-bitcoin libraries.
There is so far one exception to this rule, where we renamed the `ScriptBuf` type from rust-bitcoin to `Script`. This was done because the concept of owned vs. borrowed types is strictly a Rust concept, and is not passed onto the languages bindings in any way, and therefore keeping the script type as `Script` was our preferred option in this case.
[uniffi]: https://github.com/mozilla/uniffi-rs/

View File

@@ -1,26 +0,0 @@
# Wrapping BDK APIs
Producing language bindings potentially requires wrapping a number of APIs, and this document outlines the approach we have decided to take when thinking through this problem for bdk-ffi libraries.
## Context and Problem Statement
The tool we use to produce language bindings for bdk-ffi libraries is [uniffi]. While the library is powerful, it also comes with some caveats. Some of those include the inability to expose to foreign bindings Rust-specific types like tuples, and the inability to expose generics. This means that at least _some_ wrapping and transforming of certain things are required between the pure Rust code coming from the bdk library and the final language bindings in Swift, Kotlin, and Python.
With wrapping comes (a) the requirement for naming potentially new types, and (b) the ability to "wrap" behaviour that could be useful for end users. This document addresses point (b).
## Decision Drivers
Our main goals are:
1. Keep the multiple language bindings libraries maintainable.
2. Help users of bdk help each other and working with a similarly shaped API across languages.
## Decision Outcome
There are three potential reasons for wrapping Rust BDK APIs:
1. The Rust types are not available in the target language (e.g., a function returns a tuple, which can't be returned in Swift/Kotlin)
2. Some complex functionality is available in the Rust bitcoin/miniscript/bdk ecosystem, but exposing all underlying types required for this functionality is out of scope at the time a particular feature is required
3. Some extra feature/utility might be interesting for our end-users
Our approach with the bdk-ffi libraries is to only provide wrapping for cases (1) and (2) mentioned above. If extra functionality to the BDK API would be useful, we open issues upstream and merge those in Rust first, and then expose it in our bindings. This approach favors (a) keeping the bindings libraries as thin as possible, minimizing the potential for integrating bugs at the bindings layer, and (b) keeping the API as close as we can to Rust BDK, promoting collaboration between users of BDK across languages, including with teams that use BDK in bindings (mobile) and server-side (Rust).
[uniffi]: https://github.com/mozilla/uniffi-rs/

View File

@@ -1,12 +0,0 @@
# Architectural Decision Records
This directory contains a series of Architectural Decision Records or "ADRs" for the bdk-ffi project. We're going to use it as a kind of collective memory of the decisions we've made and the path we've taken to get the project to its current point.
A good example of simple and well executed ADRs can be found on the [uniffi](https://github.com/mozilla/uniffi-rs/) project repository. See their [readme](https://github.com/mozilla/uniffi-rs/tree/main/docs/adr) and [template](https://github.com/mozilla/uniffi-rs/blob/main/docs/adr/template.md) for more information.
Some more readings on ADRs:
- https://www.ozimmer.ch/practices/2023/04/03/ADRCreation.html
- https://github.com/joelparkerhenderson/architecture-decision-record
- https://adr.github.io/
- https://betterprogramming.pub/the-ultimate-guide-to-architectural-decision-records-6d74fd3850ee
- https://www.redhat.com/architect/architecture-decision-records