-
Notifications
You must be signed in to change notification settings - Fork 54
/
data.rs
157 lines (132 loc) · 4.99 KB
/
data.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#[cfg(feature = "std")]
use std::{
fs::{self, File},
io::{self, Read},
path::Path,
vec::Vec,
};
use miden_crypto::utils::SliceReader;
use super::{
super::utils::serde::{
ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
},
Account, AuthSecretKey, Word,
};
// ACCOUNT DATA
// ================================================================================================
/// Account data contains a complete description of an account, including the [Account] struct as
/// well as account seed and account authentication info.
///
/// The intent of this struct is to provide an easy way to serialize and deserialize all
/// account-related data as a single unit (e.g., to/from files).
#[derive(Debug, Clone)]
pub struct AccountData {
pub account: Account,
pub account_seed: Option<Word>,
pub auth_secret_key: AuthSecretKey,
}
impl AccountData {
pub fn new(account: Account, account_seed: Option<Word>, auth: AuthSecretKey) -> Self {
Self {
account,
account_seed,
auth_secret_key: auth,
}
}
#[cfg(feature = "std")]
/// Serialises and writes binary AccountData to specified file
pub fn write(&self, filepath: impl AsRef<Path>) -> io::Result<()> {
fs::write(filepath, self.to_bytes())
}
#[cfg(feature = "std")]
/// Reads from file and tries to deserialise an AccountData
pub fn read(filepath: impl AsRef<Path>) -> io::Result<Self> {
let mut file = File::open(filepath)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
let mut reader = SliceReader::new(&buffer);
Ok(AccountData::read_from(&mut reader).map_err(|_| io::ErrorKind::InvalidData)?)
}
}
// SERIALIZATION
// ================================================================================================
impl Serializable for AccountData {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
let AccountData {
account,
account_seed,
auth_secret_key: auth,
} = self;
account.write_into(target);
account_seed.write_into(target);
auth.write_into(target);
}
}
impl Deserializable for AccountData {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let account = Account::read_from(source)?;
let account_seed = <Option<Word>>::read_from(source)?;
let auth_secret_key = AuthSecretKey::read_from(source)?;
Ok(Self::new(account, account_seed, auth_secret_key))
}
fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
Self::read_from(&mut SliceReader::new(bytes))
}
}
// TESTS
// ================================================================================================
#[cfg(test)]
mod tests {
use miden_crypto::{
dsa::rpo_falcon512::SecretKey,
utils::{Deserializable, Serializable},
};
use storage::AccountStorage;
#[cfg(feature = "std")]
use tempfile::tempdir;
use super::AccountData;
use crate::{
accounts::{storage, Account, AccountCode, AccountId, AuthSecretKey, Felt, Word},
assets::AssetVault,
testing::account_id::ACCOUNT_ID_REGULAR_ACCOUNT_IMMUTABLE_CODE_ON_CHAIN,
};
fn build_account_data() -> AccountData {
let id = AccountId::try_from(ACCOUNT_ID_REGULAR_ACCOUNT_IMMUTABLE_CODE_ON_CHAIN).unwrap();
let code = AccountCode::mock();
// create account and auth
let vault = AssetVault::new(&[]).unwrap();
let storage = AccountStorage::new(vec![]).unwrap();
let nonce = Felt::new(0);
let account = Account::from_parts(id, vault, storage, code, nonce);
let account_seed = Some(Word::default());
let auth_secret_key = AuthSecretKey::RpoFalcon512(SecretKey::new());
AccountData::new(account, account_seed, auth_secret_key)
}
#[test]
fn test_serde() {
let account_data = build_account_data();
let serialized = account_data.to_bytes();
let deserialized = AccountData::read_from_bytes(&serialized).unwrap();
assert_eq!(deserialized.account, account_data.account);
assert_eq!(deserialized.account_seed, account_data.account_seed);
assert_eq!(
deserialized.auth_secret_key.to_bytes(),
account_data.auth_secret_key.to_bytes()
);
}
#[cfg(feature = "std")]
#[test]
fn test_serde_file() {
let dir = tempdir().unwrap();
let filepath = dir.path().join("account_data.mac");
let account_data = build_account_data();
account_data.write(filepath.as_path()).unwrap();
let deserialized = AccountData::read(filepath.as_path()).unwrap();
assert_eq!(deserialized.account, account_data.account);
assert_eq!(deserialized.account_seed, account_data.account_seed);
assert_eq!(
deserialized.auth_secret_key.to_bytes(),
account_data.auth_secret_key.to_bytes()
);
}
}