Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve: binary encoding for wallet data #88

Merged
merged 3 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions src/wallet/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,14 +498,8 @@
prevout: OutPoint,
contract: ScriptBuf,
) -> Result<(), WalletError> {
// let mut wallet_file_data = Wallet::load_wallet_file_data(&self.wallet_file_path[..])?;
// wallet_file_data
// .prevout_to_contract_map
// .insert(prevout, contract);
// let wallet_file = File::create(&self.wallet_file_path[..])?;
// serde_json::to_writer(wallet_file, &wallet_file_data).map_err(|e| io::Error::from(e))?;
if let Some(contract) = self.store.prevout_to_contract_map.insert(prevout, contract) {
log::debug!(target: "Wallet:cache_prevout_to_contract", "prevout-contract map updated. existing contract: {}", contract);
log::debug!(target: "Wallet:cache_prevout_to_contract", "prevout-contract map updated.\nExisting contract: {}", contract);

Check warning on line 502 in src/wallet/api.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/api.rs#L502

Added line #L502 was not covered by tests
}
Ok(())
}
Expand Down
14 changes: 7 additions & 7 deletions src/wallet/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
#[derive(Debug)]
pub enum WalletError {
File(std::io::Error),
Json(serde_json::Error),
Cbor(serde_cbor::Error),

Check warning on line 9 in src/wallet/error.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/error.rs#L9

Added line #L9 was not covered by tests
Rpc(bitcoind::bitcoincore_rpc::Error),
Protocol(String),
BIP32(bitcoin::bip32::Error),
Expand All @@ -20,12 +20,6 @@
}
}

impl From<serde_json::Error> for WalletError {
fn from(e: serde_json::Error) -> Self {
Self::File(e.into())
}
}

impl From<bitcoind::bitcoincore_rpc::Error> for WalletError {
fn from(value: bitcoind::bitcoincore_rpc::Error) -> Self {
Self::Rpc(value)
Expand All @@ -49,3 +43,9 @@
Self::Contract(value)
}
}

impl From<serde_cbor::Error> for WalletError {
fn from(value: serde_cbor::Error) -> Self {
Self::Cbor(value)
}

Check warning on line 50 in src/wallet/error.rs

View check run for this annotation

Codecov / codecov/patch

src/wallet/error.rs#L48-L50

Added lines #L48 - L50 were not covered by tests
}
28 changes: 16 additions & 12 deletions src/wallet/storage.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
//! The Wallet Storage Interface.
//!
//! Wallet data are currently written in a readable, unencrypted json file.
//! Wallet data is currently written in unencrypted CBOR files which are not directly human readable.

use std::{collections::HashMap, convert::TryFrom, io::Read, path::PathBuf};
use std::{collections::HashMap, convert::TryFrom, path::PathBuf};

use bip39::Mnemonic;
use bitcoin::{bip32::ExtendedPrivKey, Network, OutPoint, ScriptBuf};
use std::fs::{File, OpenOptions};
use serde::{Deserialize, Serialize};
use std::{
fs::{File, OpenOptions},
io::{BufReader, BufWriter},
};

use super::{error::WalletError, SwapCoin};

Expand All @@ -16,7 +20,7 @@ use super::fidelity::generate_fidelity_scripts;

const WALLET_FILE_VERSION: u32 = 0;

#[derive(serde::Serialize, serde::Deserialize)]
#[derive(Serialize, Deserialize)]
struct FileData {
file_name: String,
version: u32,
Expand All @@ -34,7 +38,7 @@ struct FileData {
pub struct WalletStore {
/// The file name associated with the wallet store.
pub(crate) file_name: String,
/// The network the wallet operates on.
/// Network the wallet operates on.
pub(crate) network: Network,
/// The master key for the wallet.
pub(super) master_key: ExtendedPrivKey,
Expand Down Expand Up @@ -153,17 +157,17 @@ impl FileData {

/// File path should exist.
fn load_from_file(path: &PathBuf) -> Result<Self, WalletError> {
let mut wallet_file = File::open(path)?;
let mut wallet_file_str = String::new();
wallet_file.read_to_string(&mut wallet_file_str)?;
Ok(serde_json::from_str::<FileData>(&wallet_file_str)?)
let wallet_file = File::open(path)?;
let reader = BufReader::new(wallet_file);
Ok(serde_cbor::from_reader(reader)?)
}

// Overwrite existing file or create a new one.
fn save_to_file(&self, path: &PathBuf) -> Result<(), WalletError> {
std::fs::create_dir_all(path.parent().expect("path should not be root"))?;
std::fs::create_dir_all(path.parent().expect("Path should NOT be root!"))?;
let file = OpenOptions::new().write(true).create(true).open(path)?;
serde_json::to_writer(file, &self)?;
let writer = BufWriter::new(file);
serde_cbor::to_writer(writer, &self)?;
Ok(())
}
}
Expand All @@ -178,7 +182,7 @@ mod tests {
#[test]
fn test_write_and_read_wallet_to_disk() {
let temp_dir = tempdir().unwrap();
let file_path = temp_dir.path().join("test_wallet.json");
let file_path = temp_dir.path().join("test_wallet.cbor");
let mnemonic = Mnemonic::generate(12).unwrap().to_string();

let original_wallet_store = WalletStore::init(
Expand Down
Loading