Skip to content

Commit

Permalink
refactor: use rust-bitcoin types defined bitcoin-ffi
Browse files Browse the repository at this point in the history
  • Loading branch information
thunderbiscuit committed Aug 30, 2024
1 parent 9d1a276 commit e23398f
Show file tree
Hide file tree
Showing 37 changed files with 255 additions and 343 deletions.
10 changes: 9 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ xcuserdata
.idea/
.editorconfig
bdk.kt
bitcoin.kt

# Swift related
/.build
Expand All @@ -28,11 +29,18 @@ bdkFFI.xcframework.zip
bdkFFI
libbdkffi.a
bdkFFI.h
BitcoinDevKitFFI.h
BitcoinDevKit.swift
bdk.swift
.build
*.xcframework/
Info.plist
BitcoinFFI.h
Bitcoin.swift
BitcoinFFi.modulemap
bdkffi.xcframework
Sources/

# Python related
__pycache__
__pycache__
bitcoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
import kotlin.test.AfterTest
import kotlin.test.assertTrue
import java.io.File
import org.rustbitcoin.bitcoin.Network
import org.rustbitcoin.bitcoin.Amount
import org.rustbitcoin.bitcoin.FeeRate

private const val SIGNET_ESPLORA_URL = "http://signet.bitcoindevkit.net"
private const val TESTNET_ESPLORA_URL = "https://esplora.testnet.kuutamo.cloud"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ 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
import java.io.File
import org.rustbitcoin.bitcoin.Network
import org.rustbitcoin.bitcoin.Amount
import org.rustbitcoin.bitcoin.FeeRate

private const val SIGNET_ESPLORA_URL = "http://signet.bitcoindevkit.net"
private const val TESTNET_ESPLORA_URL = "https://esplora.testnet.kuutamo.cloud"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 org.rustbitcoin.bitcoin.Network

@RunWith(AndroidJUnit4::class)
class OfflineDescriptorTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ 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
import java.io.File
import org.rustbitcoin.bitcoin.Network

