-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathwallet.dart
More file actions
913 lines (767 loc) · 29.2 KB
/
Copy pathwallet.dart
File metadata and controls
913 lines (767 loc) · 29.2 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
import 'dart:async';
import 'package:isar_community/isar.dart';
import 'package:meta/meta.dart';
import 'package:mutex/mutex.dart';
import '../../db/isar/main_db.dart';
import '../../models/isar/models/blockchain_data/address.dart';
import '../../models/isar/models/ethereum/eth_contract.dart';
import '../../models/isar/models/solana/sol_contract.dart';
import '../../models/keys/view_only_wallet_data.dart';
import '../../models/node_model.dart';
import '../../models/paymint/fee_object_model.dart';
import '../../services/event_bus/events/global/node_connection_status_changed_event.dart';
import '../../services/event_bus/events/global/refresh_percent_changed_event.dart';
import '../../services/event_bus/events/global/wallet_sync_status_changed_event.dart';
import '../../services/event_bus/global_event_bus.dart';
import '../../services/node_service.dart';
import '../../utilities/amount/amount.dart';
import '../../utilities/constants.dart';
import '../../utilities/enums/sync_type_enum.dart';
import '../../utilities/flutter_secure_storage_interface.dart';
import '../../utilities/logger.dart';
import '../../utilities/paynym_is_api.dart';
import '../../utilities/prefs.dart';
import '../crypto_currency/crypto_currency.dart';
import '../isar/models/wallet_info.dart';
import '../models/tx_data.dart';
import 'impl/banano_wallet.dart';
import 'impl/bitcoin_frost_wallet.dart';
import 'impl/bitcoin_wallet.dart';
import 'impl/bitcoincash_wallet.dart';
import 'impl/cardano_wallet.dart';
import 'impl/dash_wallet.dart';
import 'impl/dogecoin_wallet.dart';
import 'impl/ecash_wallet.dart';
import 'impl/epiccash_wallet.dart';
import 'impl/ethereum_wallet.dart';
import 'impl/fact0rn_wallet.dart';
import 'impl/firo_wallet.dart';
import 'impl/litecoin_wallet.dart';
import 'impl/mimblewimblecoin_wallet.dart';
import 'impl/monero_wallet.dart';
import 'impl/namecoin_wallet.dart';
import 'impl/nano_wallet.dart';
import 'impl/particl_wallet.dart';
import 'impl/peercoin_wallet.dart';
import 'impl/salvium_wallet.dart';
import 'impl/solana_wallet.dart';
import 'impl/stellar_wallet.dart';
import 'impl/sub_wallets/eth_token_wallet.dart';
import 'impl/sub_wallets/solana_token_wallet.dart';
import 'impl/tezos_wallet.dart';
import 'impl/wownero_wallet.dart';
import 'impl/xelis_wallet.dart';
import 'intermediate/cryptonote_wallet.dart';
import 'wallet_mixin_interfaces/electrumx_interface.dart';
import 'wallet_mixin_interfaces/mnemonic_interface.dart';
import 'wallet_mixin_interfaces/multi_address_interface.dart';
import 'wallet_mixin_interfaces/paynym_interface.dart';
import 'wallet_mixin_interfaces/private_key_interface.dart';
import 'wallet_mixin_interfaces/spark_interface.dart';
import 'wallet_mixin_interfaces/view_only_option_interface.dart';
abstract class Wallet<T extends CryptoCurrency> {
// default to Transaction class. For TransactionV2 set to 2
int get isarTransactionVersion => 1;
// whether the wallet currently supports multiple recipients per tx
bool get supportsMultiRecipient => false;
Wallet(this.cryptoCurrency);
//============================================================================
// ========== Properties =====================================================
final T cryptoCurrency;
late final MainDB mainDB;
late final SecureStorageInterface secureStorageInterface;
late final NodeService nodeService;
late final Prefs prefs;
final refreshMutex = Mutex();
late final String _walletId;
WalletInfo get info =>
mainDB.isar.walletInfo.where().walletIdEqualTo(walletId).findFirstSync()!;
bool get isConnected => _isConnected;
bool get shouldAutoSync => _shouldAutoSync;
set shouldAutoSync(bool shouldAutoSync) {
if (_shouldAutoSync != shouldAutoSync) {
_shouldAutoSync = shouldAutoSync;
if (!shouldAutoSync) {
_periodicRefreshTimer?.cancel();
_periodicRefreshTimer = null;
_stopNetworkAlivePinging();
} else {
_startNetworkAlivePinging();
refresh();
}
}
}
// ===== private properties ===========================================
/// Maximum time with no refresh activity before the idle watchdog
/// trips and unblocks _refresh() so refreshMutex can be released.
static const _refreshIdleThreshold = Duration(minutes: 5);
/// How often the idle watchdog checks _lastRefreshProgress.
static const _refreshWatchdogTick = Duration(seconds: 30);
Timer? _periodicRefreshTimer;
Timer? _networkAliveTimer;
/// Timestamp of the last _fireRefreshPercentChange during an active
/// refresh. Consumed by the idle watchdog in _refresh() to detect hangs.
DateTime? _lastRefreshProgress;
bool _shouldAutoSync = false;
bool _isConnected = false;
void xmrAndWowSyncSpecificFunctionThatShouldBeGottenRidOfInTheFuture(
bool flag,
) {
_isConnected = flag;
}
//============================================================================
// ========== Wallet Info Convenience Getters ================================
String get walletId => _walletId;
/// Attempt to fetch the most recent chain height.
/// On failure return the last cached height.
Future<int> get chainHeight async {
try {
// attempt updating the walletInfo's cached height
await updateChainHeight();
} catch (e, s) {
// do nothing on failure (besides logging)
Logging.instance.w("$e\n$s", error: e, stackTrace: s);
}
// return regardless of whether it was updated or not as we want a
// number even if it isn't the most recent
return info.cachedChainHeight;
}
//============================================================================
// ========== Static Main ====================================================
/// Create a new wallet and save [walletInfo] to db.
static Future<Wallet> create({
required WalletInfo walletInfo,
required MainDB mainDB,
required SecureStorageInterface secureStorageInterface,
required NodeService nodeService,
required Prefs prefs,
String? mnemonic,
String? mnemonicPassphrase,
String? privateKey,
ViewOnlyWalletData? viewOnlyData,
}) async {
// TODO: rework soon?
if (walletInfo.isViewOnly && viewOnlyData == null) {
throw Exception("Missing view key while creating view only wallet!");
}
final Wallet wallet = await _construct(
walletInfo: walletInfo,
mainDB: mainDB,
secureStorageInterface: secureStorageInterface,
nodeService: nodeService,
prefs: prefs,
);
if (wallet is ViewOnlyOptionInterface && walletInfo.isViewOnly) {
await secureStorageInterface.write(
key: getViewOnlyWalletDataSecStoreKey(walletId: walletInfo.walletId),
value: viewOnlyData!.toJsonEncodedString(),
);
} else if (wallet is MnemonicInterface) {
if (wallet is CryptonoteWallet || wallet is XelisWallet) {
//
// currently a special case due to the xmr/wow/xelis libraries handling their
// own mnemonic generation on new wallet creation
// if its a restore we must set them
if (mnemonic != null) {
if ((await secureStorageInterface.read(
key: mnemonicKey(walletId: walletInfo.walletId),
)) ==
null) {
await secureStorageInterface.write(
key: mnemonicKey(walletId: walletInfo.walletId),
value: mnemonic,
);
}
if (mnemonicPassphrase != null) {
if ((await secureStorageInterface.read(
key: mnemonicPassphraseKey(walletId: walletInfo.walletId),
)) ==
null) {
await secureStorageInterface.write(
key: mnemonicPassphraseKey(walletId: walletInfo.walletId),
value: mnemonicPassphrase,
);
}
}
}
} else {
await secureStorageInterface.write(
key: mnemonicKey(walletId: walletInfo.walletId),
value: mnemonic!,
);
await secureStorageInterface.write(
key: mnemonicPassphraseKey(walletId: walletInfo.walletId),
value: mnemonicPassphrase!,
);
}
}
// TODO [prio=low] handle eth differently?
// This would need to be changed if we actually end up allowing eth wallets
// to be created with a private key instead of mnemonic only
if (wallet is PrivateKeyInterface && wallet is! EthereumWallet) {
await secureStorageInterface.write(
key: privateKeyKey(walletId: walletInfo.walletId),
value: privateKey!,
);
}
// Store in db after wallet creation
await wallet.mainDB.isar.writeTxn(() async {
await wallet.mainDB.isar.walletInfo.put(walletInfo);
});
if (wallet is SparkInterface) {
await walletInfo.updateOtherData(
newEntries: {WalletInfoKeys.firoSparkUsedTagsCacheResetVersion: 1},
isar: mainDB.isar,
);
}
return wallet;
}
/// Load an existing wallet via [WalletInfo] using [walletId].
static Future<Wallet> load({
required String walletId,
required MainDB mainDB,
required SecureStorageInterface secureStorageInterface,
required NodeService nodeService,
required Prefs prefs,
}) async {
final walletInfo = await mainDB.isar.walletInfo
.where()
.walletIdEqualTo(walletId)
.findFirst();
Logging.instance.i(
"Wallet.load loading"
" $walletId "
"${walletInfo?.coin.identifier}"
" ${walletInfo?.name}",
);
if (walletInfo == null) {
throw Exception(
"WalletInfo not found for $walletId when trying to call Wallet.load()",
);
}
return await _construct(
walletInfo: walletInfo,
mainDB: mainDB,
secureStorageInterface: secureStorageInterface,
nodeService: nodeService,
prefs: prefs,
);
}
// TODO: [prio=low] refactor to more generalized token rather than eth specific
static Wallet loadTokenWallet({
required EthereumWallet ethWallet,
required EthContract contract,
}) {
final Wallet wallet = EthTokenWallet(ethWallet, contract);
wallet.prefs = ethWallet.prefs;
wallet.nodeService = ethWallet.nodeService;
wallet.secureStorageInterface = ethWallet.secureStorageInterface;
wallet.mainDB = ethWallet.mainDB;
return wallet.._walletId = ethWallet.info.walletId;
}
static Wallet loadSolTokenWallet({
required SolanaWallet solWallet,
required SolContract contract,
}) {
final Wallet wallet = SolanaTokenWallet(solWallet, contract);
wallet.prefs = solWallet.prefs;
wallet.nodeService = solWallet.nodeService;
wallet.secureStorageInterface = solWallet.secureStorageInterface;
wallet.mainDB = solWallet.mainDB;
return wallet.._walletId = solWallet.info.walletId;
}
//============================================================================
// ========== Static Util ====================================================
// secure storage key
static String mnemonicKey({required String walletId}) =>
"${walletId}_mnemonic";
// secure storage key
static String mnemonicPassphraseKey({required String walletId}) =>
"${walletId}_mnemonicPassphrase";
// secure storage key
static String privateKeyKey({required String walletId}) =>
"${walletId}_privateKey";
// secure storage key
static String getViewOnlyWalletDataSecStoreKey({required String walletId}) =>
"${walletId}_viewOnlyWalletData";
//============================================================================
// ========== Private ========================================================
/// Construct wallet instance by [WalletType] from [walletInfo]
static Future<Wallet> _construct({
required WalletInfo walletInfo,
required MainDB mainDB,
required SecureStorageInterface secureStorageInterface,
required NodeService nodeService,
required Prefs prefs,
}) async {
final Wallet wallet = _loadWallet(walletInfo: walletInfo);
wallet.prefs = prefs;
wallet.nodeService = nodeService;
if (wallet is ElectrumXInterface || wallet is BitcoinFrostWallet) {
// initialize electrumx instance
await wallet.updateNode();
}
return wallet
..secureStorageInterface = secureStorageInterface
..mainDB = mainDB
.._walletId = walletInfo.walletId;
}
static Wallet _loadWallet({required WalletInfo walletInfo}) {
final net = walletInfo.coin.network;
switch (walletInfo.coin.runtimeType) {
case const (Banano):
return BananoWallet(net);
case const (Bitcoin):
return BitcoinWallet(net);
case const (BitcoinFrost):
return BitcoinFrostWallet(net);
case const (Bitcoincash):
return BitcoincashWallet(net);
case const (Cardano):
return CardanoWallet(net);
case const (Dash):
return DashWallet(net);
case const (Dogecoin):
return DogecoinWallet(net);
case const (Ecash):
return EcashWallet(net);
case const (Epiccash):
return EpiccashWallet(net);
case const (Mimblewimblecoin):
return MimblewimblecoinWallet(net);
case const (Ethereum):
return EthereumWallet(net);
case const (Fact0rn):
return Fact0rnWallet(net);
case const (Firo):
return FiroWallet(net);
case const (Litecoin):
return LitecoinWallet(net);
case const (Monero):
return MoneroWallet(net);
case const (Namecoin):
return NamecoinWallet(net);
case const (Nano):
return NanoWallet(net);
case const (Particl):
return ParticlWallet(net);
case const (Peercoin):
return PeercoinWallet(net);
case const (Salvium):
return SalviumWallet(net);
case const (Solana):
return SolanaWallet(net);
case const (Stellar):
return StellarWallet(net);
case const (Tezos):
return TezosWallet(net);
case const (Wownero):
return WowneroWallet(net);
case const (Xelis):
return XelisWallet(net);
default:
// should never hit in reality
throw Exception("Unknown crypto currency: ${walletInfo.coin}");
}
}
void _startNetworkAlivePinging() {
// call once on start right away
_periodicPingCheck();
// then periodically check
_networkAliveTimer = Timer.periodic(Constants.networkAliveTimerDuration, (
_,
) async {
_periodicPingCheck();
});
}
void _periodicPingCheck() async {
if (refreshMutex.isLocked) {
// should be active calls happening so no need to make extra work
return;
}
final bool hasNetwork = await pingCheck();
if (_isConnected != hasNetwork) {
final NodeConnectionStatus status = hasNetwork
? NodeConnectionStatus.connected
: NodeConnectionStatus.disconnected;
if (!doNotFireRefreshEvents) {
GlobalEventBus.instance.fire(
NodeConnectionStatusChangedEvent(status, walletId, cryptoCurrency),
);
}
_isConnected = hasNetwork;
if (status == NodeConnectionStatus.disconnected) {
if (!doNotFireRefreshEvents) {
GlobalEventBus.instance.fire(
WalletSyncStatusChangedEvent(
WalletSyncStatus.unableToSync,
walletId,
cryptoCurrency,
),
);
}
}
if (hasNetwork) {
unawaited(refresh());
}
}
}
void _stopNetworkAlivePinging() {
_networkAliveTimer?.cancel();
_networkAliveTimer = null;
}
//============================================================================
// ========== Must override ==================================================
/// Create and sign a transaction in preparation to submit to network
Future<TxData> prepareSend({required TxData txData});
/// Broadcast transaction to network. On success update local wallet state to
/// reflect updated balance, transactions, utxos, etc.
Future<TxData> confirmSend({required TxData txData});
/// Recover a wallet by scanning the blockchain. If called on a new wallet a
/// normal recovery should occur. When called on an existing wallet and
/// [isRescan] is false then it should throw. Otherwise this function should
/// delete all locally stored blockchain data and refetch it.
Future<void> recover({required bool isRescan});
Future<void> updateNode();
Future<void> updateTransactions();
Future<void> updateBalance();
/// returns true if new utxos were added to local db
Future<bool> updateUTXOs();
/// updates the wallet info's cachedChainHeight
Future<void> updateChainHeight();
Future<Amount> estimateFeeFor(Amount amount, BigInt feeRate);
Future<FeeObject> get fees;
Future<bool> pingCheck();
Future<void> checkSaveInitialReceivingAddress();
//===========================================
/// add transaction to local db temporarily. Used for quickly updating ui
/// before refresh can fetch data from server
Future<TxData> updateSentCachedTxData({required TxData txData}) async {
if (txData.tempTx != null) {
await mainDB.updateOrPutTransactionV2s([txData.tempTx!]);
}
return txData;
}
NodeModel getCurrentNode() {
final node =
nodeService.getPrimaryNodeFor(currency: cryptoCurrency) ??
cryptoCurrency.defaultNode(isPrimary: true);
return node;
}
bool doNotFireRefreshEvents = false;
// Should fire events
Future<void> refresh() async {
final refreshCompleter = Completer<void>();
final future = refreshCompleter.future.then(
(_) {
if (!doNotFireRefreshEvents) {
GlobalEventBus.instance.fire(
WalletSyncStatusChangedEvent(
WalletSyncStatus.synced,
walletId,
cryptoCurrency,
),
);
}
if (shouldAutoSync) {
_periodicRefreshTimer ??= Timer.periodic(const Duration(seconds: 150), (
timer,
) async {
// chain height check currently broken
// if ((await chainHeight) != (await storedChainHeight)) {
// TODO: [prio=med] some kind of quick check if wallet needs to refresh to replace the old refreshIfThereIsNewData call
// if (await refreshIfThereIsNewData()) {
unawaited(refresh());
// }
// }
});
}
},
onError: (Object e, StackTrace s) {
if (!doNotFireRefreshEvents) {
GlobalEventBus.instance.fire(
NodeConnectionStatusChangedEvent(
NodeConnectionStatus.disconnected,
walletId,
cryptoCurrency,
),
);
GlobalEventBus.instance.fire(
WalletSyncStatusChangedEvent(
WalletSyncStatus.unableToSync,
walletId,
cryptoCurrency,
),
);
}
Logging.instance.e(
"Caught exception in refreshWalletData()",
error: e,
stackTrace: s,
);
},
);
unawaited(_refresh(refreshCompleter));
return future;
}
void _fireRefreshPercentChange(double percent) {
_lastRefreshProgress = DateTime.now();
if (this is ElectrumXInterface) {
(this as ElectrumXInterface?)?.refreshingPercent = percent;
}
if (!doNotFireRefreshEvents) {
GlobalEventBus.instance.fire(
RefreshPercentChangedEvent(percent, walletId),
);
}
}
// Should fire events
Future<void> _refresh(Completer<void> completer) async {
// Awaiting this lock could be dangerous.
// Since refresh is periodic (generally)
if (refreshMutex.isLocked) {
return;
}
final start = DateTime.now();
final viewOnly =
this is ViewOnlyOptionInterface &&
(this as ViewOnlyOptionInterface).isViewOnly;
try {
// this acquire should be almost instant due to above check.
// Slight possibility of race but should be irrelevant
await refreshMutex.acquire();
if (!doNotFireRefreshEvents) {
GlobalEventBus.instance.fire(
WalletSyncStatusChangedEvent(
WalletSyncStatus.syncing,
walletId,
cryptoCurrency,
),
);
}
// Idle watchdog: trips when no refresh activity has been observed
// for _refreshIdleThreshold, signalling that the refresh is wedged.
// Slow-but-active syncs keep the watchdog fed and aren't killed:
// - _fireRefreshPercentChange ticks (coarse phase checkpoints)
// - successful electrum RPCs (via ElectrumXClient.onRequestComplete)
// — this covers Spark anon-set downloads and long updateTransactions
// loops, which use electrumXClient directly and do not call
// _fireRefreshPercentChange between phases.
// Per-call hang detection is still the responsibility of the
// underlying adapters (e.g. electrum's connectionTimeout). This only
// catches what slips through those layers and would otherwise hold
// refreshMutex locked until the app is force-closed.
_lastRefreshProgress = DateTime.now();
// Feed the watchdog from successful electrum RPCs, so long sequential
// fetches (e.g. updateTransactions on a wallet with a large history)
// are classified as active rather than idle.
if (this is ElectrumXInterface) {
(this as ElectrumXInterface).electrumXClient.onRequestComplete = () {
_lastRefreshProgress = DateTime.now();
};
}
final watchdogCompleter = Completer<void>();
final watchdog = Timer.periodic(_refreshWatchdogTick, (timer) {
if (watchdogCompleter.isCompleted) {
timer.cancel();
return;
}
final last = _lastRefreshProgress;
if (last == null) return;
if (DateTime.now().difference(last) >= _refreshIdleThreshold) {
timer.cancel();
watchdogCompleter.completeError(
TimeoutException(
'Wallet refresh for $walletId idle for '
'${_refreshIdleThreshold.inMinutes} min',
_refreshIdleThreshold,
),
);
}
});
final work = _doRefreshWork(viewOnly);
try {
await Future.any([work, watchdogCompleter.future]);
} finally {
watchdog.cancel();
if (this is ElectrumXInterface) {
(this as ElectrumXInterface).electrumXClient.onRequestComplete =
null;
}
_lastRefreshProgress = null;
// If the watchdog won the race, `work` is detached and still
// running; an eventual throw would surface as an uncaught async
// error. Attach a no-op error handler to suppress it. If `work`
// completed first, this future is already resolved and the
// handler is a no-op.
unawaited(work.catchError((_) {}));
}
completer.complete();
} catch (error, strace) {
completer.completeError(error, strace);
} finally {
refreshMutex.release();
if (!completer.isCompleted) {
completer.completeError(
"finally block hit before completer completed",
StackTrace.current,
);
}
Logging.instance.i(
"Refresh for "
"$walletId::${info.name}: ${DateTime.now().difference(start)}",
);
}
}
Future<void> _doRefreshWork(bool viewOnly) async {
// add some small buffer before making calls.
// this can probably be removed in the future but was added as a
// debugging feature
await Future<void>.delayed(const Duration(milliseconds: 300));
// TODO: [prio=low] handle this differently. Extra modification of this file for coin specific functionality should be avoided.
final Set<String> codesToCheck = {};
if (this is PaynymInterface && !viewOnly) {
// isSegwit does not matter here at all
final myCode = await (this as PaynymInterface).getPaymentCode(
isSegwit: false,
);
final nym = await PaynymIsApi().nym(myCode.toString());
if (nym.value != null) {
for (final follower in nym.value!.followers) {
codesToCheck.add(follower.code);
}
for (final following in nym.value!.following) {
codesToCheck.add(following.code);
}
}
}
_fireRefreshPercentChange(0);
await updateChainHeight();
if (this is BitcoinFrostWallet) {
await (this as BitcoinFrostWallet).lookAhead();
}
_fireRefreshPercentChange(0.1);
// TODO: [prio=low] handle this differently. Extra modification of this file for coin specific functionality should be avoided.
if (this is MultiAddressInterface) {
if (info.otherData[WalletInfoKeys.reuseAddress] != true) {
await (this as MultiAddressInterface)
.checkReceivingAddressForTransactions();
}
}
_fireRefreshPercentChange(0.2);
// TODO: [prio=low] handle this differently. Extra modification of this file for coin specific functionality should be avoided.
if (this is MultiAddressInterface) {
if (info.otherData[WalletInfoKeys.reuseAddress] != true) {
await (this as MultiAddressInterface)
.checkChangeAddressForTransactions();
}
}
_fireRefreshPercentChange(0.3);
if (this is SparkInterface && !viewOnly) {
// this should be called before updateTransactions()
await (this as SparkInterface).refreshSparkData((0.3, 0.6));
}
if (this is NamecoinWallet) {
await updateUTXOs();
_fireRefreshPercentChange(0.6);
await (this as NamecoinWallet).checkAutoRegisterNameNewOutputs();
_fireRefreshPercentChange(0.70);
await updateTransactions();
} else {
final fetchFuture = updateTransactions();
_fireRefreshPercentChange(0.6);
final utxosRefreshFuture = updateUTXOs();
await utxosRefreshFuture;
_fireRefreshPercentChange(0.65);
await fetchFuture;
_fireRefreshPercentChange(0.70);
}
// TODO: [prio=low] handle this differently. Extra modification of this file for coin specific functionality should be avoided.
if (!viewOnly && this is PaynymInterface && codesToCheck.isNotEmpty) {
await (this as PaynymInterface).checkForNotificationTransactionsTo(
codesToCheck,
);
// check utxos again for notification outputs
await updateUTXOs();
}
_fireRefreshPercentChange(0.80);
// await getAllTxsToWatch();
_fireRefreshPercentChange(0.90);
await updateBalance();
_fireRefreshPercentChange(1.0);
}
Future<void> exit() async {
Logging.instance.i("exit called on $walletId");
_periodicRefreshTimer?.cancel();
_networkAliveTimer?.cancel();
// If the syncing pref is currentWalletOnly or selectedWalletsAtStartup (and
// this wallet isn't in walletIdsSyncOnStartup), then we close subscriptions.
switch (prefs.syncType) {
case SyncingType.currentWalletOnly:
// Close the subscription for this coin's chain height.
// NOTE: This does not work now that the subscription is shared
// await (await ChainHeightServiceManager.getService(cryptoCurrency))
// ?.cancelListen();
case SyncingType.selectedWalletsAtStartup:
// Close the subscription if this wallet is not in the list to be synced.
if (!prefs.walletIdsSyncOnStartup.contains(walletId)) {
// Check if there's another wallet of this coin on the sync list.
final List<String> walletIds = [];
for (final id in prefs.walletIdsSyncOnStartup) {
final wallet = mainDB.isar.walletInfo
.where()
.walletIdEqualTo(id)
.findFirstSync()!;
if (wallet.coin == cryptoCurrency) {
walletIds.add(id);
}
}
// TODO [prio=low]: use a query instead of iterating thru wallets.
// If there are no other wallets of this coin, then close the sub.
if (walletIds.isEmpty) {
// NOTE: This does not work now that the subscription is shared
// await (await ChainHeightServiceManager.getService(
// cryptoCurrency))
// ?.cancelListen();
}
}
case SyncingType.allWalletsOnStartup:
// Do nothing.
break;
}
}
@mustCallSuper
Future<void> init() async {
await checkSaveInitialReceivingAddress();
final address = await getCurrentReceivingAddress();
if (address != null) {
await info.updateReceivingAddress(
newAddress: address.value,
isar: mainDB.isar,
);
}
}
// ===========================================================================
FilterOperation? get transactionFilterOperation => null;
FilterOperation? get receivingAddressFilterOperation;
FilterOperation? get changeAddressFilterOperation;
Future<Address?> getCurrentReceivingAddress() async {
return await _addressQuery(receivingAddressFilterOperation);
}
Future<Address?> getCurrentChangeAddress() async {
return await _addressQuery(changeAddressFilterOperation);
}
Future<Address?> _addressQuery(FilterOperation? filterOperation) async {
return await mainDB.isar.addresses
.buildQuery<Address>(
whereClauses: [
IndexWhereClause.equalTo(indexName: r"walletId", value: [walletId]),
],
filter: filterOperation,
sortBy: [
const SortProperty(property: r"derivationIndex", sort: Sort.desc),
],
)
.findFirst();
}
}