Skip to content

Commit 2704d8a

Browse files
committed
feat: add reading and writing PSBT files
The Rust API makes it trivially simple to read and write PSBT to and from files. Bindings users may make use of this in air-gapped signing flows. The `PsbtError` already includes an `Io` variant, so we may make use of that error.
1 parent 0c18032 commit 2704d8a

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};
@@ -477,6 +479,15 @@ impl Psbt {
477479
Ok(Psbt(Mutex::new(psbt)))
478480
}
479481

482+
/// Create a new `Psbt` from a `.psbt` file.
483+
#[uniffi::constructor]
484+
pub(crate) fn from_file(path: String) -> Result<Self, PsbtError> {
485+
let file = File::open(path)?;
486+
let mut buf_read = BufReader::new(file);
487+
let psbt: BdkPsbt = BdkPsbt::deserialize_from_reader(&mut buf_read)?;
488+
Ok(Psbt(Mutex::new(psbt)))
489+
}
490+
480491
/// Serialize the PSBT into a base64-encoded string.
481492
pub(crate) fn serialize(&self) -> String {
482493
let psbt = self.0.lock().unwrap().clone();
@@ -548,6 +559,15 @@ impl Psbt {
548559
}
549560
}
550561

562+
/// Write the `Psbt` to a file. Note that the file must not yet exist.
563+
pub(crate) fn write_to_file(&self, path: String) -> Result<(), PsbtError> {
564+
let file = File::create(path)?;
565+
let mut writer = BufWriter::new(file);
566+
let psbt = self.0.lock().unwrap();
567+
psbt.serialize_to_writer(&mut writer)?;
568+
Ok(())
569+
}
570+
551571
/// Serializes the PSBT into a JSON string representation.
552572
pub(crate) fn json_serialize(&self) -> String {
553573
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)