@RunWith(AndroidJUnit4::class)
class OfflineWalletTest {
Expand Down
11 changes: 11 additions & 0 deletions bdk-ffi/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions bdk-ffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ bdk_esplora = { version = "0.17.0", default-features = false, features = ["std",
bdk_electrum = { version = "0.17.0", default-features = false, features = ["use-rustls-ring"] }
bdk_bitcoind_rpc = { version = "0.14.0" }
bitcoin-internals = { version = "0.2.0", features = ["alloc"] }
bitcoin-ffi = { git = "https://github.com/bitcoindevkit/bitcoin-ffi", tag = "v0.1.2" }

uniffi = { version = "=0.28.0" }
thiserror = "1.0.58"
Expand Down
80 changes: 24 additions & 56 deletions bdk-ffi/src/bdk.udl
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,6 @@ interface ExtractTxError {
OtherExtractTxErr();
};

[Error]
enum FeeRateError {
"ArithmeticOverflow"
};

[Error]
interface FromScriptError {
UnrecognizedScript();
Expand All @@ -175,16 +170,6 @@ interface LoadWithPersistError {
CouldNotLoad();
};

[Error]
interface ParseAmountError {
OutOfRange();
TooPrecise();
MissingDigits();
InputTooLarge();
InvalidCharacter(string error_message);
OtherParseAmountErr();
};

[Error]
interface PersistenceError {
Write(string error_message);
Expand Down Expand Up @@ -633,20 +618,6 @@ dictionary SentAndReceivedValues {
// bdk_wallet crate - bitcoin re-exports
// ------------------------------------------------------------------------

interface Script {
constructor(sequence<u8> raw_output_script);

sequence<u8> to_bytes();
};

[NonExhaustive]
enum Network {
"Bitcoin",
"Testnet",
"Signet",
"Regtest",
};

enum WordCount {
"Words12",
"Words15",
Expand Down Expand Up @@ -717,40 +688,37 @@ interface Psbt {
string json_serialize();
};

dictionary OutPoint {
string txid;
u32 vout;
dictionary TxIn {
OutPoint previous_output;
Script script_sig;
u32 sequence;
sequence<sequence<u8>> witness;
};

interface Amount {
[Name=from_sat]
constructor(u64 from_sat);

[Name=from_btc, Throws=ParseAmountError]
constructor(f64 from_btc);
// ------------------------------------------------------------------------
// types defined in external crate bitcoin-ffi
// ------------------------------------------------------------------------

u64 to_sat();
[ExternalInterface="bitcoin_ffi"]
typedef extern Script;

f64 to_btc();
};
[External="bitcoin_ffi"]
typedef extern Network;

interface FeeRate {
[Name=from_sat_per_vb, Throws=FeeRateError]
constructor(u64 sat_per_vb);
[ExternalInterface="bitcoin_ffi"]
typedef extern Amount;

[Name=from_sat_per_kwu]
constructor(u64 sat_per_kwu);
[ExternalInterface="bitcoin_ffi"]
typedef extern FeeRate;

u64 to_sat_per_vb_ceil();
[External="bitcoin_ffi"]
typedef extern Txid;

u64 to_sat_per_vb_floor();
[External="bitcoin_ffi"]
typedef extern OutPoint;

u64 to_sat_per_kwu();
};
[ExternalInterface="bitcoin_ffi"]
typedef extern FeeRateError;

dictionary TxIn {
OutPoint previous_output;
Script script_sig;
u32 sequence;
sequence<sequence<u8>> witness;
};
[ExternalInterface="bitcoin_ffi"]
typedef extern ParseAmountError;
120 changes: 5 additions & 115 deletions bdk-ffi/src/bitcoin.rs
Original file line number Diff line number Diff line change
@@ -1,85 +1,28 @@
use crate::error::{
AddressParseError, FeeRateError, FromScriptError, PsbtError, PsbtParseError, TransactionError,
AddressParseError, FromScriptError, PsbtError, PsbtParseError, TransactionError,
};

use bitcoin_ffi::OutPoint;
use bitcoin_ffi::Script;

use bdk_bitcoind_rpc::bitcoincore_rpc::jsonrpc::serde_json;
use bdk_wallet::bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bdk_wallet::bitcoin::amount::ParseAmountError;
use bdk_wallet::bitcoin::consensus::encode::serialize;
use bdk_wallet::bitcoin::consensus::Decodable;
use bdk_wallet::bitcoin::io::Cursor;
use bdk_wallet::bitcoin::psbt::ExtractTxError;
use bdk_wallet::bitcoin::Address as BdkAddress;
use bdk_wallet::bitcoin::Amount as BdkAmount;
use bdk_wallet::bitcoin::FeeRate as BdkFeeRate;
use bdk_wallet::bitcoin::Network;
use bdk_wallet::bitcoin::OutPoint as BdkOutPoint;
use bdk_wallet::bitcoin::Psbt as BdkPsbt;
use bdk_wallet::bitcoin::ScriptBuf as BdkScriptBuf;
use bdk_wallet::bitcoin::Transaction as BdkTransaction;
use bdk_wallet::bitcoin::TxIn as BdkTxIn;
use bdk_wallet::bitcoin::TxOut as BdkTxOut;
use bdk_wallet::bitcoin::Txid;

use std::fmt::Display;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::{Arc, Mutex};

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Amount(pub(crate) BdkAmount);

impl Amount {
pub fn from_sat(sat: u64) -> Self {
Amount(BdkAmount::from_sat(sat))
}

pub fn from_btc(btc: f64) -> Result<Self, ParseAmountError> {
let bdk_amount = BdkAmount::from_btc(btc).map_err(ParseAmountError::from)?;
Ok(Amount(bdk_amount))
}

pub fn to_sat(&self) -> u64 {
self.0.to_sat()
}

pub fn to_btc(&self) -> f64 {
self.0.to_btc()
}
}

impl From<Amount> for BdkAmount {
fn from(amount: Amount) -> Self {
amount.0
}
}

impl From<BdkAmount> for Amount {
fn from(amount: BdkAmount) -> Self {
Amount(amount)
}
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Script(pub(crate) BdkScriptBuf);

impl Script {
pub fn new(raw_output_script: Vec<u8>) -> Self {
let script: BdkScriptBuf = raw_output_script.into();
Script(script)
}

pub fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes()
}
}

impl From<BdkScriptBuf> for Script {
fn from(script: BdkScriptBuf) -> Self {
Script(script)
}
}

#[derive(Debug, PartialEq, Eq)]
pub struct Address(BdkAddress<NetworkChecked>);

Expand Down Expand Up @@ -257,30 +200,6 @@ impl From<BdkPsbt> for Psbt {
}
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct OutPoint {
pub txid: String,
pub vout: u32,
}

impl From<&OutPoint> for BdkOutPoint {
fn from(outpoint: &OutPoint) -> Self {
BdkOutPoint {
txid: Txid::from_str(&outpoint.txid).unwrap(),
vout: outpoint.vout,
}
}
}

impl From<&BdkOutPoint> for OutPoint {
fn from(outpoint: &BdkOutPoint) -> Self {
OutPoint {
txid: outpoint.txid.to_string(),
vout: outpoint.vout,
}
}
}

#[derive(Debug, Clone)]
pub struct TxIn {
pub previous_output: OutPoint,
Expand All @@ -293,7 +212,7 @@ impl From<&BdkTxIn> for TxIn {
fn from(tx_in: &BdkTxIn) -> Self {
TxIn {
previous_output: OutPoint {
txid: tx_in.previous_output.txid.to_string(),
txid: tx_in.previous_output.txid,
vout: tx_in.previous_output.vout,
},
script_sig: Arc::new(Script(tx_in.script_sig.clone())),
Expand All @@ -318,35 +237,6 @@ impl From<&BdkTxOut> for TxOut {
}
}

#[derive(Clone, Debug)]
pub struct FeeRate(pub(crate) BdkFeeRate);

impl FeeRate {
pub fn from_sat_per_vb(sat_per_vb: u64) -> Result<Self, FeeRateError> {
let fee_rate: Option<BdkFeeRate> = BdkFeeRate::from_sat_per_vb(sat_per_vb);
match fee_rate {
Some(fee_rate) => Ok(FeeRate(fee_rate)),
None => Err(FeeRateError::ArithmeticOverflow),
}
}

pub fn from_sat_per_kwu(sat_per_kwu: u64) -> Self {
FeeRate(BdkFeeRate::from_sat_per_kwu(sat_per_kwu))
}

pub fn to_sat_per_vb_ceil(&self) -> u64 {
self.0.to_sat_per_vb_ceil()
}

pub fn to_sat_per_vb_floor(&self) -> u64 {
self.0.to_sat_per_vb_floor()
}

pub fn to_sat_per_kwu(&self) -> u64 {
self.0.to_sat_per_kwu()
}
}

#[cfg(test)]
mod tests {
use crate::bitcoin::Address;
Expand Down
Loading

0 comments on commit e23398f

Please sign in to comment.