-
Notifications
You must be signed in to change notification settings - Fork 39
/
builder.rs
327 lines (290 loc) · 11.7 KB
/
builder.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use std::sync::{
atomic::{AtomicU32, AtomicUsize},
Arc,
};
#[cfg(feature = "storage")]
use std::{collections::HashSet, sync::atomic::Ordering};
use futures::{future::try_join_all, FutureExt};
use serde::Serialize;
use tokio::sync::RwLock;
use super::operations::storage::SaveLoadWallet;
#[cfg(feature = "events")]
use crate::wallet::events::EventEmitter;
#[cfg(all(feature = "storage", not(feature = "rocksdb")))]
use crate::wallet::storage::adapter::memory::Memory;
#[cfg(feature = "storage")]
use crate::wallet::{
account::AccountDetails,
storage::{StorageManager, StorageOptions},
};
use crate::{
client::secret::{SecretManage, SecretManager},
wallet::{core::WalletInner, Account, ClientOptions, Wallet},
};
/// Builder for the wallet.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletBuilder<S: SecretManage = SecretManager> {
pub(crate) client_options: Option<ClientOptions>,
pub(crate) coin_type: Option<u32>,
#[cfg(feature = "storage")]
pub(crate) storage_options: Option<StorageOptions>,
#[serde(skip)]
pub(crate) secret_manager: Option<Arc<RwLock<S>>>,
}
impl<S: SecretManage> Default for WalletBuilder<S> {
fn default() -> Self {
Self {
client_options: Default::default(),
coin_type: Default::default(),
#[cfg(feature = "storage")]
storage_options: Default::default(),
secret_manager: Default::default(),
}
}
}
impl<S: 'static + SecretManage> WalletBuilder<S>
where
crate::wallet::Error: From<S::Error>,
{
/// Initialises a new instance of the wallet builder with the default storage adapter.
pub fn new() -> Self {
Self {
secret_manager: None,
..Default::default()
}
}
/// Set the client options for the core nodes.
pub fn with_client_options(mut self, client_options: impl Into<Option<ClientOptions>>) -> Self {
self.client_options = client_options.into();
self
}
/// Set the coin type for the wallet. Registered coin types can be found at <https://github.com/satoshilabs/slips/blob/master/slip-0044.md>.
pub fn with_coin_type(mut self, coin_type: impl Into<Option<u32>>) -> Self {
self.coin_type = coin_type.into();
self
}
/// Set the storage options to be used.
#[cfg(feature = "storage")]
#[cfg_attr(docsrs, doc(cfg(feature = "storage")))]
pub fn with_storage_options(mut self, storage_options: impl Into<Option<StorageOptions>>) -> Self {
self.storage_options = storage_options.into();
self
}
/// Set the secret_manager to be used.
pub fn with_secret_manager(mut self, secret_manager: impl Into<Option<S>>) -> Self {
self.secret_manager = secret_manager.into().map(|sm| Arc::new(RwLock::new(sm)));
self
}
/// Set the secret_manager to be used wrapped in an Arc<RwLock<>> so it can be cloned and mutated also outside of
/// the Wallet.
pub fn with_secret_manager_arc(mut self, secret_manager: impl Into<Option<Arc<RwLock<S>>>>) -> Self {
self.secret_manager = secret_manager.into();
self
}
/// Set the storage path to be used.
#[cfg(feature = "storage")]
#[cfg_attr(docsrs, doc(cfg(feature = "storage")))]
pub fn with_storage_path(mut self, path: &str) -> Self {
self.storage_options = Some(StorageOptions {
path: path.into(),
..Default::default()
});
self
}
}
impl<S: 'static + SecretManage> WalletBuilder<S>
where
crate::wallet::Error: From<S::Error>,
Self: SaveLoadWallet,
{
/// Builds the wallet
pub async fn finish(mut self) -> crate::wallet::Result<Wallet<S>> {
log::debug!("[WalletBuilder]");
#[cfg(feature = "storage")]
let storage_options = self.storage_options.clone().unwrap_or_default();
// Check if the db exists and if not, return an error if one parameter is missing, because otherwise the db
// would be created with an empty parameter which just leads to errors later
#[cfg(feature = "storage")]
if !storage_options.path.is_dir() {
if self.client_options.is_none() {
return Err(crate::wallet::Error::MissingParameter("client_options"));
}
if self.coin_type.is_none() {
return Err(crate::wallet::Error::MissingParameter("coin_type"));
}
if self.secret_manager.is_none() {
return Err(crate::wallet::Error::MissingParameter("secret_manager"));
}
}
#[cfg(all(feature = "rocksdb", feature = "storage"))]
let storage =
crate::wallet::storage::adapter::rocksdb::RocksdbStorageAdapter::new(storage_options.path.clone())?;
#[cfg(all(not(feature = "rocksdb"), feature = "storage"))]
let storage = Memory::default();
#[cfg(feature = "storage")]
let mut storage_manager = StorageManager::new(storage, storage_options.encryption_key.clone()).await?;
#[cfg(feature = "storage")]
let read_manager_builder = Self::load(&storage_manager).await?;
#[cfg(not(feature = "storage"))]
let read_manager_builder: Option<Self> = None;
// Prioritize provided client_options and secret_manager over stored ones
let new_provided_client_options = if self.client_options.is_none() {
let loaded_client_options = read_manager_builder
.as_ref()
.and_then(|data| data.client_options.clone())
.ok_or(crate::wallet::Error::MissingParameter("client_options"))?;
// Update self so it gets used and stored again
self.client_options.replace(loaded_client_options);
false
} else {
true
};
if self.secret_manager.is_none() {
let secret_manager = read_manager_builder
.as_ref()
.and_then(|data| data.secret_manager.clone())
.ok_or(crate::wallet::Error::MissingParameter("secret_manager"))?;
// Update self so it gets used and stored again
self.secret_manager.replace(secret_manager);
}
if self.coin_type.is_none() {
self.coin_type = read_manager_builder.and_then(|builder| builder.coin_type);
}
let coin_type = self.coin_type.ok_or(crate::wallet::Error::MissingParameter(
"coin_type (IOTA: 4218, Shimmer: 4219)",
))?;
#[cfg(feature = "storage")]
let mut accounts = storage_manager.get_accounts().await?;
// Check against potential account coin type before saving the wallet data
#[cfg(feature = "storage")]
if let Some(account) = accounts.first() {
if *account.coin_type() != coin_type {
return Err(crate::wallet::Error::InvalidCoinType {
new_coin_type: coin_type,
existing_coin_type: *account.coin_type(),
});
}
}
// Store wallet data in storage
#[cfg(feature = "storage")]
self.save(&storage_manager).await?;
#[cfg(feature = "events")]
let event_emitter = tokio::sync::RwLock::new(EventEmitter::new());
// It happened that inputs got locked, the transaction failed, but they weren't unlocked again, so we do this
// here
#[cfg(feature = "storage")]
unlock_unused_inputs(&mut accounts)?;
#[cfg(not(feature = "storage"))]
let accounts = Vec::new();
let wallet_inner = Arc::new(WalletInner {
background_syncing_status: AtomicUsize::new(0),
client: self
.client_options
.clone()
.ok_or(crate::wallet::Error::MissingParameter("client_options"))?
.finish()
.await?,
coin_type: AtomicU32::new(coin_type),
secret_manager: self
.secret_manager
.ok_or(crate::wallet::Error::MissingParameter("secret_manager"))?,
#[cfg(feature = "events")]
event_emitter,
#[cfg(feature = "storage")]
storage_options,
#[cfg(feature = "storage")]
storage_manager: tokio::sync::RwLock::new(storage_manager),
});
let mut accounts: Vec<Account<S>> = try_join_all(
accounts
.into_iter()
.map(|a| Account::new(a, wallet_inner.clone()).boxed()),
)
.await?;
// If the wallet builder is not set, it means the user provided it and we need to update the addresses.
// In the other case it was loaded from the database and addresses are up to date.
if new_provided_client_options {
for account in accounts.iter_mut() {
// Safe to unwrap because we create the client if accounts aren't empty
account.update_account_bech32_hrp().await?;
}
}
Ok(Wallet {
inner: wallet_inner,
accounts: Arc::new(RwLock::new(accounts)),
})
}
#[cfg(feature = "storage")]
pub(crate) async fn from_wallet(wallet: &Wallet<S>) -> Self {
Self {
client_options: Some(wallet.client_options().await),
coin_type: Some(wallet.coin_type.load(Ordering::Relaxed)),
storage_options: Some(wallet.storage_options.clone()),
secret_manager: Some(wallet.secret_manager.clone()),
}
}
}
// Check if any of the locked inputs is not used in a transaction and unlock them, so they get available for new
// transactions
#[cfg(feature = "storage")]
fn unlock_unused_inputs(accounts: &mut [AccountDetails]) -> crate::wallet::Result<()> {
log::debug!("[unlock_unused_inputs]");
for account in accounts.iter_mut() {
let mut used_inputs = HashSet::new();
for transaction_id in account.pending_transactions() {
if let Some(tx) = account.transactions().get(transaction_id) {
for input in &tx.inputs {
used_inputs.insert(*input.metadata.output_id());
}
}
}
account.locked_outputs.retain(|input| {
let used = used_inputs.contains(input);
if !used {
log::debug!("unlocking unused input {input}");
}
used
})
}
Ok(())
}
#[cfg(feature = "serde")]
pub(crate) mod dto {
use serde::Deserialize;
use super::*;
#[cfg(feature = "storage")]
use crate::{client::secret::SecretManage, wallet::storage::StorageOptions};
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletBuilderDto {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) client_options: Option<ClientOptions>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) coin_type: Option<u32>,
#[cfg(feature = "storage")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) storage_options: Option<StorageOptions>,
}
impl<S: SecretManage> From<WalletBuilderDto> for WalletBuilder<S> {
fn from(value: WalletBuilderDto) -> Self {
Self {
client_options: value.client_options,
coin_type: value.coin_type,
#[cfg(feature = "storage")]
storage_options: value.storage_options,
secret_manager: None,
}
}
}
impl<'de, S: SecretManage> Deserialize<'de> for WalletBuilder<S> {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
WalletBuilderDto::deserialize(d).map(Into::into)
}
}
}