keechain_core/command/
psbt.rs

1// Copyright (c) 2022 Yuki Kishimoto
2// Distributed under the MIT software license
3
4use std::fs::File;
5use std::io::Read;
6use std::path::PathBuf;
7
8use bitcoin::Network;
9
10use crate::error::{Error, Result};
11use crate::types::{Psbt, Seed};
12use crate::util::dir;
13
14pub fn decode_file(psbt_file: PathBuf, network: Network) -> Result<Psbt> {
15    if !psbt_file.exists() && !psbt_file.is_file() {
16        return Err(Error::Generic("PSBT file not found.".to_string()));
17    }
18    let mut file: File = File::open(psbt_file)?;
19    let mut content: Vec<u8> = Vec::new();
20    file.read_to_end(&mut content)?;
21    Psbt::decode(base64::encode(content), network)
22}
23
24pub fn sign_file_from_seed(seed: &Seed, network: Network, psbt_file: PathBuf) -> Result<bool> {
25    let mut psbt: Psbt = decode_file(psbt_file.clone(), network)?;
26    let finalized: bool = psbt.sign(seed)?;
27    if finalized {
28        let mut psbt_file = psbt_file;
29        dir::rename_psbt_to_signed(&mut psbt_file)?;
30        psbt.save_to_file(psbt_file)?;
31    }
32    Ok(finalized)
33}