-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathdb.dart
More file actions
380 lines (329 loc) · 13.1 KB
/
db.dart
File metadata and controls
380 lines (329 loc) · 13.1 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
* This file is part of Stack Wallet.
*
* Copyright (c) 2023 Cypher Stack
* All Rights Reserved.
* The code is distributed under GPLv3 license, see LICENSE file for details.
* Generated by Cypher Stack on 2023-05-26
*
*/
import 'dart:isolate';
import 'package:compat/compat.dart' as lib_monero_compat;
import 'package:hive_ce/hive.dart' show Box;
import 'package:hive_ce/src/hive_impl.dart';
import 'package:mutex/mutex.dart';
import '../../app_config.dart';
import '../../models/epicbox_server_model.dart';
import '../../models/exchange/response_objects/trade.dart';
import '../../models/node_model.dart';
import '../../models/notification_model.dart';
import '../../models/trade_wallet_lookup.dart';
import '../../services/wallets_service.dart';
import '../../utilities/logger.dart';
import '../../wallets/crypto_currency/crypto_currency.dart';
class DB {
final hive = HiveImpl();
// legacy (required for migrations)
@Deprecated("Left over for migration from old versions of Stack Wallet")
static const String boxNameAddressBook = "addressBook";
static const String boxNameTrades = "exchangeTransactionsBox";
static const String boxNameAllWalletsData = "wallets";
static const String boxNameFavoriteWallets = "favoriteWallets";
static const String boxNamePrimaryNodesDeprecated = "primaryNodes";
// in use
// TODO: migrate
static const String boxNameNodeModels = "nodeModels";
static const String boxNameNotifications = "notificationModels";
static const String boxNameWatchedTransactions =
"watchedTxNotificationModels";
static const String boxNameWatchedTrades = "watchedTradesNotificationModels";
static const String boxNameTradesV2 = "exchangeTradesBox";
static const String boxNameTradeNotes = "tradeNotesBox";
static const String boxNameTradeLookup = "tradeToTxidLookUpBox";
static const String boxNameWalletsToDeleteOnStart = "walletsToDeleteOnStart";
static const String boxNamePriceCache = "priceAPIPrice24hCache";
// in use (keep for now)
static const String boxNameDBInfo = "dbInfo";
static const String boxNamePrefs = "prefs";
static const String boxNameOneTimeDialogsShown = "oneTimeDialogsShown";
static const String boxNameEpicBoxModels = "epicBoxModels";
static const String boxNamePrimaryEpicBox = "primaryEpicBox";
String _boxNameTxCache({required CryptoCurrency currency}) =>
"${currency.identifier}_txCache";
// firo only
String _boxNameSetCache({required CryptoCurrency currency}) =>
"${currency.identifier}_anonymitySetCache";
String _boxNameUsedSerialsCache({required CryptoCurrency currency}) =>
"${currency.identifier}_usedSerialsCache";
Box<NodeModel>? _boxNodeModels;
Box<NodeModel>? _boxPrimaryNodes;
Box<dynamic>? _boxAllWalletsData;
Box<NotificationModel>? _boxNotifications;
Box<NotificationModel>? _boxWatchedTransactions;
Box<NotificationModel>? _boxWatchedTrades;
Box<Trade>? _boxTradesV2;
Box<String>? _boxTradeNotes;
Box<String>? _boxFavoriteWallets;
Box<lib_monero_compat.WalletInfo>? _walletInfoSource;
Box<dynamic>? _boxPrefs;
Box<TradeWalletLookup>? _boxTradeLookup;
Box<dynamic>? _boxDBInfo;
late final Box<EpicBoxServerModel> _boxEpicBoxModels;
late final Box<EpicBoxServerModel> _boxPrimaryEpicBoxes;
// Box<String>? _boxDesktopData;
final Map<String, Box<dynamic>> _walletBoxes = {};
final Map<String, Box<dynamic>> _txCacheBoxes = {};
final Map<String, Box<dynamic>> _setCacheBoxes = {};
final Map<String, Box<dynamic>> _usedSerialsCacheBoxes = {};
final Map<String, Box<dynamic>> _getSparkUsedCoinsTagsCacheBoxes = {};
// exposed for monero
Box<lib_monero_compat.WalletInfo> get moneroWalletInfoBox =>
_walletInfoSource!;
// mutex for stack backup
final mutex = Mutex();
DB._();
static final DB _instance = DB._();
static DB get instance {
// "This name does not uniquely identify an isolate. Multiple isolates in the same process may have the same debugName."
// if (Isolate.current.debugName != "main") {
// TODO: make sure this works properly
if (Isolate.current.debugName != "main") {
throw Exception(
"DB.instance should not be accessed outside the main isolate!",
);
}
return _instance;
}
// open hive boxes
Future<void> init() async {
if (hive.isBoxOpen(boxNameDBInfo)) {
_boxDBInfo = hive.box<dynamic>(boxNameDBInfo);
} else {
_boxDBInfo = await hive.openBox<dynamic>(boxNameDBInfo);
}
await hive.openBox<String>(boxNameWalletsToDeleteOnStart);
if (hive.isBoxOpen(boxNameEpicBoxModels)) {
_boxEpicBoxModels = hive.box<EpicBoxServerModel>(boxNameEpicBoxModels);
} else {
_boxEpicBoxModels = await hive.openBox<EpicBoxServerModel>(
boxNameEpicBoxModels,
);
}
if (hive.isBoxOpen(boxNamePrimaryEpicBox)) {
_boxPrimaryEpicBoxes = hive.box<EpicBoxServerModel>(
boxNamePrimaryEpicBox,
);
} else {
_boxPrimaryEpicBoxes = await hive.openBox<EpicBoxServerModel>(
boxNamePrimaryEpicBox,
);
}
if (hive.isBoxOpen(boxNamePrefs)) {
_boxPrefs = hive.box<dynamic>(boxNamePrefs);
} else {
_boxPrefs = await hive.openBox<dynamic>(boxNamePrefs);
}
if (hive.isBoxOpen(boxNameNodeModels)) {
_boxNodeModels = hive.box<NodeModel>(boxNameNodeModels);
} else {
_boxNodeModels = await hive.openBox<NodeModel>(boxNameNodeModels);
}
if (hive.isBoxOpen(boxNameAllWalletsData)) {
_boxAllWalletsData = hive.box<dynamic>(boxNameAllWalletsData);
} else {
_boxAllWalletsData = await hive.openBox<dynamic>(boxNameAllWalletsData);
}
_boxNotifications = await hive.openBox<NotificationModel>(
boxNameNotifications,
);
_boxWatchedTransactions = await hive.openBox<NotificationModel>(
boxNameWatchedTransactions,
);
_boxWatchedTrades = await hive.openBox<NotificationModel>(
boxNameWatchedTrades,
);
_boxTradesV2 = await hive.openBox<Trade>(boxNameTradesV2);
_boxTradeNotes = await hive.openBox<String>(boxNameTradeNotes);
_boxTradeLookup = await hive.openBox<TradeWalletLookup>(boxNameTradeLookup);
_walletInfoSource = await hive.openBox<lib_monero_compat.WalletInfo>(
lib_monero_compat.WalletInfo.boxName,
);
_boxFavoriteWallets = await hive.openBox<String>(boxNameFavoriteWallets);
await Future.wait([
hive.openBox<dynamic>(boxNamePriceCache),
_loadWalletBoxes(),
]);
}
Future<void> _loadWalletBoxes() async {
final names = _boxAllWalletsData!.get("names") as Map? ?? {};
names.removeWhere((name, dyn) {
final jsonObject = Map<String, dynamic>.from(dyn as Map);
try {
AppConfig.getCryptoCurrencyFor(jsonObject["coin"] as String);
return false;
} catch (e, s) {
Logging.instance.e(
"Error, ${jsonObject["coin"]} does not exist, $name wallet cannot be loaded",
error: e,
stackTrace: s,
);
return true;
}
});
final mapped = Map<String, dynamic>.from(names).map(
(name, dyn) => MapEntry(
name,
WalletInfo.fromJson(Map<String, dynamic>.from(dyn as Map)),
),
);
for (final entry in mapped.entries) {
if (hive.isBoxOpen(entry.value.walletId)) {
_walletBoxes[entry.value.walletId] = hive.box<dynamic>(
entry.value.walletId,
);
} else {
_walletBoxes[entry.value.walletId] = await hive.openBox<dynamic>(
entry.value.walletId,
);
}
}
}
Future<Box<dynamic>> getTxCacheBox({required CryptoCurrency currency}) async {
if (_txCacheBoxes[currency.identifier]?.isOpen != true) {
_txCacheBoxes.remove(currency.identifier);
}
return _txCacheBoxes[currency.identifier] ??= await hive.openBox<dynamic>(
_boxNameTxCache(currency: currency),
);
}
Future<void> closeTxCacheBox({required CryptoCurrency currency}) async {
await _txCacheBoxes[currency.identifier]?.close();
}
Future<Box<dynamic>> getAnonymitySetCacheBox({
required CryptoCurrency currency,
}) async {
if (_setCacheBoxes[currency.identifier]?.isOpen != true) {
_setCacheBoxes.remove(currency.identifier);
}
return _setCacheBoxes[currency.identifier] ??= await hive.openBox<dynamic>(
_boxNameSetCache(currency: currency),
);
}
Future<void> closeAnonymitySetCacheBox({
required CryptoCurrency currency,
}) async {
await _setCacheBoxes[currency.identifier]?.close();
}
Future<Box<dynamic>> getUsedSerialsCacheBox({
required CryptoCurrency currency,
}) async {
if (_usedSerialsCacheBoxes[currency.identifier]?.isOpen != true) {
_usedSerialsCacheBoxes.remove(currency.identifier);
}
return _usedSerialsCacheBoxes[currency.identifier] ??= await hive
.openBox<dynamic>(_boxNameUsedSerialsCache(currency: currency));
}
Future<void> closeUsedSerialsCacheBox({
required CryptoCurrency currency,
}) async {
await _usedSerialsCacheBoxes[currency.identifier]?.close();
}
/// Clear all cached transactions for the specified coin
Future<void> clearSharedTransactionCache({
required CryptoCurrency currency,
}) async {
await deleteAll<dynamic>(boxName: _boxNameTxCache(currency: currency));
if (currency is Firo) {
await deleteAll<dynamic>(boxName: _boxNameSetCache(currency: currency));
await deleteAll<dynamic>(
boxName: _boxNameUsedSerialsCache(currency: currency),
);
}
}
/////////////////////////////////////////
Future<void> addWalletBox({required String walletId}) async {
if (_walletBoxes[walletId] != null) {
throw Exception("Attempted overwrite of existing wallet box!");
}
_walletBoxes[walletId] = await hive.openBox<dynamic>(walletId);
}
Future<void> removeWalletBox({required String walletId}) async {
_walletBoxes.remove(walletId);
}
///////////////////////////////////////////
// reads
List<dynamic> keys<T>({required String boxName}) =>
hive.box<T>(boxName).keys.toList(growable: false);
List<T> values<T>({required String boxName}) =>
hive.box<T>(boxName).values.toList(growable: false);
T? get<T>({required String boxName, required dynamic key}) =>
hive.box<T>(boxName).get(key);
bool containsKey<T>({required String boxName, required dynamic key}) =>
hive.box<T>(boxName).containsKey(key);
// writes
Future<void> put<T>({
required String boxName,
required dynamic key,
required T value,
}) async => await mutex.protect(
() async => await hive.box<T>(boxName).put(key, value),
);
Future<void> add<T>({required String boxName, required T value}) async =>
await mutex.protect(() async => await hive.box<T>(boxName).add(value));
Future<void> addAll<T>({
required String boxName,
required Iterable<T> values,
}) async => await mutex.protect(
() async => await hive.box<T>(boxName).addAll(values),
);
Future<void> delete<T>({
required dynamic key,
required String boxName,
}) async =>
await mutex.protect(() async => await hive.box<T>(boxName).delete(key));
Future<void> deleteAll<T>({required String boxName}) async {
await mutex.protect(() async {
final box = await hive.openBox<T>(boxName);
await box.clear();
});
}
Future<void> deleteBoxFromDisk({required String boxName}) async =>
await mutex.protect(() async => await hive.deleteBoxFromDisk(boxName));
///////////////////////////////////////////////////////////////////////////
Future<bool> deleteEverything() async {
try {
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameAddressBook);
await DB.instance.deleteBoxFromDisk(boxName: "debugInfoBox");
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameNodeModels);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameAllWalletsData);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameNotifications);
await DB.instance.deleteBoxFromDisk(
boxName: DB.boxNameWatchedTransactions,
);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameWatchedTrades);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameTrades);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameTradesV2);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameTradeNotes);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameTradeLookup);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameFavoriteWallets);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNamePrefs);
await DB.instance.deleteBoxFromDisk(
boxName: DB.boxNameWalletsToDeleteOnStart,
);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNamePriceCache);
await DB.instance.deleteBoxFromDisk(boxName: DB.boxNameDBInfo);
await DB.instance.deleteBoxFromDisk(boxName: "theme");
return true;
} catch (e, s) {
Logging.instance.e("$e $s", error: e, stackTrace: s);
return false;
}
}
}
abstract class DBKeys {
static const String cachedBalance = "cachedBalance";
static const String cachedBalanceSecondary = "cachedBalanceSecondary";
static const String isFavorite = "isFavorite";
static const String id = "id";
static const String storedChainHeight = "storedChainHeight";
}