use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::path::Path;
use miden_protocol::account::Account;
use miden_protocol::account::auth::AuthSecretKey;
use crate::{ConversionError, DecodeMessageExt, proto};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountFile {
account: Account,
auth_secret_keys: Vec<AuthSecretKey>,
}
impl AccountFile {
pub fn new(account: Account, auth_secret_keys: Vec<AuthSecretKey>) -> Self {
Self { account, auth_secret_keys }
}
pub fn account(&self) -> &Account {
&self.account
}
pub fn auth_secret_keys(&self) -> &[AuthSecretKey] {
&self.auth_secret_keys
}
pub fn into_parts(self) -> (Account, Vec<AuthSecretKey>) {
(self.account, self.auth_secret_keys)
}
pub fn to_bytes(&self) -> Vec<u8> {
prost::Message::encode_to_vec(&proto::account_file::AccountFile::from(self))
}
pub fn try_from_bytes(bytes: &[u8]) -> Result<Self, AccountFileError> {
<proto::account_file::AccountFile as prost::Message>::decode(bytes)
.map_err(|error| AccountFileError::Decode(ConversionError::new(error)))?
.decode_and_verify()
.map_err(AccountFileError::Decode)
}
#[cfg(feature = "std")]
pub fn write(&self, path: impl AsRef<Path>) -> Result<(), AccountFileError> {
std::fs::write(path, self.to_bytes()).map_err(AccountFileError::Io)
}
#[cfg(feature = "std")]
pub fn read(path: impl AsRef<Path>) -> Result<Self, AccountFileError> {
let bytes = std::fs::read(path).map_err(AccountFileError::Io)?;
Self::try_from_bytes(&bytes)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AccountFileError {
#[error("failed to decode the account file")]
Decode(#[source] ConversionError),
#[cfg(feature = "std")]
#[error("failed to read or write the account file")]
Io(#[source] std::io::Error),
}