forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathwasm_storage.rs
More file actions
330 lines (292 loc) · 12.7 KB
/
Copy pathwasm_storage.rs
File metadata and controls
330 lines (292 loc) · 12.7 KB
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
328
329
330
use crate::hd_wallet_storage::{HDAccountStorageItem, HDWalletId, HDWalletStorageError, HDWalletStorageInternalOps,
HDWalletStorageResult};
use crate::CoinsContext;
use async_trait::async_trait;
use crypto::XPub;
use mm2_core::mm_ctx::MmArc;
use mm2_db::indexed_db::cursor_prelude::*;
use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbLocked, DbTable, DbTransactionError, DbUpgrader, IndexedDb,
IndexedDbBuilder, InitDbError, InitDbResult, ItemId, MultiIndex, OnUpgradeResult, SharedDb,
TableSignature, WeakDb};
use mm2_err_handle::prelude::*;
const DB_NAME: &str = "hd_wallet";
const DB_VERSION: u32 = 1;
/// An index of the `HDAccountTable` table that consists of the following properties:
/// * coin - coin ticker
/// * hd_wallet_rmd160 - RIPEMD160(SHA256(x)) where x is a pubkey extracted from a Hardware Wallet device or passphrase.
const WALLET_ID_INDEX: &str = "wallet_id";
/// A **unique** index of the `HDAccountTable` table that consists of the following properties:
/// * coin - coin ticker
/// * hd_wallet_rmd160 - RIPEMD160(SHA256(x)) where x is a pubkey extracted from a Hardware Wallet device or passphrase.
/// * account_id - HD account id
const WALLET_ACCOUNT_ID_INDEX: &str = "wallet_account_id";
pub type HDWalletDbLocked<'a> = DbLocked<'a, HDWalletDb>;
impl From<DbTransactionError> for HDWalletStorageError {
fn from(e: DbTransactionError) -> Self {
let desc = e.to_string();
match e {
DbTransactionError::NoSuchTable { .. }
| DbTransactionError::ErrorCreatingTransaction(_)
| DbTransactionError::ErrorOpeningTable { .. }
| DbTransactionError::ErrorSerializingIndex { .. }
| DbTransactionError::MultipleItemsByUniqueIndex { .. }
| DbTransactionError::NoSuchIndex { .. }
| DbTransactionError::InvalidIndex { .. }
| DbTransactionError::UnexpectedState(_)
| DbTransactionError::TransactionAborted => HDWalletStorageError::Internal(desc),
DbTransactionError::ErrorDeserializingItem(_) => HDWalletStorageError::ErrorDeserializing(desc),
DbTransactionError::ErrorSerializingItem(_) => HDWalletStorageError::ErrorSerializing(desc),
DbTransactionError::ErrorGettingItems(_) | DbTransactionError::ErrorCountingItems(_) => {
HDWalletStorageError::ErrorLoading(desc)
},
DbTransactionError::ErrorUploadingItem(_) | DbTransactionError::ErrorDeletingItems(_) => {
HDWalletStorageError::ErrorSaving(desc)
},
}
}
}
impl From<CursorError> for HDWalletStorageError {
fn from(e: CursorError) -> Self {
let stringified_error = e.to_string();
match e {
// We don't expect that the `String` and `u32` types serialization to fail.
CursorError::ErrorSerializingIndexFieldValue {..}
// We don't expect that the `String` and `u32` types deserialization to fail.
| CursorError::ErrorDeserializingIndexValue {..}
| CursorError::ErrorOpeningCursor {..}
| CursorError::AdvanceError {..}
| CursorError::InvalidKeyRange {..}
| CursorError::TypeMismatch {..}
| CursorError::IncorrectNumberOfKeysPerIndex {..}
| CursorError::UnexpectedState(..)
| CursorError::IncorrectUsage {..} => HDWalletStorageError::Internal(stringified_error),
CursorError::ErrorDeserializingItem {..} => HDWalletStorageError::ErrorDeserializing(stringified_error),
}
}
}
impl From<InitDbError> for HDWalletStorageError {
fn from(e: InitDbError) -> Self { HDWalletStorageError::Internal(e.to_string()) }
}
/// The table has the following individually non-unique indexes: `coin`, `hd_wallet_rmd160`, `account_id`,
/// one non-unique multi-index `wallet_id` that consists of `coin`, `hd_wallet_rmd160`,
/// and one unique multi-index `wallet_account_id` that consists of these four indexes in a row.
/// See [`HDAccountTable::on_update_needed`].
#[derive(Deserialize, Serialize)]
pub struct HDAccountTable {
/// [`HDWalletId::coin`].
/// Non-unique index that is used to fetch/remove items from the storage.
coin: String,
/// [`HDWalletId::hd_wallet_rmd160`].
/// Non-unique index that is used to fetch/remove items from the storage.
hd_wallet_rmd160: String,
/// HD Account ID.
/// Non-unique index that is used to fetch/remove items from the storage.
account_id: u32,
account_xpub: XPub,
/// The number of addresses that we know have been used by the user.
external_addresses_number: u32,
internal_addresses_number: u32,
}
impl TableSignature for HDAccountTable {
const TABLE_NAME: &'static str = "hd_account";
fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()> {
if let (0, 1) = (old_version, new_version) {
let table = upgrader.create_table(Self::TABLE_NAME)?;
table.create_multi_index(WALLET_ID_INDEX, &["coin", "hd_wallet_rmd160"], false)?;
table.create_multi_index(
WALLET_ACCOUNT_ID_INDEX,
&["coin", "hd_wallet_rmd160", "account_id"],
true,
)?;
}
Ok(())
}
}
impl HDAccountTable {
fn new(wallet_id: HDWalletId, account_info: HDAccountStorageItem) -> HDAccountTable {
HDAccountTable {
coin: wallet_id.coin,
hd_wallet_rmd160: wallet_id.hd_wallet_rmd160,
account_id: account_info.account_id,
account_xpub: account_info.account_xpub,
external_addresses_number: account_info.external_addresses_number,
internal_addresses_number: account_info.internal_addresses_number,
}
}
}
impl From<HDAccountTable> for HDAccountStorageItem {
fn from(account: HDAccountTable) -> Self {
HDAccountStorageItem {
account_id: account.account_id,
account_xpub: account.account_xpub,
external_addresses_number: account.external_addresses_number,
internal_addresses_number: account.internal_addresses_number,
}
}
}
pub struct HDWalletDb {
pub(crate) inner: IndexedDb,
}
#[async_trait]
impl DbInstance for HDWalletDb {
fn db_name() -> &'static str { DB_NAME }
async fn init(db_id: DbIdentifier) -> InitDbResult<Self> {
let inner = IndexedDbBuilder::new(db_id)
.with_version(DB_VERSION)
.with_table::<HDAccountTable>()
.build()
.await?;
Ok(HDWalletDb { inner })
}
}
/// The wrapper over the [`CoinsContext::hd_wallet_db`] weak pointer.
pub struct HDWalletIndexedDbStorage {
db: WeakDb<HDWalletDb>,
}
#[async_trait]
impl HDWalletStorageInternalOps for HDWalletIndexedDbStorage {
async fn init(ctx: &MmArc) -> HDWalletStorageResult<Self>
where
Self: Sized,
{
let coins_ctx = CoinsContext::from_ctx(ctx).map_to_mm(HDWalletStorageError::Internal)?;
let db = SharedDb::downgrade(&coins_ctx.hd_wallet_db);
Ok(HDWalletIndexedDbStorage { db })
}
async fn load_accounts(&self, wallet_id: HDWalletId) -> HDWalletStorageResult<Vec<HDAccountStorageItem>> {
let shared_db = self.get_shared_db()?;
let locked_db = Self::lock_db_mutex(&shared_db).await?;
let transaction = locked_db.inner.transaction().await?;
let table = transaction.table::<HDAccountTable>().await?;
let index_keys = MultiIndex::new(WALLET_ID_INDEX)
.with_value(wallet_id.coin)?
.with_value(wallet_id.hd_wallet_rmd160)?;
Ok(table
.get_items_by_multi_index(index_keys)
.await?
.into_iter()
.map(|(_item_id, item)| HDAccountStorageItem::from(item))
.collect())
}
async fn load_account(
&self,
wallet_id: HDWalletId,
account_id: u32,
) -> HDWalletStorageResult<Option<HDAccountStorageItem>> {
let shared_db = self.get_shared_db()?;
let locked_db = Self::lock_db_mutex(&shared_db).await?;
let transaction = locked_db.inner.transaction().await?;
let table = transaction.table::<HDAccountTable>().await?;
let maybe_account = Self::find_account(&table, wallet_id, account_id).await?;
match maybe_account {
Some((_account_item_id, account_item)) => Ok(Some(HDAccountStorageItem::from(account_item))),
None => Ok(None),
}
}
async fn update_external_addresses_number(
&self,
wallet_id: HDWalletId,
account_id: u32,
new_external_addresses_number: u32,
) -> HDWalletStorageResult<()> {
self.update_account(wallet_id, account_id, |account| {
account.external_addresses_number = new_external_addresses_number;
})
.await
}
async fn update_internal_addresses_number(
&self,
wallet_id: HDWalletId,
account_id: u32,
new_internal_addresses_number: u32,
) -> HDWalletStorageResult<()> {
self.update_account(wallet_id, account_id, |account| {
account.internal_addresses_number = new_internal_addresses_number;
})
.await
}
async fn upload_new_account(
&self,
wallet_id: HDWalletId,
account: HDAccountStorageItem,
) -> HDWalletStorageResult<()> {
let shared_db = self.get_shared_db()?;
let locked_db = Self::lock_db_mutex(&shared_db).await?;
let transaction = locked_db.inner.transaction().await?;
let table = transaction.table::<HDAccountTable>().await?;
let new_account = HDAccountTable::new(wallet_id, account);
table
.add_item(&new_account)
.await
.map(|_| ())
.mm_err(HDWalletStorageError::from)
}
async fn clear_accounts(&self, wallet_id: HDWalletId) -> HDWalletStorageResult<()> {
let shared_db = self.get_shared_db()?;
let locked_db = Self::lock_db_mutex(&shared_db).await?;
let transaction = locked_db.inner.transaction().await?;
let table = transaction.table::<HDAccountTable>().await?;
let index_keys = MultiIndex::new(WALLET_ID_INDEX)
.with_value(wallet_id.coin)?
.with_value(wallet_id.hd_wallet_rmd160)?;
table.delete_items_by_multi_index(index_keys).await?;
Ok(())
}
}
impl HDWalletIndexedDbStorage {
fn get_shared_db(&self) -> HDWalletStorageResult<SharedDb<HDWalletDb>> {
self.db
.upgrade()
.or_mm_err(|| HDWalletStorageError::Internal("'HDWalletIndexedDbStorage::db' doesn't exist".to_owned()))
}
async fn lock_db_mutex(db: &SharedDb<HDWalletDb>) -> HDWalletStorageResult<HDWalletDbLocked<'_>> {
db.get_or_initialize().await.mm_err(HDWalletStorageError::from)
}
async fn find_account(
table: &DbTable<'_, HDAccountTable>,
wallet_id: HDWalletId,
account_id: u32,
) -> HDWalletStorageResult<Option<(ItemId, HDAccountTable)>> {
let index_keys = MultiIndex::new(WALLET_ACCOUNT_ID_INDEX)
.with_value(wallet_id.coin)?
.with_value(wallet_id.hd_wallet_rmd160)?
.with_value(account_id)?;
table
.get_item_by_unique_multi_index(index_keys)
.await
.mm_err(HDWalletStorageError::from)
}
async fn update_account<F>(&self, wallet_id: HDWalletId, account_id: u32, f: F) -> HDWalletStorageResult<()>
where
F: FnOnce(&mut HDAccountTable),
{
let shared_db = self.get_shared_db()?;
let locked_db = Self::lock_db_mutex(&shared_db).await?;
let transaction = locked_db.inner.transaction().await?;
let table = transaction.table::<HDAccountTable>().await?;
let (account_item_id, mut account) = Self::find_account(&table, wallet_id.clone(), account_id)
.await?
.or_mm_err(|| HDWalletStorageError::HDAccountNotFound { wallet_id, account_id })?;
// Apply `f` to `account` and upload the changes to the storage.
f(&mut account);
table
.replace_item(account_item_id, &account)
.await
.map(|_| ())
.mm_err(HDWalletStorageError::from)
}
}
/// This function is used in `hd_wallet_storage::tests`.
pub(super) async fn get_all_storage_items(ctx: &MmArc) -> Vec<HDAccountStorageItem> {
let coins_ctx = CoinsContext::from_ctx(ctx).unwrap();
let db = coins_ctx.hd_wallet_db.get_or_initialize().await.unwrap();
let transaction = db.inner.transaction().await.unwrap();
let table = transaction.table::<HDAccountTable>().await.unwrap();
table
.get_all_items()
.await
.expect("Error getting items")
.into_iter()
.map(|(_item_id, item)| HDAccountStorageItem::from(item))
.collect()
}