-
Notifications
You must be signed in to change notification settings - Fork 54
/
freewallet-desktop.js
6592 lines (6303 loc) · 260 KB
/
freewallet-desktop.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
/*********************************************************************
* freewallet-desktop.js
*
* Custom javascript for FreeWallet (desktop version)
*********************************************************************/
// Setup some short aliases
var ls = localStorage,
ss = sessionStorage,
bc = bitcore;
// Define FreeWallet namespace
FW = {};
// Define object to hold data for dialog boxes
FW.DIALOG_DATA = {};
// Define list of API keys used
FW.API_KEYS = {};
// Load wallet network (1=Mainnet, 2=Testnet)
FW.WALLET_NETWORK = ls.getItem('walletNetwork') || 1;
// Load latest network information (btc/xcp price, fee info, block info)
FW.NETWORK_INFO = JSON.parse(ls.getItem('networkInfo')) || {};
// Wallet format (0=Counterwallet, 1=BIP39)
FW.WALLET_FORMAT = ls.getItem('walletFormat') || 0;
// Wallet encryption status (0=default, 1=encrypted with password)
FW.WALLET_ENCRYPTED = parseInt(ls.getItem('walletEncrypted')) || 0;
// Minimum transaction fee
FW.MINIMUM_TX_FEE_DEFAULT = 1000;
FW.MINIMUM_TX_FEE = ls.getItem('feeMinimum') || FW.MINIMUM_TX_FEE_DEFAULT;
// Load current wallet address and address label
FW.WALLET_ADDRESS = ls.getItem('walletAddress') || null;
FW.WALLET_ADDRESS_LABEL = ls.getItem('walletAddressLabel') || null;
// Array of the known wallet addresses any labels
FW.WALLET_ADDRESSES = JSON.parse(ls.getItem('walletAddresses')) || [];
// Example record
// {
// address: '14PPCFzhQbMFyuUTRRqDnbt1gTVnXcCETi',
// label: 'My Wallet Address'
// network: 1, // 1=Mainnet, 2=Testnet
// type: 1, // 1=indexed, 2=imported (privkey), 3=watch-only, 4=trezor, 5=ledger, 6=keepkey
// index: 0 // The index of the address
// path: "m/44'/0'/0" // Node path for address (ex: m/44'/0'/0)
// }
FW.WALLET_KEYS = {}; // Address/Private keys
FW.EXCHANGE_MARKETS = {}; // DEX Markets cache
FW.DISPENSERS = {}; // Dispensers cache
// Load the last known wallet balances and history
FW.WALLET_BALANCES = JSON.parse(ls.getItem('walletBalances')) || [];
FW.WALLET_HISTORY = JSON.parse(ls.getItem('walletHistory')) || [];
// Define default server info
FW.WALLET_SERVER_INFO_DEFAULT = {
mainnet: {
host: 'public.xchain.io',
port: 4001,
user: 'rpc',
pass: 'rpc',
ssl: true,
api_host: 'xchain.io',
api_ssl: true
},
testnet: {
host: 'public.xchain.io',
port: 14001,
user: 'rpc',
pass: 'rpc',
ssl: true,
api_host: 'testnet.xchain.io',
api_ssl: true
}
};
// Set server info to default server info
FW.WALLET_SERVER_INFO = FW.WALLET_SERVER_INFO_DEFAULT;
// Define the default and base markets for the Decentralized Exchange (DEX)
FW.DEFAULT_MARKETS = ['BTC','XCP','BITCRYSTALS','PEPECASH','WILLCOIN'];
FW.BASE_MARKETS = JSON.parse(ls.getItem('walletMarkets')) || FW.DEFAULT_MARKETS;
FW.MARKET_OPTIONS = JSON.parse(ls.getItem('walletMarketOptions')) || [1,2]; // 1=named, 2=subasset, 3=numeric
FW.BASE_MARKETS = FW.BASE_MARKETS.slice(0, 10); // Limit exchange market list to 10
// Define default dispenser watchlist assets
FW.DEFAULT_DISPENSERS = ['XCP','PEPECASH'];
FW.BASE_DISPENSERS = JSON.parse(ls.getItem('walletDispensers')) || FW.DEFAULT_DISPENSERS;
FW.DISPENSER_OPTIONS = JSON.parse(ls.getItem('walletDispenserOptions')) || []; // 1=hide closed
FW.BASE_DISPENSERS = FW.BASE_DISPENSERS.slice(0, 10); // Limit dispenser watchlist to 10
// Define arrays to hold BTCPay information
FW.BTCPAY_ORDERS = JSON.parse(ls.getItem('btcpayOrders')) || {}; // array of order tx_hashes to monitor for BTCpay transactions
FW.BTCPAY_MATCHES = JSON.parse(ls.getItem('btcpayMatches')) || {}; // array of order matches that have seen/processed
FW.BTCPAY_QUEUE = JSON.parse(ls.getItem('btcpayQueue')) || {}; // Array of btcpay transactions to process
// Example of how BTCPAY data is stored
// FW.BTCPAY_ORDERS[network][address][order_hash] = autopay; // (autopay 0=false, 1=true)
// FW.BTCPAY_MATCHES[network][order_hash] = [order_match1, order_match2]; // Array of order match transactions that have been seen/added to queue
// FW.BTCPAY_QUEUE[network] = [{ tx_info },{ tx_info }]; // Array of btcpay transactions to process
// Define cache for asset information
// We cache the data in order to reduce duplicate API calls as much as possible
FW.ASSET_INFO = {};
// Example of cached asset data
// FW.ASSET_INFO['BTC'] = {
// block: 0, // Block # when data was last updated
// ...
// }
// Define cache for reputation information ()
// We cache the data in order to reduce duplicate API calls as much as possible
FW.REPUTATION_INFO = {};
// Example of cached reputation data
// FW.REPUTATION_INFO['BTC'] = {
// block: 0, // Block # when data was last updated
// ...
// }
// Define cache for market information
// We cache the data in order to reduce duplicate API calls as much as possible
FW.MARKET_DATA = {};
// Example of cached market data
// FW.MARKET_DATA['BTC/XCP'] = {
// block: 0, // Block # when data was last updated
// basics: {}, // Basics (last price, high/low, volume)
// orderbook: {}, // Full Orderbook
// history: {}, // Full History
// trades: {}, // My Trades
// orders: {}, // My Open Orders
// chart: {}, // Chart data
// }
// Define cache for oracles
FW.ORACLES = {};
// Cache for cards from NFT projects
FW.NFT_CARDS = []; // placeholder
FW.NFT_DATA = JSON.parse(ls.getItem('nftInfo')) || []; // placeholder for raw NFT data
// Load any dust data encoding preferences (stored in sats)
FW.DUST_SIZE_REGULAR = JSON.parse(ls.getItem('dustSizeRegular')) || false;
FW.DUST_SIZE_MULTISIG = JSON.parse(ls.getItem('dustSizeMultisig')) || false;
// Define balance viewing options
FW.BALANCE_OPTIONS = JSON.parse(ls.getItem('walletBalanceOptions')) || [1,2,3]; // 1=named, 2=subasset, 3=numeric
// Lazy Loader config
FW.LAZY_LOAD_CONFIG = {
effect: 'fadeIn',
visibleOnly: true
};
// Define vars for donation system and load any saved preferences
FW.DONATE = {}; // donation causes cache
FW.DONATE_DEFAULT = 1000; // 1,000 satoshis
FW.DONATE_TRIGGER = 25000; // 25,000 satoshis (amount at which donation is actually added to a tx)
FW.DONATE_TOTAL = ls.getItem('donateTotal') || 0; // Track total donation until we hit FW.DONATE_TRIGGER
FW.DONATE_COUNT = ls.getItem('donateCount') || 0; // Track number of transactions
FW.DONATE_STATUS = ls.getItem('donateStatus') || 1; // 1=enabled, 0=disabled, #=% of txs
FW.DONATE_ADDRESS = ls.getItem('donateAddress') || 'bc1qd0nateja8l9am8tqpzjn9uazhf6dlp9qer2tra';
FW.DONATE_AMOUNT = ls.getItem('donateAmount') || FW.DONATE_DEFAULT;
// Load any auto-lock settings (default to 15 minutes)
FW.WALLET_AUTOLOCK = ls.getItem('walletAutoLock') || 15;
FW.WALLET_LAST_UNLOCKED = Date.now();
// Load UTXO usage preferences (default to use all UTXOS)
FW.UNCONFIRMED_UTXOS = ls.getItem('unconfirmedUtxos') || 1;
// Define cache for asset divisibility
FW.ASSET_DIVISIBLE = {};
FW.ASSET_DIVISIBLE['BTC'] = true;
FW.ASSET_DIVISIBLE['XCP'] = true;
// Start loading the wallet
$(document).ready(function(){
// Quick hack to blow away any old data from freewallet.io/browser
var old = ls.getItem("Balances");
if(old){
ls.clear();
ss.clear();
window.location.reload();
}
// If user has not already agreed to license agreement, display it
if(parseInt(ls.getItem('licenseAgreementAccept'))!=1)
dialogLicenseAgreement();
// If user has not already agreed to Automatic Donation System (ADS) agreement, display it
if(parseInt(ls.getItem('donateAgreementAccept'))!=1)
dialogDonateAgreement();
// Load the server information
var info = ls.getItem('serverInfo');
if(info)
FW.WALLET_SERVER_INFO = JSON.parse(info);
// Setup the xchain API url
setXChainAPI(FW.WALLET_NETWORK);
// Initialize the wallet
initWallet();
});
// Handle changing theme
function setTheme( theme ) {
var body = $('body');
body.removeClass();
body.addClass(theme);
}
// Handle getting XChain API url for given network
function getXChainAPI( network ){
var name = (network==2||network=='testnet') ? 'testnet' : 'mainnet',
o = FW.WALLET_SERVER_INFO[name],
url = ((o.api_ssl) ? 'https' : 'http') + '://' + o.api_host;
return url;
}
// Handle setting server information based off current network
function setXChainAPI( network ){
FW.XCHAIN_API = getXChainAPI(network);
}
// Handle checking for an updated wallet version
function checkWalletUpgrade(version, message){
$.ajax({
url: "https://freewallet.io/releases/current",
cache: false
}).done(function(current){
// Only proceed if we have a response/version
if(current){
var a = version.trim().split('.'),
b = current.trim().split('.'),
update = false;
// Check for any semantic versioning differences
if(parseInt(a[0])<parseInt(b[0])){ // Major
update = true;
} else if(parseInt(a[1])<parseInt(b[1])){ // Minor
update = true;
} else if(parseInt(a[2])<parseInt(b[2])){ // Patch
update = true;
}
// If an update is available, handle notifying the user
if(update)
dialogUpdateAvailable(current.trim());
else if(message)
dialogMessage('Current Release', 'You are running the latest version of FreeWallet', false, true);
}
});
}
// Handle loading content into the main panel
function loadPage(page){
var html = page + '.html';
// Handle mapping pages to correct content
if(page=='betting'){
// html = (checkTokenAccess()) ? 'betting/index.html' : 'betting/betting.html';
html = 'betting/betting.html';
}
if(page=='dispensers') html = 'dispensers/index.html';
if(page=='exchange') html = 'exchange/markets.html';
if(page=='market') html = 'exchange/market.html';
// Load the page content and switch the tab to active
$('#main-content-panel').load('html/' + html);
$('.header .navbar-nav li > a').removeClass('active');
$('#' + page).addClass('active');
}
// Initialize / Load the wallet
function initWallet(){
if(ss.getItem('wallet') == null){
if(ls.getItem('wallet')){
if(FW.WALLET_ENCRYPTED){
// Try to unlock the wallet when app first opens
// if(parseInt(ss.getItem('skipWalletAuth'))!=1)
// dialogPassword();
} else {
decryptWallet();
}
} else {
dialogWelcome();
}
} else {
// Decrypt the wallet using the current password (do this so we populate FW.WALLET_KEYS)
decryptWallet(getWalletPassword());
}
// Check if we have everything needed to authorize Auto-BTCpay transactions
checkBtcpayAuth();
// Trigger an immediate check of if we need to update the wallet information (prices/balances)
checkUpdateWallet();
// Check every 60 seconds if we should update the wallet information
setInterval(checkUpdateWallet, 60000);
updateWalletOptions();
// Populate the oracle list
updateOracleList();
// Populate the donation list
updateDonationList();
// Populate FW.NFT_CARDS
updateNFTCards();
}
// Reset/Remove wallet
function resetWallet(){
ls.removeItem('wallet');
ls.removeItem('walletKeys');
ls.removeItem('walletPassword');
ls.removeItem('walletEncrypted');
ls.removeItem('walletAddress');
ls.removeItem('walletAddresses');
ls.removeItem('walletAddressLabel');
ls.removeItem('walletBalances');
ls.removeItem('walletBalanceOptions');
ls.removeItem('walletFormat');
ls.removeItem('walletHistory');
ls.removeItem('walletNetwork');
ls.removeItem('walletMarkets');
ls.removeItem('walletMarketOptions');
ls.removeItem('walletDispeners');
ls.removeItem('walletDispenserOptions');
ls.removeItem('btcpayOrders');
ls.removeItem('btcpayMatches');
ls.removeItem('btcpayQueue');
ss.removeItem('btcpayWallet');
ss.removeItem('wallet');
ss.removeItem('walletPassword');
ss.removeItem('skipWalletAuth');
FW.WALLET_ADDRESS = null;
FW.WALLET_ADDRESSES = []
FW.WALLET_BALANCES = [];
FW.WALLET_HISTORY = [];
FW.WALLET_KEYS = {};
FW.WALLET_FORMAT = 0;
FW.WALLET_ENCRYPTED = 0;
FW.BTCPAY_ORDERS = {};
FW.BTCPAY_MATCHES = {};
FW.BTCPAY_QUEUE = {};
FW.BTCPAY_ORDERS = {}
FW.BASE_MARKETS = FW.DEFAULT_MARKETS;
FW.BASE_DISPENSERS = FW.DEFAULT_DISPENSERS;
}
// Function to handle generating a passphrase
function generateWalletPassphrase(isBip39=false){
var passphrase = false;
if(isBip39){
passphrase = bip39.generateMnemonic();
} else {
passphrase = new Mnemonic(128).toWords().toString().replace(/,/gi, " ");
}
return passphrase;
}
// Create HD wallet
function createWallet( passphrase, isBip39=false ){
var wallet = false;
// Generate a passphrase if one is not passed
if(!passphrase)
passphrase = generateWalletPassphrase(isBip39);
// Support BIP39 and counterwallet's shorter wordlist
if(isBip39){
wallet = bip39.mnemonicToEntropy(passphrase);
} else {
wallet = Mnemonic.fromWords(passphrase.trim().split(" ")).toHex();
}
var password = Math.random().toString(36).substring(3), // Generate random password
privkeys = JSON.stringify(FW.WALLET_KEYS),
encWallet = CryptoJS.AES.encrypt(wallet, String(password)).toString(),
encKeys = CryptoJS.AES.encrypt(privkeys, String(password)).toString();
ss.setItem('wallet', wallet);
ss.setItem('walletPassword', password);
ls.setItem('wallet', encWallet);
ls.setItem('walletKeys', encKeys);
ls.setItem('walletPassword', password);
ls.setItem('walletEncrypted',0);
ls.setItem('walletNetwork',1);
ss.removeItem('skipWalletAuth');
// Set the wallet format (0 = Counterwallet, 1=BIP39)
FW.WALLET_FORMAT = (isBip39) ? 1 : 0;
ls.setItem('walletFormat', FW.WALLET_FORMAT); //
// Add the first 10 addresses to the wallet (both mainnet and testnet)
var networks = ['mainnet','testnet'];
networks.forEach(function(net){
for(var i=0;i<10;i++){
addNewWalletAddress(net, 'normal');
addNewWalletAddress(net, 'bech32');
}
});
// Set current address to first address in wallet
// This also handles saving FW.WALLET_ADDRESSES to disk
setWalletAddress(getWalletAddress(0), true);
}
// Handle generating a new indexed address and adding it to the wallet
function addNewWalletAddress(net=1, type='normal'){
// Force network to numeric value and net to string value
var ls = localStorage;
net = (net=='testnet' || net==2) ? 2 : 1;
network = (net==2) ? 'testnet' : 'mainnet',
addrtype = 1, // 1=Normal, 7=Bech32, 8=Taproot
address = false;
// Normalize types
if(type=='p2pkh')
type = 'normal';
if(type=='segwit')
type = 'bech32';
// Set the address type
if(type=='bech32')
addrtype = 7;
if(type=='taproot')
addrtype = 8;
// Lookup the highest indexed address so far
var idx = 0,
init = true;
FW.WALLET_ADDRESSES.forEach(function(item){
if(item.type==addrtype && item.network==net){
init = false;
if(item.index>idx)
idx = item.index;
}
});
// Increase index for new address
if(!init)
idx++;
// Generate new address
var w = getWallet(),
n = bc.Networks[network],
s = bc.HDPrivateKey.fromSeed(w, n),
d = s.derive("m/0'/0/" + idx);
label = 'Address #' + (idx + 1);
// Support generating Normal Addresses (P2PKH)
if(type=='normal')
address = bc.Address(d.publicKey, n).toString();
// Support generating Bech32 Addresses (Segwit)
if(type=='bech32'){
var netname = (net==2) ? 'testnet' : 'bitcoin';
var address = bitcoinjs.payments.p2wpkh({ pubkey: d.publicKey.toBuffer(), network: bitcoinjs.networks[netname] }).address;
label = 'Segwit ' + label;
}
// Support generating Taproot Addresses (Segwit)
if(type=='taproot'){
// Coming soon
label = 'Taproot ' + label;
}
// Add the address to the wallet
addWalletAddress(network, address, label, addrtype, idx);
// Save wallet addresses info to disk
ls.setItem('walletAddresses', JSON.stringify(FW.WALLET_ADDRESSES));
return address;
}
// Decrypt wallet
function decryptWallet( password ){
var encWallet = ls.getItem('wallet'),
encKeys = ls.getItem('walletKeys') || '',
password = (password) ? password : ls.getItem('walletPassword'),
wallet = CryptoJS.AES.decrypt(encWallet, String(password)).toString(CryptoJS.enc.Utf8),
privkeys = CryptoJS.AES.decrypt(encKeys, String(password)).toString(CryptoJS.enc.Utf8);
// Save wallet to session storage
ss.setItem('wallet', wallet);
// Parse private keys into FW.WALLET_KEYS
FW.WALLET_KEYS = JSON.parse(privkeys);
// Save the current wallet password (so we can re-encrypt things without needing to re-prompt the user for pass)
ss.setItem('walletPassword', password);
// Remove any skip wallet authorization flag
ss.removeItem('skipWalletAuth');
}
// Decrypt wallet
function encryptWallet( password, skip=false ){
var wallet = getWallet(),
password = (password) ? password : ls.getItem('walletPassword'),
privkeys = JSON.stringify(FW.WALLET_KEYS),
encWallet = CryptoJS.AES.encrypt(wallet, String(password)).toString(),
encPass = CryptoJS.AES.encrypt(password, String(password)).toString(),
encKeys = CryptoJS.AES.encrypt(privkeys, String(password)).toString();
// Save the encrypted data to disk
ls.setItem('wallet', encWallet);
// Mark wallet as encrypted and save encrypted password unless instructed not to
if(!skip){
FW.WALLET_ENCRYPTED = 1;
ls.setItem('walletEncrypted',FW.WALLET_ENCRYPTED);
ls.setItem('walletPassword', encPass);
}
ls.setItem('walletKeys', encKeys);
// Remove any skip wallet authorization flag
ss.removeItem('skipWalletAuth');
}
// Get decrypted wallet from sessionStorage
function getWallet(){
return ss.getItem('wallet');
}
// Get decrypted wallet password from sessionStorage
function getWalletPassword(){
return ss.getItem('walletPassword');
}
// Get 12-word passphrase
function getWalletPassphrase(){
var w = getWallet(),
p = false;
if(w){
// Counterwallet's Mnemonic wordlist
if(FW.WALLET_FORMAT==0)
p = Mnemonic.fromHex(w).toWords().toString().replace(/,/gi, " ");
// BIP39 wordlist
if(FW.WALLET_FORMAT==1)
p = bip39.entropyToMnemonic(w);
if(p)
return p;
}
return false;
}
// Handle locking wallet by removing decrypted wallet from sessionStorage
function lockWallet(){
ss.removeItem('wallet');
ss.removeItem('walletPassword')
FW.WALLET_KEYS = {};
}
// Get wallet addresses using given index
function getWalletAddress( index ){
// console.log('getWalletAddress index=',index);
// update network (used in CWBitcore)
var net = (FW.WALLET_NETWORK==2) ? 'testnet' : 'mainnet',
NETWORK = bc.Networks[net];
if(typeof index === 'number'){
// var type
var w = getWallet(),
a = null;
if(w){
k = bc.HDPrivateKey.fromSeed(w, NETWORK),
d = k.derive("m/0'/0/" + index),
a = bc.Address(d.publicKey, NETWORK).toString();
} else {
dialogMessage('<i class="fa fa-lg fa-fw fa-exclamation-circle"></i> Error(s)', errors.join('<br/>') );
}
return a;
} else {
return ls.getItem('walletAddress');
}
}
// Set wallet address
function setWalletAddress( address, load=0 ){
// console.log('setWalletAddress address, load=',address,load);
FW.WALLET_ADDRESS = address;
var info = getWalletAddressInfo(address);
if(!info)
info = addWalletAddress(address);
// Save the label info to disk
if(info){
FW.WALLET_ADDRESS_LABEL = info.label;
ls.setItem('walletAddressLabel', FW.WALLET_ADDRESS_LABEL);
}
// Save updated information to disk
ls.setItem('walletAddress', address);
ls.setItem('walletAddresses', JSON.stringify(FW.WALLET_ADDRESSES));
// Update the wallet display to reflect the new address
updateWalletOptions();
if(load)
checkUpdateWallet();
}
// Handle adding addresses to FW.WALLET_ADDRESSES array
function addWalletAddress( network=1, address='', label='', type=1, index='', path='' ){
// console.log('addWalletAddress network,address,label,type,index=',network,address,label,type,index, path);
// Bail out if no address is passed
if(address=='')
return;
// Bail out if address already exists
var found = false;
FW.WALLET_ADDRESSES.forEach(function(item){
if(item.address==address)
found = true;
});
if(found)
return;
// Convert network to integer value
if(typeof network == 'string')
network = (network=='testnet') ? 2 : 1;
var info = {
address: address, // Address to add
network: network, // Default to mainnet (1=mainnet, 2=testnet)
label: label, // Default to blank label
type: type, // 1=indexed, 2=imported (privkey), 3=watch-only, 4=trezor, 5=ledger, 6=keepkey, 7=bech32, 8=taproot
path: path, // node path for address (ex: m/44'/0'/0)
index: index // wallet address index (used in address sorting)
};
FW.WALLET_ADDRESSES.push(info);
return info;
}
// Handle removing an address from the wallet
function removeWalletAddress( address ){
// Remove the address from FW.WALLET_ADDRESSES array
var arr = [];
FW.WALLET_ADDRESSES.forEach(function(item){
if(item.address!=address)
arr.push(item);
});
FW.WALLET_ADDRESSES = arr;
// Remove any private keys associated with the address
if(FW.WALLET_KEYS[address])
delete FW.WALLET_KEYS[address];
// Save wallet addresses info to disk
ls.setItem('walletAddresses', JSON.stringify(FW.WALLET_ADDRESSES));
// Re-encrypt the wallet with the last known valid password
encryptWallet(getWalletPassword(), true);
}
// Handle returning the information from FW.WALLET_ADDRESSES for a given address
function getWalletAddressInfo( address ){
var info = false;
FW.WALLET_ADDRESSES.forEach(function(item){
if(item.address==address)
info = item;
});
return info;
}
// Handle updating wallet address labels (friendly names)
function setWalletAddressLabel( address, label ){
FW.WALLET_ADDRESSES.forEach(function(item, idx){
if(item.address==address)
FW.WALLET_ADDRESSES[idx].label = label;
});
// Save the label info to disk
FW.WALLET_ADDRESS_LABEL = label;
ls.setItem('walletAddressLabel', label);
// Save updated wallet addresses array to disk
ls.setItem('walletAddresses', JSON.stringify(FW.WALLET_ADDRESSES));
}
// Handle setting the wallet network (1=mainnet/2=testnet)
function setWalletNetwork(network, load=false){
ls.setItem('walletNetwork', network);
FW.WALLET_NETWORK = network;
// Reset exchange/market/asset/reputation info
FW.EXCHANGE_MARKETS = {};
FW.DISPENSERS = {};
FW.ASSET_INFO = {};
FW.REPUTATION_INFO = {};
// Update the xchain API url
setXChainAPI(network);
// Set current address to first address in wallet
setWalletAddress(getWalletAddress(0), load);
}
// Handle adding private key to wallet
function addWalletPrivkey(key){
// Verify that the private key is added
var net = FW.WALLET_NETWORK, // Numeric
network = (net==2) ? 'testnet' : 'mainnet', // Text
ls = localStorage,
n = false,
address = false,
sanitizedKey = key.replace('p2wpkh:', '');
// Try to generate a public key and address using the key
try {
privkey = new bc.PrivateKey.fromWIF(sanitizedKey);
pubkey = privkey.toPublicKey();
if (key.includes('p2wpkh:')){
n = bitcoinjs.networks[network];
address = bitcoinjs.payments.p2wpkh({ pubkey: pubkey.toBuffer(), network: n }).address;
}else{
n = bc.Networks[network];
address = pubkey.toAddress(n).toString();
}
} catch (e){
console.log('error : ',e);
}
// Add wallet to address
if(address){
// Check if the address has alreaday been added to the list
var found = false,
cnt = 0;
FW.WALLET_ADDRESSES.forEach(function(item){
if(item.address==address)
found = true;
if(item.network==net && item.type==2)
cnt++;
});
if(!found){
// Add the address to the wallet
addWalletAddress(network, address, 'Imported Address #' + (cnt + 1), 2, null);
// Save wallet addresses info to disk
ls.setItem('walletAddresses', JSON.stringify(FW.WALLET_ADDRESSES));
// Add address and private key to keys array
FW.WALLET_KEYS[address] = sanitizedKey;
// Re-encrypt the wallet with the last known valid password
encryptWallet(getWalletPassword(), true);
}
}
return address;
}
// Validate wallet password
function isValidWalletPassword( password ){
var p = ls.getItem('walletPassword'),
d = false;
// Try to decrypt the encrypted password using the given password
try {
d = CryptoJS.AES.decrypt(p, String(password)).toString(CryptoJS.enc.Utf8);
} catch(e){
}
if(d==password)
return true
return false;
}
// Validate wallet passphrase
function isValidWalletPassphrase( passphrase, isBip39=false ){
var arr = passphrase.trim().split(" "),
valid = true;
if(arr.length<12)
valid = false;
for(var i=0;i<arr.length;i++){
if(isBip39){
if($.inArray(arr[i], bip39.wordlists.english)==-1)
valid = false;
} else {
if($.inArray(arr[i], Mnemonic.words)==-1)
valid = false;
}
}
return valid;
}
// Validate address
function isValidAddress(addr){
var net = (FW.WALLET_NETWORK==2) ? 'testnet' : 'mainnet';
// update network (used in CWBitcore)
NETWORK = bc.Networks[net];
if(CWBitcore.isValidAddress(addr))
return true;
return false;
}
// Validate if we are running in nwjs or not
function is_nwjs(){
try{
return (typeof require('nw.gui') !== "undefined");
} catch (e){
return false;
}
}
// Display correct wallet options based on wallet status
function updateWalletOptions(){
// Handle updating lock/unlock icon based on state
var icon = $('#lock > i'),
lock = $('#lock');
if(!ss.getItem('wallet')){
icon.removeClass('fa-unlock').addClass('fa-lock');
lock.attr('data-original-title','<div class="nowrap">Unlock Wallet</div>');
} else {
icon.removeClass('fa-lock').addClass('fa-unlock');
lock.attr('data-original-title', '<div class="nowrap">Lock Wallet</div>');
}
// Handle updating the settings screen
$('#settings-address').val(FW.WALLET_ADDRESS);
$('#settings-network').val(FW.WALLET_NETWORK);
$('#settings-address-label').val(FW.WALLET_ADDRESS_LABEL);
// Handle updating footer info
var net = (FW.WALLET_NETWORK==2) ? 'testnet' : 'mainnet';
last = ls.getItem('networkInfoLastUpdated') || '',
block = (FW.NETWORK_INFO.network_info) ? FW.NETWORK_INFO.network_info[net].block_height : 'NA';
$('.footer-current-block').text('Block ' + numeral(block).format('0,0'));
$('.footer-last-updated').html('Last updated <span data-livestamp=' + last.substr(0,last.length-3) + ' class="nowrap"></span>');
$('.footer-current-price').text('$' + numeral(getAssetPrice('XCP')).format('0,0.00') + ' USD');
var info = getWalletAddressInfo(FW.WALLET_ADDRESS);
if(info.type==3){
$('#action-view-privkey').hide();
$('#action-send').hide();
$('#action-sign-message').hide();
$('#action-sign-transaction').hide();
$('#action-dividend').hide();
$('#action-broadcast-message').hide();
$('#header-token-actions').hide();
$('#action-asset-create').hide();
$('#action-asset-description').hide();
$('#action-asset-supply').hide();
$('#action-asset-transfer').hide();
$('#action-asset-lock').hide();
} else {
$('#action-view-privkey').show();
$('#action-send').show();
$('#action-sign-message').show();
$('#action-sign-transaction').show();
$('#action-dividend').show();
$('#action-broadcast-message').show();
$('#header-token-actions').show();
$('#action-asset-create').show();
$('#action-asset-description').show();
$('#action-asset-supply').show();
$('#action-asset-transfer').show();
$('#action-asset-lock').show();
}
}
// Handle looking up asset price from FW.NETWORK_INFO
function getAssetPrice(id, full){
var price = false;
for(var key in FW.NETWORK_INFO.currency_info){
var item = FW.NETWORK_INFO.currency_info[key];
if(item.id==id||item.symbol==id||name==id){
if(full)
price = item;
else
price = item.price_usd;
}
}
return price;
}
// Handle retrieving asset information from xchain and handing the data to a callback function
// We cache the information between blocks to reduce the number of duplicate API calls
function getAssetInfo(asset, callback, force){
var net = (FW.WALLET_NETWORK==2) ? 'testnet' : 'mainnet',
block = (FW.NETWORK_INFO.network_info) ? FW.NETWORK_INFO.network_info[net].block_height : 1,
data = FW.ASSET_INFO[asset] || false,
last = (data) ? data.block : 0,
update = (block > last || data.init ||force) ? true : false;
// Initialize the asset data cache
if(!FW.ASSET_INFO[asset])
FW.ASSET_INFO[asset] = {}
if(update){
$.getJSON( FW.XCHAIN_API + '/api/asset/' + asset, function( o ){
o.block = block;
o.collapsed = data.collapsed;
FW.ASSET_INFO[asset] = o;
if(typeof callback === 'function')
callback(o);
});
} else {
callback(data);
}
}
// Handle retrieving asset reputation info from coindaddy and handing the data to a callback function
// We cache the information between blocks to reduce the number of duplicate API calls
function getAssetReputationInfo(asset, callback, force){
var net = (FW.WALLET_NETWORK==2) ? 'testnet' : 'mainnet',
block = (FW.NETWORK_INFO.network_info) ? FW.NETWORK_INFO.network_info[net].block_height : 1,
data = FW.REPUTATION_INFO[asset] || false,
last = (data) ? data.block : 0,
update = (block > last || force) ? true : false;
// Initialize the asset data cache
if(!FW.REPUTATION_INFO[asset])
FW.REPUTATION_INFO[asset] = {}
if(update){
$.getJSON('https://reputation.coindaddy.io/api/asset/xcp/' + asset, function( data ){
data.block = block;
FW.REPUTATION_INFO[asset] = data;
if(typeof callback === 'function')
callback(data);
});
} else {
callback(data);
}
}
// Check if wallet price/balance info should be updated
function checkUpdateWallet(){
updateNetworkInfo();
checkBtcpayTransactions();
var addr = getWalletAddress();
if(addr){
updateWalletBalances(addr);
updateWalletHistory(addr);
if(typeof updateDispensersLists === 'function')
updateDispensersLists();
}
updateNFTInfo();
checkAutoLock();
};
// Check if we should auto-lock wallet based on the users preferences
function checkAutoLock(){
// If wallet is encrypted, unlocked, auto-lock is enabled, and we are past the auto-lock time, then lock the wallet
if(FW.WALLET_ENCRYPTED && ss.getItem('wallet') && FW.WALLET_AUTOLOCK>0 && (FW.WALLET_LAST_UNLOCKED + (FW.WALLET_AUTOLOCK * 60 * 1000)) < Date.now()){
lockWallet();
updateWalletOptions();
}
}
// Handle checking for special tokens to enable access to features
// Check access each time a feature is accessed instead of setting a localStorage flag (make it a pain to access feature without access token)
function checkTokenAccess(feature){
var assets = ['XCHAINPEPE','FULLACCESS'],
access = false;
// Loop through all addresses except watch-only addresses (ownership not proven)
FW.WALLET_ADDRESSES.forEach(function(item){
if(item.type!=3){
FW.WALLET_BALANCES.forEach(function(itm){
if(itm.address==item.address){
itm.data.forEach(function(balance){
if(assets.indexOf(balance.asset)!=-1 && parseFloat(balance.quantity)>=1)
access = true;
});
}
});
}
});
return access;
}
// Handle verifying that we have wallet seed available for BTCpay transactions
function checkBtcpayAuth(){
// console.log('checkBtcpayAuth FW.BTCPAY_ORDERS=',FW.BTCPAY_ORDERS);
var enabled = false;
$.each(['mainnet','testnet'],function(ndx, network){
$.each(FW.BTCPAY_ORDERS[network], function(address, orders){
$.each(orders, function(order, autopay){
if(autopay==1)
enabled = true;
});
});
});
// If Auto-BTCpay is enabled, make sure we have unlocked wallet available
var a = ss.getItem('btcpayWallet'),
b = ss.getItem('wallet');
if(enabled && a==null){
if(b){
ss.setItem('btcpayWallet',b);
} else {
dialogEnableBtcpay();
}
}
}
// Check the status of any btcpay transactions
function checkBtcpayTransactions( force ){
// console.log('checkBtcpayTransactions');
var ls = localStorage,
last = ls.getItem('btcpayLastUpdated') || 0,
ms = 300000, // 5 minutes
save = false;
// Handle requesting updated order match information
if((parseInt(last) + ms) <= Date.now() || force ){
$.each(['mainnet','testnet'], function(idx, network){
$.each(FW.BTCPAY_ORDERS[network], function(address, orders){
// Only request data if we have orders to monitor
if(Object.keys(orders).length){
// Set XChain url
var info = FW.WALLET_SERVER_INFO[network],
host = ((info.api_ssl) ? 'https' : 'http') + '://' + info.api_host;
url = host + '/api/order_matches/' + address;
// Request order match data for the given address
$.getJSON(url, function(o){
if(!o.error){
$.each(o.data,function(ndx,data){
$.each(orders, function(order, autopay){
// Find any pending order matches that we care about
if(data.status=='pending' && (data.tx0_hash==order||data.tx1_hash==order)){
var tx = (data.tx0_hash==order) ? data.tx1_hash : data.tx0_hash, // tx hash of the other side of the order match
src = (data.tx0_hash==order) ? data.tx0_address : data.tx1_address; // source address for our order
// Initialize the BTCPAY objects if needed
if(!FW.BTCPAY_QUEUE[network])
FW.BTCPAY_QUEUE[network] = [];
if(!FW.BTCPAY_MATCHES[network])
FW.BTCPAY_MATCHES[network] = {};
if(!FW.BTCPAY_MATCHES[network][order])
FW.BTCPAY_MATCHES[network][order] = [];
// Detect any orders we have not already seen
if(FW.BTCPAY_MATCHES[network][order].indexOf(tx)==-1){
// Add tx hash to BTCPAY_MATCHES so we know we have already detected this transaction
FW.BTCPAY_MATCHES[network][order].push(tx);
// Add tx info to BTCPAY_QUEUE so we can process
data.autopay = autopay;
data.source = src;
FW.BTCPAY_QUEUE[network].push(data);
// Set flag to indicate we should save updated data
save = true;
}
}
});
});
// Save updated data to disk
if(save){
ls.setItem('btcpayMatches',JSON.stringify(FW.BTCPAY_MATCHES));
ls.setItem('btcpayQueue',JSON.stringify(FW.BTCPAY_QUEUE));
}
// Handle processing any BTCpay transaction
processBtcpayQueue();
}