Skip to content

Commit 010a6a9

Browse files
authored
feat: add reading and writing PSBT files
1 parent cf9dfcc commit 010a6a9

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

bdk-ffi/src/bitcoin.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ use bdk_wallet::miniscript::psbt::PsbtExt;
3232
use bdk_wallet::serde_json;
3333

3434
use std::fmt::Display;
35+
use std::fs::File;
36+
use std::io::{BufReader, BufWriter};
3537
use std::ops::Deref;
3638
use std::str::FromStr;
3739
use std::sync::{Arc, Mutex};
@@ -495,6 +497,15 @@ impl Psbt {
495497
Ok(Arc::new(Psbt(Mutex::new(psbt))))
496498
}
497499

500+
/// Create a new `Psbt` from a `.psbt` file.
501+
#[uniffi::constructor]
502+
pub(crate) fn from_file(path: String) -> Result<Self, PsbtError> {
503+
let file = File::open(path)?;
504+
let mut buf_read = BufReader::new(file);
505+
let psbt: BdkPsbt = BdkPsbt::deserialize_from_reader(&mut buf_read)?;
506+
Ok(Psbt(Mutex::new(psbt)))
507+
}
508+
498509
/// Serialize the PSBT into a base64-encoded string.
499510
pub(crate) fn serialize(&self) -> String {
500511
let psbt = self.0.lock().unwrap().clone();
@@ -566,6 +577,15 @@ impl Psbt {
566577
}
567578
}
568579

580+
/// Write the `Psbt` to a file. Note that the file must not yet exist.
581+
pub(crate) fn write_to_file(&self, path: String) -> Result<(), PsbtError> {
582+
let file = File::create_new(path)?;
583+
let mut writer = BufWriter::new(file);
584+
let psbt = self.0.lock().unwrap();
585+
psbt.serialize_to_writer(&mut writer)?;
586+
Ok(())
587+
}
588+
569589
/// Serializes the PSBT into a JSON string representation.
570590
pub(crate) fn json_serialize(&self) -> String {
571591
let psbt = self.0.lock().unwrap();

bdk-ffi/src/error.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1438,6 +1438,22 @@ impl From<BdkPsbtParseError> for PsbtParseError {
14381438
}
14391439
}
14401440

1441+
impl From<std::io::Error> for PsbtError {
1442+
fn from(error: std::io::Error) -> Self {
1443+
PsbtError::Io {
1444+
error_message: error.to_string(),
1445+
}
1446+
}
1447+
}
1448+
1449+
impl From<bdk_wallet::bitcoin::io::Error> for PsbtError {
1450+
fn from(error: bdk_wallet::bitcoin::io::Error) -> Self {
1451+
PsbtError::Io {
1452+
error_message: error.to_string(),
1453+
}
1454+
}
1455+
}
1456+
14411457
impl From<BdkPsbtFinalizeError> for PsbtFinalizeError {
14421458
fn from(value: BdkPsbtFinalizeError) -> Self {
14431459
match value {

0 commit comments

Comments
 (0)