-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathepiccash_wallet.dart
More file actions
1353 lines (1177 loc) · 43.2 KB
/
epiccash_wallet.dart
File metadata and controls
1353 lines (1177 loc) · 43.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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:decimal/decimal.dart';
import 'package:flutter_libepiccash/lib.dart' as epiccash;
import 'package:flutter_libepiccash/models/transaction.dart' as epic_models;
import 'package:isar/isar.dart';
import 'package:mutex/mutex.dart';
import 'package:stack_wallet_backup/generate_password.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import '../../../exceptions/wallet/node_tor_mismatch_config_exception.dart';
import '../../../models/balance.dart';
import '../../../models/epicbox_config_model.dart';
import '../../../models/isar/models/blockchain_data/address.dart';
import '../../../models/isar/models/blockchain_data/transaction.dart';
import '../../../models/isar/models/blockchain_data/v2/input_v2.dart';
import '../../../models/isar/models/blockchain_data/v2/output_v2.dart';
import '../../../models/isar/models/blockchain_data/v2/transaction_v2.dart';
import '../../../models/node_model.dart';
import '../../../models/paymint/fee_object_model.dart';
import '../../../pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart';
import '../../../services/event_bus/events/global/blocks_remaining_event.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 '../../../utilities/amount/amount.dart';
import '../../../utilities/default_epicboxes.dart';
import '../../../utilities/flutter_secure_storage_interface.dart';
import '../../../utilities/logger.dart';
import '../../../utilities/stack_file_system.dart';
import '../../../utilities/test_epic_box_connection.dart';
import '../../../utilities/tor_plain_net_option_enum.dart';
import '../../crypto_currency/crypto_currency.dart';
import '../../models/tx_data.dart';
import '../intermediate/bip39_wallet.dart';
import '../supporting/epiccash_wallet_info_extension.dart';
//
// refactor of https://github.com/cypherstack/stack_wallet/blob/1d9fb4cd069f22492ece690ac788e05b8f8b1209/lib/services/coins/epiccash/epiccash_wallet.dart
//
class EpiccashWallet extends Bip39Wallet {
EpiccashWallet(CryptoCurrencyNetwork network) : super(Epiccash(network));
final syncMutex = Mutex();
NodeModel? _epicNode;
Timer? timer;
double highestPercent = 0;
Future<double> get getSyncPercent async {
final int lastScannedBlock = info.epicData?.lastScannedBlock ?? 0;
final _chainHeight = await chainHeight;
final double restorePercent = lastScannedBlock / _chainHeight;
GlobalEventBus.instance.fire(
RefreshPercentChangedEvent(highestPercent, walletId),
);
if (restorePercent > highestPercent) {
highestPercent = restorePercent;
}
final int blocksRemaining = _chainHeight - lastScannedBlock;
GlobalEventBus.instance.fire(
BlocksRemainingEvent(blocksRemaining, walletId),
);
return restorePercent < 0 ? 0.0 : restorePercent;
}
Future<void> updateEpicboxConfig(String host, int port) async {
final String stringConfig = jsonEncode({
"epicbox_domain": host,
"epicbox_port": port,
"epicbox_protocol_unsecure": false,
"epicbox_address_index": 0,
});
await secureStorageInterface.write(
key: '${walletId}_epicboxConfig',
value: stringConfig,
);
// TODO: refresh anything that needs to be refreshed/updated due to epicbox info changed
}
/// returns an empty String on success, error message on failure
Future<String> cancelPendingTransactionAndPost(String txSlateId) async {
try {
_hackedCheckTorNodePrefs();
final String wallet =
(await secureStorageInterface.read(key: '${walletId}_wallet'))!;
final result = await epiccash.LibEpiccash.cancelTransaction(
wallet: wallet,
transactionId: txSlateId,
);
Logging.instance.d("cancel $txSlateId result: $result");
return result;
} catch (e, s) {
Logging.instance.e("", error: e, stackTrace: s);
return e.toString();
}
}
Future<EpicBoxConfigModel> getEpicBoxConfig() async {
final EpicBoxConfigModel _epicBoxConfig = EpicBoxConfigModel.fromServer(
DefaultEpicBoxes.defaultEpicBoxServer,
);
//Get the default Epicbox server and check if it's conected
// bool isEpicboxConnected = await _testEpicboxServer(
// DefaultEpicBoxes.defaultEpicBoxServer.host, DefaultEpicBoxes.defaultEpicBoxServer.port ?? 443);
// if (isEpicboxConnected) {
//Use default server for as Epicbox config
// }
// else {
// //Use Europe config
// _epicBoxConfig = EpicBoxConfigModel.fromServer(DefaultEpicBoxes.europe);
// }
// // example of selecting another random server from the default list
// // alternative servers: copy list of all default EB servers but remove the default default
// // List<EpicBoxServerModel> alternativeServers = DefaultEpicBoxes.all;
// // alternativeServers.removeWhere((opt) => opt.name == DefaultEpicBoxes.defaultEpicBoxServer.name);
// // alternativeServers.shuffle(); // randomize which server is used
// // _epicBoxConfig = EpicBoxConfigModel.fromServer(alternativeServers.first);
//
// // TODO test this connection before returning it
// }
return _epicBoxConfig;
}
// ================= Private =================================================
Future<String> _getConfig() async {
if (_epicNode == null) {
await updateNode();
}
final NodeModel node = _epicNode!;
final String nodeAddress = node.host;
final int port = node.port;
final uri = Uri.parse(nodeAddress).replace(port: port);
final String nodeApiAddress = uri.toString();
final walletDir = await _currentWalletDirPath();
final Map<String, dynamic> config = {};
config["wallet_dir"] = walletDir;
config["check_node_api_http_addr"] = nodeApiAddress;
config["chain"] = "mainnet";
config["account"] = "default";
config["api_listen_port"] = port;
config["api_listen_interface"] = nodeApiAddress.replaceFirst(
uri.scheme,
"",
);
final String stringConfig = jsonEncode(config);
return stringConfig;
}
Future<String> _currentWalletDirPath() async {
final Directory appDir = await StackFileSystem.applicationRootDirectory();
final path = "${appDir.path}/epiccash";
final String name = walletId.trim();
return '$path/$name';
}
Future<int> _nativeFee(
int satoshiAmount, {
bool ifErrorEstimateFee = false,
}) async {
final wallet = await secureStorageInterface.read(key: '${walletId}_wallet');
try {
_hackedCheckTorNodePrefs();
final available = info.cachedBalance.spendable.raw.toInt();
final transactionFees = await epiccash.LibEpiccash.getTransactionFees(
wallet: wallet!,
amount: satoshiAmount,
minimumConfirmations: cryptoCurrency.minConfirms,
available: available,
);
int realFee = 0;
try {
realFee =
(Decimal.parse(transactionFees.fee.toString())).toBigInt().toInt();
} catch (e, s) {
//todo: come back to this
Logging.instance.e("Error getting fees", error: e, stackTrace: s);
}
return realFee;
} catch (e, s) {
Logging.instance.e("Error getting fees $e - $s", error: e, stackTrace: s);
rethrow;
}
}
Future<void> _startSync() async {
_hackedCheckTorNodePrefs();
Logging.instance.d("request start sync");
final wallet = await secureStorageInterface.read(key: '${walletId}_wallet');
const int refreshFromNode = 1;
if (!syncMutex.isLocked) {
await syncMutex.protect(() async {
// How does getWalletBalances start syncing????
await epiccash.LibEpiccash.getWalletBalances(
wallet: wallet!,
refreshFromNode: refreshFromNode,
minimumConfirmations: 10,
);
});
} else {
Logging.instance.d("request start sync denied");
}
}
Future<
({
double awaitingFinalization,
double pending,
double spendable,
double total,
})
>
_allWalletBalances() async {
_hackedCheckTorNodePrefs();
final wallet = await secureStorageInterface.read(key: '${walletId}_wallet');
const refreshFromNode = 0;
return await epiccash.LibEpiccash.getWalletBalances(
wallet: wallet!,
refreshFromNode: refreshFromNode,
minimumConfirmations: cryptoCurrency.minConfirms,
);
}
Future<bool> _testEpicboxServer(EpicBoxConfigModel epicboxConfig) async {
_hackedCheckTorNodePrefs();
final host = epicboxConfig.host;
final port = epicboxConfig.port ?? 443;
WebSocketChannel? channel;
try {
final uri = Uri.parse('wss://$host:$port');
channel = WebSocketChannel.connect(uri);
await channel.ready;
final response = await channel.stream.first.timeout(
const Duration(seconds: 2),
);
return response is String && response.contains("Challenge");
} catch (e, s) {
Logging.instance.w(
"_testEpicBoxConnection failed on \"$host:$port\"",
error: e,
stackTrace: s,
);
return false;
} finally {
await channel?.sink.close();
}
}
Future<bool> _putSendToAddresses(
({String slateId, String commitId}) slateData,
Map<String, String> txAddressInfo,
) async {
try {
final slatesToCommits = info.epicData?.slatesToCommits ?? {};
final from = txAddressInfo['from'];
final to = txAddressInfo['to'];
slatesToCommits[slateData.slateId] = {
"commitId": slateData.commitId,
"from": from,
"to": to,
};
await info.updateExtraEpiccashWalletInfo(
epicData: info.epicData!.copyWith(slatesToCommits: slatesToCommits),
isar: mainDB.isar,
);
return true;
} catch (e, s) {
Logging.instance.e("ERROR STORING ADDRESS", error: e, stackTrace: s);
return false;
}
}
Future<int> _getCurrentIndex() async {
try {
final int receivingIndex = info.epicData!.receivingIndex;
// TODO: go through pendingarray and processed array and choose the index
// of the last one that has not been processed, or the index after the one most recently processed;
return receivingIndex;
} catch (e, s) {
Logging.instance.e("$e $s", error: e, stackTrace: s);
return 0;
}
}
/// Only index 0 is currently used in stack wallet.
Future<Address> _generateAndStoreReceivingAddressForIndex(int index) async {
// Since only 0 is a valid index in stack wallet at this time, lets just
// throw is not zero
if (index != 0) {
throw Exception("Invalid/unexpected address index used");
}
final epicBoxConfig = await getEpicBoxConfig();
final address = await thisWalletAddress(index, epicBoxConfig);
if (info.cachedReceivingAddress != address.value) {
await info.updateReceivingAddress(
newAddress: address.value,
isar: mainDB.isar,
);
}
return address;
}
Future<Address> thisWalletAddress(
int index,
EpicBoxConfigModel epicboxConfig,
) async {
final wallet = await secureStorageInterface.read(key: '${walletId}_wallet');
final walletAddress = await epiccash.LibEpiccash.getAddressInfo(
wallet: wallet!,
index: index,
epicboxConfig: epicboxConfig.toString(),
);
Logging.instance.d("WALLET_ADDRESS_IS $walletAddress");
final address = Address(
walletId: walletId,
value: walletAddress,
derivationIndex: index,
derivationPath: null,
type: AddressType.mimbleWimble,
subType: AddressSubType.receiving,
publicKey: [], // ??
);
await mainDB.updateOrPutAddresses([address]);
return address;
}
Future<void> _startScans() async {
try {
//First stop the current listener
epiccash.LibEpiccash.stopEpicboxListener();
final wallet = await secureStorageInterface.read(
key: '${walletId}_wallet',
);
// max number of blocks to scan per loop iteration
const scanChunkSize = 10000;
// force firing of scan progress event
await getSyncPercent;
// fetch current chain height and last scanned block (should be the
// restore height if full rescan or a wallet restore)
int chainHeight = await this.chainHeight;
int lastScannedBlock = info.epicData!.lastScannedBlock;
// loop while scanning in chain in chunks (of blocks?)
while (lastScannedBlock < chainHeight) {
Logging.instance.d(
"chainHeight: $chainHeight, lastScannedBlock: $lastScannedBlock",
);
final int nextScannedBlock = await epiccash.LibEpiccash.scanOutputs(
wallet: wallet!,
startHeight: lastScannedBlock,
numberOfBlocks: scanChunkSize,
);
// update local cache
await info.updateExtraEpiccashWalletInfo(
epicData: info.epicData!.copyWith(lastScannedBlock: nextScannedBlock),
isar: mainDB.isar,
);
// force firing of scan progress event
await getSyncPercent;
// update while loop condition variables
chainHeight = await this.chainHeight;
lastScannedBlock = nextScannedBlock;
}
Logging.instance.d("_startScans successfully at the tip");
// await _listenToEpicbox();
// Epicbox listener already started before scanning.
} catch (e, s) {
Logging.instance.e("_startScans failed: ", error: e, stackTrace: s);
rethrow;
}
}
Future<void> _listenToEpicbox() async {
Logging.instance.d("STARTING WALLET LISTENER ....");
final wallet = await secureStorageInterface.read(key: '${walletId}_wallet');
final EpicBoxConfigModel epicboxConfig = await getEpicBoxConfig();
epiccash.LibEpiccash.startEpicboxListener(
wallet: wallet!,
epicboxConfig: epicboxConfig.toString(),
);
}
// As opposed to fake config?
Future<String> _getRealConfig() async {
String? config = await secureStorageInterface.read(
key: '${walletId}_config',
);
if (Platform.isIOS) {
final walletDir = await _currentWalletDirPath();
final editConfig = jsonDecode(config as String);
editConfig["wallet_dir"] = walletDir;
config = jsonEncode(editConfig);
}
return config!;
}
// TODO: make more robust estimate of date maybe using https://explorer.epic.tech/api-index
int _calculateRestoreHeightFrom({required DateTime date}) {
final int secondsSinceEpoch = date.millisecondsSinceEpoch ~/ 1000;
const int epicCashFirstBlock = 1565370278;
const double overestimateSecondsPerBlock = 61;
final int chosenSeconds = secondsSinceEpoch - epicCashFirstBlock;
final int approximateHeight = chosenSeconds ~/ overestimateSecondsPerBlock;
int height = approximateHeight;
if (height < 0) {
height = 0;
}
return height;
}
// ============== Overrides ==================================================
@override
int get isarTransactionVersion => 2;
@override
FilterOperation? get changeAddressFilterOperation =>
FilterGroup.and(standardChangeAddressFilters);
@override
FilterOperation? get receivingAddressFilterOperation =>
FilterGroup.and(standardReceivingAddressFilters);
@override
Future<void> checkSaveInitialReceivingAddress() async {
// epiccash seems ok with nothing here?
}
@override
Future<void> init({bool? isRestore}) async {
if (isRestore != true) {
String? encodedWallet = await secureStorageInterface.read(
key: "${walletId}_wallet",
);
// check if should create a new wallet
if (encodedWallet == null) {
await updateNode();
final mnemonicString = await getMnemonic();
final String password = generatePassword();
final String stringConfig = await _getConfig();
final EpicBoxConfigModel epicboxConfig = await getEpicBoxConfig();
await secureStorageInterface.write(
key: '${walletId}_config',
value: stringConfig,
);
await secureStorageInterface.write(
key: '${walletId}_password',
value: password,
);
await secureStorageInterface.write(
key: '${walletId}_epicboxConfig',
value: epicboxConfig.toString(),
);
final String name = walletId;
await epiccash.LibEpiccash.initializeNewWallet(
config: stringConfig,
mnemonic: mnemonicString,
password: password,
name: name,
);
//Open wallet
encodedWallet = await epiccash.LibEpiccash.openWallet(
config: stringConfig,
password: password,
);
await secureStorageInterface.write(
key: '${walletId}_wallet',
value: encodedWallet,
);
//Store Epic box address info
await _generateAndStoreReceivingAddressForIndex(0);
// subtract a couple days to ensure we have a buffer for SWB
final bufferedCreateHeight = _calculateRestoreHeightFrom(
date: DateTime.now().subtract(const Duration(days: 2)),
);
final epicData = ExtraEpiccashWalletInfo(
receivingIndex: 0,
changeIndex: 0,
slatesToAddresses: {},
slatesToCommits: {},
lastScannedBlock: bufferedCreateHeight,
restoreHeight: bufferedCreateHeight,
creationHeight: bufferedCreateHeight,
);
await info.updateExtraEpiccashWalletInfo(
epicData: epicData,
isar: mainDB.isar,
);
} else {
try {
Logging.instance.d(
"initializeExisting() ${cryptoCurrency.prettyName} wallet",
);
final config = await _getRealConfig();
final password = await secureStorageInterface.read(
key: '${walletId}_password',
);
final walletOpen = await epiccash.LibEpiccash.openWallet(
config: config,
password: password!,
);
await secureStorageInterface.write(
key: '${walletId}_wallet',
value: walletOpen,
);
await updateNode();
} catch (e, s) {
// do nothing, still allow user into wallet
Logging.instance.w(
"$runtimeType init() failed: ",
error: e,
stackTrace: s,
);
}
}
}
return await super.init();
}
@override
Future<TxData> confirmSend({required TxData txData}) async {
try {
_hackedCheckTorNodePrefs();
final wallet = await secureStorageInterface.read(
key: '${walletId}_wallet',
);
final EpicBoxConfigModel epicboxConfig = await getEpicBoxConfig();
// TODO determine whether it is worth sending change to a change address.
final String receiverAddress = txData.recipients!.first.address;
if (!receiverAddress.startsWith("http://") ||
!receiverAddress.startsWith("https://")) {
final bool isEpicboxConnected = await _testEpicboxServer(epicboxConfig);
if (!isEpicboxConnected) {
throw Exception("Failed to send TX : Unable to reach epicbox server");
}
}
({String commitId, String slateId}) transaction;
if (receiverAddress.startsWith("http://") ||
receiverAddress.startsWith("https://")) {
transaction = await epiccash.LibEpiccash.txHttpSend(
wallet: wallet!,
selectionStrategyIsAll: 0,
minimumConfirmations: cryptoCurrency.minConfirms,
message: txData.noteOnChain ?? "",
amount: txData.recipients!.first.amount.raw.toInt(),
address: txData.recipients!.first.address,
);
} else {
transaction = await epiccash.LibEpiccash.createTransaction(
wallet: wallet!,
amount: txData.recipients!.first.amount.raw.toInt(),
address: txData.recipients!.first.address,
secretKeyIndex: 0,
epicboxConfig: epicboxConfig.toString(),
minimumConfirmations: cryptoCurrency.minConfirms,
note: txData.noteOnChain!,
);
}
final Map<String, String> txAddressInfo = {};
txAddressInfo['from'] = (await getCurrentReceivingAddress())!.value;
txAddressInfo['to'] = txData.recipients!.first.address;
await _putSendToAddresses(transaction, txAddressInfo);
return txData.copyWith(txid: transaction.slateId);
} catch (e, s) {
Logging.instance.e("Epic cash confirmSend: ", error: e, stackTrace: s);
rethrow;
}
}
@override
Future<TxData> prepareSend({required TxData txData}) async {
try {
_hackedCheckTorNodePrefs();
if (txData.recipients?.length != 1) {
throw Exception("Epic cash prepare send requires a single recipient!");
}
TxRecipient recipient = txData.recipients!.first;
final int realFee = await _nativeFee(recipient.amount.raw.toInt());
final feeAmount = Amount(
rawValue: BigInt.from(realFee),
fractionDigits: cryptoCurrency.fractionDigits,
);
if (feeAmount > info.cachedBalance.spendable) {
throw Exception(
"Epic cash prepare send fee is greater than available balance!",
);
}
if (info.cachedBalance.spendable == recipient.amount) {
recipient = recipient.copyWith(amount: recipient.amount - feeAmount);
}
return txData.copyWith(recipients: [recipient], fee: feeAmount);
} catch (e, s) {
Logging.instance.e("Epic cash prepareSend", error: e, stackTrace: s);
rethrow;
}
}
@override
Future<void> recover({required bool isRescan}) async {
try {
_hackedCheckTorNodePrefs();
await refreshMutex.protect(() async {
if (isRescan) {
// clear blockchain info
await mainDB.deleteWalletBlockchainData(walletId);
await info.updateExtraEpiccashWalletInfo(
epicData: info.epicData!.copyWith(
lastScannedBlock: info.epicData!.restoreHeight,
),
isar: mainDB.isar,
);
unawaited(refresh(doScan: true));
} else {
await updateNode();
final String password = generatePassword();
final String stringConfig = await _getConfig();
final EpicBoxConfigModel epicboxConfig = await getEpicBoxConfig();
await secureStorageInterface.write(
key: '${walletId}_config',
value: stringConfig,
);
await secureStorageInterface.write(
key: '${walletId}_password',
value: password,
);
await secureStorageInterface.write(
key: '${walletId}_epicboxConfig',
value: epicboxConfig.toString(),
);
await epiccash.LibEpiccash.recoverWallet(
config: stringConfig,
password: password,
mnemonic: await getMnemonic(),
name: info.walletId,
);
final epicData = ExtraEpiccashWalletInfo(
receivingIndex: 0,
changeIndex: 0,
slatesToAddresses: {},
slatesToCommits: {},
lastScannedBlock: info.restoreHeight,
restoreHeight: info.restoreHeight,
creationHeight: info.epicData?.creationHeight ?? info.restoreHeight,
);
await info.updateExtraEpiccashWalletInfo(
epicData: epicData,
isar: mainDB.isar,
);
//Open Wallet
final walletOpen = await epiccash.LibEpiccash.openWallet(
config: stringConfig,
password: password,
);
await secureStorageInterface.write(
key: '${walletId}_wallet',
value: walletOpen,
);
await _generateAndStoreReceivingAddressForIndex(
epicData.receivingIndex,
);
}
unawaited(refresh(doScan: false));
});
} catch (e, s) {
Logging.instance.e(
"Exception rethrown from electrumx_mixin recover(): ",
error: e,
stackTrace: s,
);
rethrow;
}
}
@override
Future<void> refresh({bool doScan = true}) async {
// Awaiting this lock could be dangerous.
// Since refresh is periodic (generally)
if (refreshMutex.isLocked) {
return;
}
try {
// this acquire should be almost instant due to above check.
// Slight possibility of race but should be irrelevant
await refreshMutex.acquire();
GlobalEventBus.instance.fire(
WalletSyncStatusChangedEvent(
WalletSyncStatus.syncing,
walletId,
cryptoCurrency,
),
);
_hackedCheckTorNodePrefs();
// if (info.epicData?.creationHeight == null) {
// await info.updateExtraEpiccashWalletInfo(epicData: inf, isar: isar)
// await epicUpdateCreationHeight(await chainHeight);
// }
// this will always be zero????
final int curAdd = await _getCurrentIndex();
await _generateAndStoreReceivingAddressForIndex(curAdd);
if (doScan) {
// Start epicbox listener first for instant transaction appearance.
await _listenToEpicbox();
// Immediately check for epicbox transactions without node dependency.
try {
await _updateTransactionsWithoutNodeRefresh();
await updateBalance(); // Update balance to show pending transactions.
} catch (e, s) {
Logging.instance.w(
"Initial epicbox transaction check failed",
error: e,
stackTrace: s,
);
}
await _startScans();
unawaited(_startSync());
}
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.0, walletId));
await updateChainHeight();
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.1, walletId));
// if (this is MultiAddressInterface) {
// await (this as MultiAddressInterface)
// .checkReceivingAddressForTransactions();
// }
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.2, walletId));
// // TODO: [prio=low] handle this differently. Extra modification of this file for coin specific functionality should be avoided.
// if (this is MultiAddressInterface) {
// await (this as MultiAddressInterface)
// .checkChangeAddressForTransactions();
// }
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.3, walletId));
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.50, walletId));
final fetchFuture = updateTransactions();
// if (currentHeight != storedHeight) {
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.60, walletId));
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.70, walletId));
await fetchFuture;
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.80, walletId));
// await getAllTxsToWatch();
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.90, walletId));
await updateBalance();
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(1.0, walletId));
GlobalEventBus.instance.fire(
WalletSyncStatusChangedEvent(
WalletSyncStatus.synced,
walletId,
cryptoCurrency,
),
);
if (shouldAutoSync) {
timer ??= 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());
// }
// }
});
}
} catch (e, s) {
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,
);
} finally {
refreshMutex.release();
}
}
@override
Future<void> updateBalance() async {
try {
_hackedCheckTorNodePrefs();
final balances = await _allWalletBalances();
final balance = Balance(
total: Amount.fromDecimal(
Decimal.parse(balances.total.toString()) +
Decimal.parse(balances.awaitingFinalization.toString()),
fractionDigits: cryptoCurrency.fractionDigits,
),
spendable: Amount.fromDecimal(
Decimal.parse(balances.spendable.toString()),
fractionDigits: cryptoCurrency.fractionDigits,
),
blockedTotal: Amount.zeroWith(
fractionDigits: cryptoCurrency.fractionDigits,
),
pendingSpendable: Amount.fromDecimal(
Decimal.parse(balances.pending.toString()),
fractionDigits: cryptoCurrency.fractionDigits,
),
);
await info.updateBalance(newBalance: balance, isar: mainDB.isar);
} catch (e, s) {
Logging.instance.w(
"Epic cash wallet failed to update balance: ",
error: e,
stackTrace: s,
);
}
}
/// Updates transactions without refreshing from node (for epicbox-only transactions).
Future<void> _updateTransactionsWithoutNodeRefresh() async {
try {
_hackedCheckTorNodePrefs();
final wallet = await secureStorageInterface.read(
key: '${walletId}_wallet',
);
const refreshFromNode =
0; // Don't refresh from node, use cached/epicbox data.
final myAddresses =
await mainDB
.getAddresses(walletId)
.filter()
.typeEqualTo(AddressType.mimbleWimble)
.and()
.subTypeEqualTo(AddressSubType.receiving)
.and()
.valueIsNotEmpty()
.valueProperty()
.findAll();
final myAddressesSet = myAddresses.toSet();
final transactions = await epiccash.LibEpiccash.getTransactions(
wallet: wallet!,
refreshFromNode: refreshFromNode,
);
final List<TransactionV2> txns = [];
final slatesToCommits = info.epicData?.slatesToCommits ?? {};
for (final tx in transactions) {
final isIncoming =
tx.txType == epic_models.TransactionType.TxReceived ||
tx.txType == epic_models.TransactionType.TxReceivedCancelled;
final slateId = tx.txSlateId;
final commitId = slatesToCommits[slateId]?['commitId'] as String?;
final numberOfMessages = tx.messages?.messages.length;
final onChainNote = tx.messages?.messages[0].message;
final addressFrom = slatesToCommits[slateId]?["from"] as String?;
final addressTo = slatesToCommits[slateId]?["to"] as String?;
final credit = int.parse(tx.amountCredited);
final debit = int.parse(tx.amountDebited);
final fee = int.tryParse(tx.fee ?? "0") ?? 0;
// Hack EPIC tx data into inputs and outputs.
final List<OutputV2> outputs = [];
final List<InputV2> inputs = [];
final addressFromIsMine = myAddressesSet.contains(addressFrom);
final addressToIsMine = myAddressesSet.contains(addressTo);
OutputV2 output = OutputV2.isarCantDoRequiredInDefaultConstructor(
scriptPubKeyHex: "00",
valueStringSats: credit.toString(),
addresses: [if (addressFrom != null) addressFrom],
walletOwns: true,
);
final InputV2 input = InputV2.isarCantDoRequiredInDefaultConstructor(
scriptSigHex: null,
scriptSigAsm: null,
sequence: null,
outpoint: null,
addresses: [if (addressTo != null) addressTo],
valueStringSats: debit.toString(),
witness: null,
innerRedeemScriptAsm: null,
coinbase: null,
walletOwns: true,
);
final TransactionType txType;
if (isIncoming) {
if (addressToIsMine && addressFromIsMine) {
txType = TransactionType.sentToSelf;
} else {
txType = TransactionType.incoming;
}
output = output.copyWith(
addresses: [
myAddressesSet
.first, // Must be changed if we ever do more than a single wallet address!!!
],
walletOwns: true,
);
} else {