-
Notifications
You must be signed in to change notification settings - Fork 17
/
Wallet.js
1830 lines (1738 loc) · 68.4 KB
/
Wallet.js
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
'use strict'
const async = require('async')
const EventEmitter = require('events')
const extend = require('util')._extend
const uuidV1 = require('uuid/v1')
//
const monero_txParsing_utils = require('@mymonero/mymonero-tx-parsing-utils')
const monero_sendingFunds_utils = require('@mymonero/mymonero-sendfunds-utils')
const JSBigInt = require('@mymonero/mymonero-bigint').BigInteger
const monero_amount_format_utils = require('@mymonero/mymonero-money-format')
const monero_config = require('@mymonero/mymonero-monero-config')
const mnemonic_languages = require('@mymonero/mymonero-locales')
//
const persistable_object_utils = require('../../DocumentPersister/persistable_object_utils')
const wallet_persistence_utils = require('./wallet_persistence_utils')
const WalletHostPollingController = require('../Controllers/WalletHostPollingController')
//
const wallet_currencies =
{
xmr: 'xmr'
}
const humanReadable__wallet_currencies =
{
xmr: 'XMR'
}
//
// Shared utility functions (these can be factored out)
function areObjectsEqual (x, y) {
if (x === y) return true
if (!(x instanceof Object) || !(y instanceof Object)) return false
if (x.constructor !== y.constructor) return false
for (var p in x) {
if (!x.hasOwnProperty(p)) continue
if (!y.hasOwnProperty(p)) return false
if (x[p] === y[p]) continue
if (typeof (x[p]) !== 'object') return false
if (!areObjectsEqual(x[p], y[p])) return false
}
for (p in y) {
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) return false
}
return true
}
//
//
class Wallet extends EventEmitter {
/// /////////////////////////////////////////////////////////////////////////////
// Lifecycle - Init -> setup
// Important: You must manually call one of the 'Boot_' methods after you initialize
constructor (options, context) {
super() // must call super before we can access this
//
const self = this
self.options = options
self.context = context
//
self.initTimeInstanceUUID = uuidV1() // so that e.g. the list controller can immediately have an id with which to do observation listener fn cache hashes
//
// initialization state
self._id = self.options._id || null // initialize to null if creating wallet
self.failedToInitialize_cb = function (err) { // v--- Trampoline by executing on next tick to avoid instantiators having undefined instance ref when failure cb called
{
self.didFailToInitialize_flag = true
self.didFailToInitialize_errOrNil = err
}
setTimeout(function () {
const fn = self.options.failedToInitialize_cb || function (err, walletInstance) {}
fn(err, self)
})
}
self.successfullyInitialized_cb = function () { // v--- Trampoline by executing on next tick to avoid instantiators having undefined instance ref when success cb called
setTimeout(function () {
const fn = self.options.successfullyInitialized_cb || function (walletInstance) {}
fn(self)
})
}
//
// runtime state initialization
self.isBooted = false // you must manually boot the instance
self.isLoggingIn = false
self.isLoggedIn = false // may be modified by existing doc
//
// detecting how to set up instance
if (self._id !== null) { // need to look up existing document but do not decrypt & boot
self.__setup_fetchExistingDoc_andAwaitBoot()
} else {
self.__setup_andAwaitBootAndLogInAndDocumentCreation()
}
}
__setup_fetchExistingDoc_andAwaitBoot () {
const self = this
self.context.persister.DocumentsWithIds(
wallet_persistence_utils.CollectionName,
[self._id], // cause we're saying we have an _id passed in…
function (err, contentStrings) {
if (err) {
console.error('err.message:', err.message)
self.failedToInitialize_cb(err)
return
}
if (contentStrings.length === 0) {
const errStr = '❌ Wallet with that _id not found.'
const err = new Error(errStr)
console.error(errStr)
self.failedToInitialize_cb(err)
return
}
const encryptedString = contentStrings[0]
// and we hang onto this for when the instantiator opts to boot the instance
self.initialization_encryptedString = encryptedString
self.successfullyInitialized_cb()
}
)
}
__setup_andAwaitBootAndLogInAndDocumentCreation () {
const self = this
//
// need to create new document. gather metadata & state we need to do so
self.isLoggedIn = false
self.wallet_currency = self.options.wallet_currency || wallet_currencies.xmr // default
if (self.options.generateNewWallet !== true) { // if not generating new mnemonic seed -- which we will pick this up later in the corresponding Boot_*
// First, for now, pre-boot, we'll simply await boot - no need to create a document yet
self.successfullyInitialized_cb()
return
}
function _createWithLocale (currentLocale/* TODO rename */) {
let compatibleLocaleCode = mnemonic_languages.compatibleCodeFromLocale(currentLocale)
if (compatibleLocaleCode == null) {
compatibleLocaleCode = 'en' // fall back to English
}
//
// NOTE: the wallet needs to be imported to the hosted API (e.g. MyMonero) for the hosted API stuff to work
// case I: user is inputting mnemonic string
// case II: user is inputting address + view & spend keys
// case III: we're creating a new wallet
try {
const ret = self.context.monero_utils.newly_created_wallet(
compatibleLocaleCode,
self.context.nettype
)
self.mnemonic_wordsetName = ret.mnemonic_language // newly_created_wallet converts locale language code to mnemonic language for us
if (typeof self.mnemonic_wordsetName === 'undefined' || !self.mnemonic_wordsetName) {
throw 'self.mnemonic_wordsetName not found'
}
self.generatedOnInit_walletDescription =
{ // this structure here is an artifact of a previous organization of the mymonero-core-js code. it should/can be phased out
seed: ret.sec_seed_string,
mnemonicString: ret.mnemonic_string,
keys: {
public_addr: ret.address_string,
view: {
sec: ret.sec_viewKey_string,
pub: ret.pub_viewKey_string
},
spend: {
sec: ret.sec_spendKey_string,
pub: ret.pub_spendKey_string
}
}
}
} catch (e) {
self.failedToInitialize_cb(e)
return
}
//
// First, for now, pre-boot, we'll simply await boot - no need to create a document yet
self.successfullyInitialized_cb()
}
if (self.options.locale_code && typeof self.options.locale_code !== 'undefined') {
_createWithLocale(self.options.locale_code)
return
}
const currentLocale = window.navigator.language
_createWithLocale(currentLocale)
}
/// /////////////////////////////////////////////////////////////////////////////
// Lifecycle - Teardown
// Important: You must manually call TearDown() based on how you retain self
TearDown () {
const self = this
self.hasBeenTornDown = true
self.tearDownRuntime()
}
tearDownRuntime () {
const self = this
self.isLoggingIn = false
self._tearDown_polling()
self._stopTimer__localTxCleanupJob()
//
// and be sure to delete the managed key image cache
self.context.backgroundAPIResponseParser.DeleteManagedKeyImagesForWalletWith(self.public_address, function () {})
}
abortAnyLogInRequest () { // acct info
const self = this
const req = self.requestHandle_for_logIn
if (typeof req !== 'undefined' && req !== null) {
console.log('💬 Aborting running login request')
req.abort()
}
self.requestHandle_for_logIn = null
self.isLoggingIn = false // set synchronously
}
_tearDown_polling () {
const self = this
if (typeof self.hostPollingController !== 'undefined' && self.hostPollingController !== null) {
self.hostPollingController.TearDown()
self.hostPollingController = null
}
}
/// /////////////////////////////////////////////////////////////////////////////
// Runtime (Post init, pre-boot) - Accessors - Public - Creating new wallets
MnemonicStringWhichWasGeneratedOnInit () {
return self.generatedOnInit_walletDescription.mnemonicString
}
// TODO: there may be room for a 'regenerate mnemonic' with new wordset imperative function
/// /////////////////////////////////////////////////////////////////////////////
// Runtime - Imperatives - Public - Booting - Creating/adding wallets
Boot_byLoggingIn_givenNewlyCreatedWallet (
persistencePassword,
walletLabel,
swatch,
fn
) {
const self = this
//
self.persistencePassword = persistencePassword || null
if (self.persistencePassword === null) {
throw 'You must supply a persistencePassword when you are calling a Boot_* method of Wallet'
}
self.walletLabel = walletLabel || ''
self.swatch = swatch || ''
//
const generatedOnInit_walletDescription = self.generatedOnInit_walletDescription
const seed = generatedOnInit_walletDescription.seed
const mnemonicString = generatedOnInit_walletDescription.mnemonicString
const keys = generatedOnInit_walletDescription.keys
//
// pretty sure this is redundant, so commenting:
const address = keys.public_addr
const view_key__private = keys.view.sec
const spend_key__private = keys.spend.sec
const wasAGeneratedWallet = true // true, in this case
//
self._boot_byLoggingIn(
address,
view_key__private,
spend_key__private,
seed,
wasAGeneratedWallet,
false, // persistEvenIfLoginFailed_forServerChange
fn
)
}
Boot_byLoggingIn_existingWallet_withMnemonic (
persistencePassword,
walletLabel,
swatch,
mnemonicString,
persistEvenIfLoginFailed_forServerChange, // need to be able to pass this in, in this case
fn
) { // fn: (err?) -> Void
const self = this
//
self.persistencePassword = persistencePassword || null
if (persistencePassword === null) {
throw 'You must supply a persistencePassword when you are calling a Boot_* method of Wallet'
}
//
self.walletLabel = walletLabel || ''
self.swatch = swatch || ''
//
self.mnemonicString = mnemonicString // even though we re-derive the mnemonicString on success, this is being set here so as to prevent the bug where it gets lost when changing the API server and a reboot w/mnemonicSeed occurs
// we'll grab the mnemonic_language in a sec:
//
let ret
try {
ret = self.context.monero_utils.seed_and_keys_from_mnemonic(
mnemonicString,
self.context.nettype
)
} catch (e) {
console.error('Invalid mnemonic!')
self.__trampolineFor_failedToBootWith_fnAndErr(fn, e)
return
}
{
if (typeof ret.mnemonic_language === 'undefined' || !ret.mnemonic_language) {
self.__trampolineFor_failedToBootWith_fnAndErr(fn, 'Unknown mnemonic language')
return
}
self.mnemonic_wordsetName = ret.mnemonic_language
}
self._boot_byLoggingIn(
ret.address_string,
ret.sec_viewKey_string,
ret.sec_spendKey_string,
ret.sec_seed_string,
false, // wasAGeneratedWallet,
persistEvenIfLoginFailed_forServerChange,
fn
)
}
Boot_byLoggingIn_existingWallet_withAddressAndKeys (
persistencePassword,
walletLabel,
swatch,
address,
view_key__private,
spend_key__private,
persistEvenIfLoginFailed_forServerChange,
fn // (err?) -> Void
) {
const self = this
{
self.persistencePassword = persistencePassword || null
if (persistencePassword === null) {
throw 'You must supply a persistencePassword when you are calling a Boot_* method of Wallet'
}
}
{
self.walletLabel = walletLabel || ''
self.swatch = swatch || ''
}
{
const seed = undefined
const wasAGeneratedWallet = false
self._boot_byLoggingIn(
address,
view_key__private,
spend_key__private,
seed, // seed
wasAGeneratedWallet,
persistEvenIfLoginFailed_forServerChange,
fn
)
}
}
/// /////////////////////////////////////////////////////////////////////////////
// Runtime - Imperatives - Public - Booting - Reading saved wallets
Boot_decryptingExistingInitDoc (
persistencePassword,
fn
) {
const self = this
self.persistencePassword = persistencePassword || null
if (persistencePassword === null) {
const errStr = '❌ You must supply a persistencePassword when you are calling a Boot_* method of Wallet'
const err = new Error(errStr)
console.error(errStr)
self.__trampolineFor_failedToBootWith_fnAndErr(fn, err)
return
}
//
const encryptedString = self.initialization_encryptedString
if (typeof encryptedString === 'undefined' || encryptedString === null) {
const errStr = '__boot_decryptInitDoc_andBoot called but encryptedString undefined'
const err = new Error(err)
self.__trampolineFor_failedToBootWith_fnAndErr(fn, err)
return
}
//
__proceedTo_decryptContentString(encryptedString)
//
function __proceedTo_decryptContentString (encryptedString) {
self.context.string_cryptor__background.New_DecryptedString__Async(
encryptedString,
self.persistencePassword,
function (err, plaintextString) {
if (err) {
console.error('❌ Decryption err: ' + err.toString())
self.__trampolineFor_failedToBootWith_fnAndErr(fn, err)
return
}
self.initialization_encryptedString = null // now we can free this
//
let plaintextDocument = null
try {
plaintextDocument = JSON.parse(plaintextString)
} catch (e) {
self.__trampolineFor_failedToBootWith_fnAndErr(fn, e)
return
}
__proceedTo_hydrateByParsingPlaintextDocument(plaintextDocument)
}
)
}
function __proceedTo_hydrateByParsingPlaintextDocument (plaintextDocument) { // reconstituting state…
wallet_persistence_utils.HydrateInstance(
self,
plaintextDocument
)
// Regenerate any runtime vals that depend on persisted vals..
//
__proceedTo_validateEncryptedValuesHydration()
}
function __proceedTo_validateEncryptedValuesHydration () {
function _failWithValidationErr (errStr) {
const err = new Error(errStr)
console.error(errStr)
self.__trampolineFor_failedToBootWith_fnAndErr(fn, err)
}
if (self.walletLabel === null || typeof self.walletLabel === 'undefined' || self.walletLabel === '') {
return _failWithValidationErr('Reconstituted wallet had no valid self.walletLabel')
}
if (self.wallet_currency === null || typeof self.wallet_currency === 'undefined' || self.wallet_currency === '') {
return _failWithValidationErr('Reconstituted wallet had no valid self.wallet_currency')
}
// We are not going to check whether the acct seed is nil/'' here because if the wallet was
// imported with public addr, view key, and spend key only rather than seed/mnemonic, we
// cannot obtain the seed.
if (self.public_address === null || typeof self.public_address === 'undefined' || self.public_address === '') {
return _failWithValidationErr('Reconstituted wallet had no valid public_address')
}
if (self.public_keys === null || typeof self.public_keys === 'undefined' || self.public_keys === {}) {
return _failWithValidationErr('Reconstituted wallet had no valid public_keys')
}
if (self.public_keys.view === null || typeof self.public_keys.view === 'undefined' || self.public_keys.view === '') {
return _failWithValidationErr('Reconstituted wallet had no valid public_keys.view')
}
if (self.public_keys.spend === null || typeof self.public_keys.spend === 'undefined' || self.public_keys.spend === '') {
return _failWithValidationErr('Reconstituted wallet had no valid public_keys.spend')
}
if (self.private_keys === null || typeof self.private_keys === 'undefined' || self.private_keys === {}) {
return _failWithValidationErr('Reconstituted wallet had no valid private_keys')
}
if (self.private_keys.view === null || typeof self.private_keys.view === 'undefined' || self.private_keys.view === '') {
return _failWithValidationErr('Reconstituted wallet had no valid private_keys.view')
}
if (self.private_keys.spend === null || typeof self.private_keys.spend === 'undefined' || self.private_keys.spend === '') {
return _failWithValidationErr('Reconstituted wallet had no valid private_keys.spend')
}
if (self.account_seed == '') {
return _failWithValidationErr('Reconstituted wallet had empty string at account_seed')
}
//
// finally
if (self.isLoggedIn) { // the typical case - and we can check this here b/c we actually persist .isLoggedIn
self._trampolineFor_successfullyBooted(fn)
// so we're doing the same thing as Boot_havingLoadedDecryptedExistingInitDoc in the iOS app - since record load architecture differs slightly
} else {
console.log('Wallet which was unable to log in was loaded. Attempting to reboot.')
//
// going to treat this as a wallet which was saved but which failed to log in
self.logOutAndSaveThenLogBackIn(persistencePassword)
//
fn()
}
}
}
//
// Runtime - Imperatives - Rebooting / Debooting
deBoot () {
const self = this
const old__total_received = self.total_received
const old__total_sent = self.total_sent
const old__locked_balance = self.locked_balance
const old__spent_outputs = self.spent_outputs
const old__transactions = self.transactions
{
self.tearDownRuntime() // stop any requests, etc
}
{
// important flags to clear:
self.isLoggedIn = false
self.didFailToBoot_flag = false
self.didFailToBoot_errOrNil = null
self.isBooted = false
//
self.total_received = undefined
self.total_sent = undefined
self.locked_balance = undefined
//
self.account_scanned_tx_height = undefined
self.account_scanned_height = undefined
self.account_scanned_block_height = undefined
self.account_scan_start_height = undefined
self.transaction_height = undefined
self.blockchain_height = undefined
//
self.spent_outputs = undefined
self.transactions = undefined
//
self.dateThatLast_fetchedAccountInfo = undefined
self.dateThatLast_fetchedAccountTransactions = undefined
}
{
self.___didReceiveActualChangeTo_balance(
old__total_received,
old__total_sent,
old__locked_balance
)
self.___didReceiveActualChangeTo_spentOutputs(old__spent_outputs)
self.___didReceiveActualChangeTo_heights()
if (typeof self.options.didReceiveUpdateToAccountTransactions === 'function') {
self.options.didReceiveUpdateToAccountTransactions()
}
self.___didReceiveActualChangeTo_transactionsList(
0, // numberOfTransactionsAdded,
[], // newTransactions
old__transactions // oldTransactions
)
}
self.saveToDisk(function (err) {
if (err) {
console.log('Error while saving during a deBoot(): ' + err)
}
})
}
logOutAndSaveThenLogBackIn (persistencePassword) {
const self = this
const fn = function (err) {
if (err) {
console.log('❌ Error while trying to log back in:', err)
} else {
console.log('✅ Logged back in')
}
}
if (self.isLoggedIn || self.isBooted || self.didFailToBoot_flag) {
self.deBoot()
}
if (self.mnemonicString != null && typeof self.mnemonicString !== 'undefined') {
self.Boot_byLoggingIn_existingWallet_withMnemonic(
persistencePassword,
self.walletLabel,
self.swatch,
self.mnemonicString,
true, // persistEvenIfLoginFailed_forServerChange,
fn
)
} else {
if (self.account_seed != null && typeof self.account_seed !== 'undefined') {
throw 'expected nil self.account_seed'
}
self.Boot_byLoggingIn_existingWallet_withAddressAndKeys(
persistencePassword,
self.walletLabel,
self.swatch,
self.public_address,
self.private_keys.view,
self.private_keys.spend,
true, // persistEvenIfLoginFailed_forServerChange,
fn
)
}
}
//
// Runtime - Imperatives - Private - Booting
_trampolineFor_successfullyBooted (
fn // (err?) -> Void
) {
const self = this
{
if (typeof self.account_seed === 'undefined' || self.account_seed === null || self.account_seed == '') {
console.warn('⚠️ Wallet initialized without an account_seed.')
self.wasInitializedWith_addrViewAndSpendKeysInsteadOfSeed = true
} else {
// TODO: move this to -before- the initial saveToDisk()
const derived_mnemonicString = self.context.monero_utils.mnemonic_from_seed(self.account_seed, self.mnemonic_wordsetName)
if (self.mnemonicString != null && typeof self.mnemonicString !== 'undefined') {
const areMnemonicsEqual = self.context.monero_utils.are_equal_mnemonics(
self.mnemonicString,
derived_mnemonicString
)
if (areMnemonicsEqual == false) { // would be rather odd
throw 'Different mnemonicString derived from accountSeed than was entered for login'
}
console.log("Not setting mnemonicSeed because the instance was initialized with one and it's the same as the one derived from the account_seed.")
}
self.mnemonicString = derived_mnemonicString // in all cases, save derived mnemonic in case input mnemonic was truncated words form - so we always recover full form
}
}
// console.info("✅ Successfully instantiated", self.Description())
{
self.isBooted = true
}
{ // ensure we call the callback
fn()
}
{ // notify listeners
self.emit(self.EventName_booted())
}
{
self.__do_localTxCleanupJob()
self._startTimer__localTxCleanupJob() // mark dropped txs as dead
self._atRuntime_setup_hostPollingController() // instantiate (and kick off) polling controller
}
}
_atRuntime_setup_hostPollingController () {
const self = this
const options = {
wallet: self,
factorOfIsFetchingStateDidUpdate_fn: function () {
self.emit(self.EventName_isFetchingUpdatesChanged())
}
}
const context = self.context
self.hostPollingController = new WalletHostPollingController(options, context)
}
_stopTimer__localTxCleanupJob () {
const self = this
// console.log("💬 Clearing polling localTxCleanupJob__intervalTimer.")
clearInterval(self.localTxCleanupJob__intervalTimer)
self.localTxCleanupJob__intervalTimer = null
}
_startTimer__localTxCleanupJob () {
const self = this
// it would be cool to change the sync polling interval to faster while any transactions are pending confirmation, then dial it back while passively waiting
self.localTxCleanupJob__intervalTimer = setInterval(function () {
self.__do_localTxCleanupJob()
}, 60 * 1000 /* ms */) // every minute?
}
__do_localTxCleanupJob () {
const self = this
let didChangeAny = false
const oneDayAndABit_ms = 60 * 60 * (24 + 1/* bit=1hr */) * 1000/* ms time */ // and a bit to avoid possible edge cases
const timeNow = (new Date()).getTime()
const n_transactions = (self.transactions || []).length
for (let i = 0; i < n_transactions; i++) {
const existing_tx = self.transactions[i]
if (typeof existing_tx.timestamp !== 'undefined' && existing_tx.timestamp) {
const msSinceCreation = timeNow - existing_tx.timestamp.getTime()
if (msSinceCreation < 0) {
console.warn('Expected non-negative msSinceCreation')
continue // skip this one .. probably some weird mempool thing
}
if (msSinceCreation > oneDayAndABit_ms) {
if (self.IsTransactionConfirmed(existing_tx) == false ||
existing_tx.mempool == true) {
if (existing_tx.isFailed != true/* already */) {
console.log('Marking transaction as dead: ', existing_tx)
//
didChangeAny = true
existing_tx.isFailed = true // this flag does not need to get preserved on existing_txs when overwritten by an incoming_tx because if it's returned by the server, it can't be dead
}
}
}
} else {
console.warn('Expected non-nil existing_tx.timestamp')
}
}
if (didChangeAny) {
self.saveToDisk(function (err) {})
}
}
__trampolineFor_failedToBootWith_fnAndErr (fn, err) {
const self = this
{
self.didFailToBoot_flag = true
self.didFailToBoot_errOrNil = err
}
fn(err)
//
self.emit(self.EventName_errorWhileBooting(), err)
}
_boot_byLoggingIn (
address,
view_key,
sec_spendKey_orUndef,
seed_orUndefined,
wasAGeneratedWallet,
persistEvenIfLoginFailed_forServerChange,
fn
) {
const self = this
//
self.abortAnyLogInRequest()
self.isLoggingIn = true
//
let ret
try {
ret = self.context.monero_utils.validate_components_for_login(
address,
view_key,
sec_spendKey_orUndef || '', // expects string
seed_orUndefined || '', // expects string
self.context.nettype
)
} catch (e) {
return {
err_str: typeof e === 'string' ? e : '' + e
}
}
if (ret.isValid == false) { // actually don't think we're expecting this..
self.__trampolineFor_failedToBootWith_fnAndErr(fn, 'Invalid input')
return
}
//
// record these properties regardless of whether we are about to error on login
self.public_address = address
if (seed_orUndefined === '') {
throw '_boot_byLoggingIn passed an empty string for a seed; pass undefined or seed.'
}
self.account_seed = seed_orUndefined
self.public_keys =
{
view: ret.pub_viewKey_string,
spend: ret.pub_spendKey_string
}
self.private_keys =
{
view: view_key,
spend: sec_spendKey_orUndef
}
self.isInViewOnlyMode = ret.isInViewOnlyMode // should be true "if(spend_key__orZero)"
self.local_wasAGeneratedWallet = wasAGeneratedWallet // for regeneration purposes later
//
{ // this state must be reset after a failure or the wallet will appear to not have logged in successfully despite success
self.didFailToBoot_flag = false
self.didFailToBoot_errOrNil = null
}
self.requestHandle_for_logIn = self.context.hostedMoneroAPIClient.LogIn(
address,
view_key,
wasAGeneratedWallet,
function (login__err, new_address, received__generated_locally, start_height) {
self.requestHandle_for_logIn = null // free
//
self.isLoggingIn = false
self.isLoggedIn = login__err == null
self.login__new_address = new_address
self.login__generated_locally = received__generated_locally // now update this b/c the server may have pre-existing information
self.account_scan_start_height = start_height // is actually the same thing - we should save this here so we can use it when calculating whether to show the import btn
//
//
const shouldExitOnLoginError = persistEvenIfLoginFailed_forServerChange == false
if (login__err) {
if (shouldExitOnLoginError == true) {
self.__trampolineFor_failedToBootWith_fnAndErr(fn, login__err)
//
return
} else {
// not returning here allows us to continue with the above-set login info to call
// 'saveToDisk(…)' when this call to log in is coming from a wallet
// reboot. reason is that we expect all such wallets to be valid monero
// wallets if they are able to have been rebooted.
}
}
//
self.saveToDisk(
function (save__err) {
if (save__err) {
self.__trampolineFor_failedToBootWith_fnAndErr(fn, save__err)
return
}
if (shouldExitOnLoginError == false && login__err) {
// if we are attempting to re-boot the wallet, but login failed
self.__trampolineFor_failedToBootWith_fnAndErr(fn, login__err) // i.e. leave the wallet in the 'errored'/'failed to boot' state even though we saved
} else { // it's actually a success
self._trampolineFor_successfullyBooted(fn)
}
}
)
}
)
}
/// /////////////////////////////////////////////////////////////////////////////
// Runtime - Accessors - Public - Events - Booting
EventName_booted () {
return 'EventName_booted'
}
EventName_errorWhileBooting () {
return 'EventName_errorWhileBooting'
}
/// /////////////////////////////////////////////////////////////////////////////
// Runtime - Accessors - Public - Events - Updates
EventName_walletLabelChanged () {
return 'EventName_walletLabelChanged'
}
EventName_walletSwatchChanged () {
return 'EventName_walletSwatchChanged'
}
EventName_balanceChanged () {
return 'EventName_balanceChanged'
}
EventName_spentOutputsChanged () {
return 'EventName_spentOutputsChanged'
}
EventName_heightsUpdated () {
return 'EventName_heightsUpdated'
}
EventName_transactionsChanged () {
return 'EventName_transactionsChanged'
}
EventName_transactionsAdded () {
return 'EventName_transactionsAdded'
}
EventName_isFetchingUpdatesChanged () {
return 'EventName_isFetchingUpdatesChanged'
}
//
EventName_willBeDeleted () {
return 'EventName_willBeDeleted'
}
EventName_deleted () {
return 'EventName_deleted'
}
/// /////////////////////////////////////////////////////////////////////////////
// Runtime - Accessors - Public - Wallet properties
IsFetchingAnyUpdates () {
const self = this
if (typeof self.hostPollingController === 'undefined' || !self.hostPollingController) {
return false
}
return self.hostPollingController.IsFetchingAnyUpdates()
}
HasEverFetched_accountInfo () { // semantically, accountInfo here actually excludes the address, keys, mnemonic, …
// and mostly means stuff like totals (balances) and heights… but we keep accountInfo
// cause of the endpoint name
const self = this
if (typeof self.dateThatLast_fetchedAccountInfo === 'undefined') {
return false
}
if (self.dateThatLast_fetchedAccountInfo === null) {
return false
}
//
return true
}
HasEverFetched_transactions () {
const self = this
if (typeof self.dateThatLast_fetchedAccountTransactions === 'undefined') {
return false
}
if (self.dateThatLast_fetchedAccountTransactions === null) {
return false
}
//
return true
}
IsScannerCatchingUp () {
const self = this
if (self.blockchain_height == 0 || typeof self.blockchain_height === 'undefined' || self.blockchain_height == null) {
console.warn('IsScannerCatchingUp() called while nil/0 blockchain_height')
return true
}
if (self.account_scanned_block_height == 0 || typeof self.account_scanned_block_height === 'undefined' || self.account_scanned_block_height == null) {
console.warn('IsScannerCatchingUp() called while nil/0 account_scanned_block_height.')
return true
}
const nBlocksBehind = self.blockchain_height - self.account_scanned_block_height
if (nBlocksBehind >= 10) {
return true
} else if (nBlocksBehind < 0) {
throw 'nBlocksBehind < 0' // maybe replace with warn log
// return false
}
return false
}
NBlocksBehind () {
const self = this
if (self.blockchain_height == 0 || typeof self.blockchain_height === 'undefined' || self.blockchain_height == null) {
console.warn('IsScannerCatchingUp() called while nil/0 blockchain_height')
return 0
}
if (self.account_scanned_block_height == 0 || typeof self.account_scanned_block_height === 'undefined' || self.account_scanned_block_height == null) {
console.warn('IsScannerCatchingUp() called while nil/0 account_scanned_block_height.')
return 0
}
const nBlocksBehind = self.blockchain_height - self.account_scanned_block_height
return nBlocksBehind
}
CatchingUpPercentageFloat () // btn 0 and 1.0
{
const self = this
if (self.account_scanned_height == 0 || typeof self.account_scanned_height === 'undefined' || self.account_scanned_height === null) {
throw 'CatchingUpPercentageFloat() requested but self.account_scanned_height still 0' // maybe replace with warn log
// return 0
} else if (self.transaction_height == 0 || typeof self.transaction_height === 'undefined' || self.transaction_height === null) {
throw 'CatchingUpPercentageFloat() requested but self.transaction_height still 0' // maybe replace with warn log
// return 0
}
const pctFloat = self.account_scanned_height / self.transaction_height
console.log(`CatchingUpPercentageFloat ${self.account_scanned_height}/${self.transaction_height}=${pctFloat.toFixed(2)}%`)
return pctFloat
}
IsTransactionConfirmed (tx) {
const self = this
const blockchain_height = self.blockchain_height
//
return monero_txParsing_utils.IsTransactionConfirmed(tx, blockchain_height)
}
IsTransactionUnlocked (tx) {
const self = this
const blockchain_height = self.blockchain_height
//
return monero_txParsing_utils.IsTransactionUnlocked(tx, blockchain_height)
}
TransactionLockedReason (tx) {
const self = this
const blockchain_height = self.blockchain_height
//
return monero_txParsing_utils.TransactionLockedReason(tx, blockchain_height)
}
//
New_StateCachedTransactions () { // this function is preferred for public access
// as it caches the derivations of the above accessors.
// these things could maybe be derived on reception from API instead of on each access
const self = this
const transactions = self.transactions || []
const stateCachedTransactions = [] // to finalize
const transactions_length = transactions.length
for (let i = 0; i < transactions_length; i++) {
stateCachedTransactions.push(self.New_StateCachedTransaction(transactions[i]))
}
//
return stateCachedTransactions
}
New_StateCachedTransaction (transaction) {
const self = this
const shallowCopyOf_transaction = extend({}, transaction)
shallowCopyOf_transaction.isConfirmed = self.IsTransactionConfirmed(transaction)
shallowCopyOf_transaction.isUnlocked = self.IsTransactionUnlocked(transaction)
shallowCopyOf_transaction.lockedReason = self.TransactionLockedReason(transaction)
if (shallowCopyOf_transaction.isConfirmed && shallowCopyOf_transaction.isFailed) {
// throw "Unexpected isFailed && isConfirmed"
}
//
return shallowCopyOf_transaction
}
//
IsAccountCatchingUp () {
const self = this
// TODO: detect whether account is synched yet
//
return (self.blockchain_height - self.account_scanned_block_height) >= 10
}
//
Balance_JSBigInt () {
const self = this
let total_received = self.total_received
let total_sent = self.total_sent
if (typeof total_received === 'undefined') {
total_received = new JSBigInt(0) // patch up to avoid crash as this doesn't need to be fatal
}
if (typeof total_sent === 'undefined') {
total_sent = new JSBigInt(0) // patch up to avoid crash as this doesn't need to be fatal
}
const balance_JSBigInt = total_received.subtract(total_sent)
if (balance_JSBigInt.compare(0) < 0) {
return new JSBigInt(0)
}
return balance_JSBigInt
}
Balance_FormattedString () { // provided for convenience mainly so consumers don't have to require monero_utils
const self = this