-
Notifications
You must be signed in to change notification settings - Fork 320
/
MbwManager.java
1276 lines (1090 loc) · 47.8 KB
/
MbwManager.java
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
/*
* Copyright 2013, 2014 Megion Research and Development GmbH
*
* Licensed under the Microsoft Reference Source License (MS-RSL)
*
* This license governs use of the accompanying software. If you use the software, you accept this license.
* If you do not accept the license, do not use the software.
*
* 1. Definitions
* The terms "reproduce," "reproduction," and "distribution" have the same meaning here as under U.S. copyright law.
* "You" means the licensee of the software.
* "Your company" means the company you worked for when you downloaded the software.
* "Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes
* of debugging your products, maintaining your products, or enhancing the interoperability of your products with the
* software, and specifically excludes the right to distribute the software outside of your company.
* "Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor
* under this license.
*
* 2. Grant of Rights
* (A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive,
* worldwide, royalty-free copyright license to reproduce the software for reference use.
* (B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive,
* worldwide, royalty-free patent license under licensed patents for reference use.
*
* 3. Limitations
* (A) No Trademark License- This license does not grant you any rights to use the Licensor’s name, logo, or trademarks.
* (B) If you begin patent litigation against the Licensor over patents that you think may apply to the software
* (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically.
* (C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties,
* guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot
* change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability,
* fitness for a particular purpose and non-infringement.
*/
package com.mycelium.wallet;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.EvictingQueue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.mrd.bitlib.crypto.*;
import com.mrd.bitlib.model.Address;
import com.mrd.bitlib.model.NetworkParameters;
import com.mrd.bitlib.util.BitUtils;
import com.mrd.bitlib.util.CoinUtil;
import com.mrd.bitlib.util.CoinUtil.Denomination;
import com.mrd.bitlib.util.HashUtils;
import com.mycelium.WapiLogger;
import com.mycelium.lt.api.LtApiClient;
import com.mycelium.net.ServerEndpointType;
import com.mycelium.net.TorManager;
import com.mycelium.net.TorManagerOrbot;
import com.mycelium.wallet.activity.modern.ExploreHelper;
import com.mycelium.wallet.activity.util.BlockExplorer;
import com.mycelium.wallet.activity.util.BlockExplorerManager;
import com.mycelium.wallet.activity.util.Pin;
import com.mycelium.wallet.api.AndroidAsyncApi;
import com.mycelium.wallet.bitid.ExternalService;
import com.mycelium.wallet.coinapult.CoinapultManager;
import com.mycelium.wallet.event.*;
import com.mycelium.wallet.extsig.common.ExternalSignatureDeviceManager;
import com.mycelium.wallet.extsig.keepkey.KeepKeyManager;
import com.mycelium.wallet.extsig.ledger.LedgerManager;
import com.mycelium.wallet.extsig.trezor.TrezorManager;
import com.mycelium.wallet.lt.LocalTraderManager;
import com.mycelium.wallet.persistence.MetadataStorage;
import com.mycelium.wallet.persistence.TradeSessionDb;
import com.mycelium.wallet.wapi.SqliteWalletManagerBackingWrapper;
import com.mycelium.wapi.api.WapiClient;
import com.mycelium.wapi.wallet.*;
import com.mycelium.wapi.wallet.bip44.Bip44Account;
import com.mycelium.wapi.wallet.bip44.Bip44AccountContext;
import com.mycelium.wapi.wallet.bip44.ExternalSignatureProviderProxy;
import com.mycelium.wapi.wallet.single.SingleAddressAccount;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import static java.util.concurrent.TimeUnit.SECONDS;
public class MbwManager {
public static final String PROXY_HOST = "socksProxyHost";
public static final String PROXY_PORT = "socksProxyPort";
public static final String SELECTED_ACCOUNT = "selectedAccount";
private static volatile MbwManager _instance = null;
/**
* The root index we use for generating authentication keys.
* 0x80 makes the number negative == hardened key derivation
* 0x424944 = "BID"
*/
private static final int BIP32_ROOT_AUTHENTICATION_INDEX = 0x80424944;
private Optional<CoinapultManager> _coinapultManager;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private AtomicBoolean lastPinAgeOkay = new AtomicBoolean(false);
private ScheduledFuture<?> pinOkTimeoutHandle;
private int failedPinCount = 0;
private final CurrencySwitcher _currencySwitcher;
private boolean startUpPinUnlocked = false;
private Timer _addressWatchTimer;
public static synchronized MbwManager getInstance(Context context) {
if (_instance == null) {
_instance = new MbwManager(context);
}
return _instance;
}
private final Bus _eventBus;
private final ExternalSignatureDeviceManager _trezorManager;
private final KeepKeyManager _keepkeyManager;
private final LedgerManager _ledgerManager;
private final WapiClient _wapi;
private final LtApiClient _ltApi;
private Handler _torHandler;
private Context _applicationContext;
private AddressBookManager _addressBookManager;
private MetadataStorage _storage;
private LocalTraderManager _localTraderManager;
private Pin _pin;
private boolean _pinRequiredOnStartup;
private MinerFee _minerFee;
private boolean _enableContinuousFocus;
private boolean _keyManagementLocked;
private MrdExport.V1.EncryptionParameters _cachedEncryptionParameters;
private final MrdExport.V1.ScryptParameters _deviceScryptParameters;
private MbwEnvironment _environment;
private final ExploreHelper _exploreHelper;
private HttpErrorCollector _httpErrorCollector;
private String _language;
private final VersionManager _versionManager;
private final ExchangeRateManager _exchangeRateManager;
private final WalletManager _walletManager;
private WalletManager _tempWalletManager;
private final RandomSource _randomSource;
private final EventTranslator _eventTranslator;
private ServerEndpointType.Types _torMode;
private TorManager _torManager;
public final BlockExplorerManager _blockExplorerManager;
private EvictingQueue<LogEntry> _wapiLogs = EvictingQueue.create(100);
private Cache<String, Object> _semiPersistingBackgroundObjects = CacheBuilder.newBuilder().maximumSize(10).build();
private MbwManager(Context evilContext) {
_applicationContext = Preconditions.checkNotNull(evilContext.getApplicationContext());
_environment = MbwEnvironment.verifyEnvironment(_applicationContext);
String version = VersionManager.determineVersion(_applicationContext);
// Preferences
SharedPreferences preferences = getPreferences();
// setProxy(preferences.getString(Constants.PROXY_SETTING, ""));
// Initialize proxy early, to enable error reporting during startup..
_eventBus = new Bus();
_eventBus.register(this);
// init tor - if needed
try {
setTorMode(ServerEndpointType.Types.valueOf(preferences.getString(Constants.TOR_MODE, "")));
} catch (IllegalArgumentException ex) {
setTorMode(ServerEndpointType.Types.ONLY_HTTPS);
}
_wapi = initWapi();
_httpErrorCollector = HttpErrorCollector.registerInVM(_applicationContext, _wapi);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.GINGERBREAD) {
// Disable HTTP keep-alive on systems predating Gingerbread
System.setProperty("http.keepAlive", "false");
}
_randomSource = new AndroidRandomSource();
// Local Trader
TradeSessionDb tradeSessionDb = new TradeSessionDb(_applicationContext);
_ltApi = initLt();
_localTraderManager = new LocalTraderManager(_applicationContext, tradeSessionDb, getLtApi(), this);
_pin = new Pin(
preferences.getString(Constants.PIN_SETTING, ""),
preferences.getString(Constants.PIN_SETTING_RESETTABLE, "1").equals("1")
);
_pinRequiredOnStartup = preferences.getBoolean(Constants.PIN_SETTING_REQUIRED_ON_STARTUP, false);
_minerFee = MinerFee.fromString(preferences.getString(Constants.MINER_FEE_SETTING, MinerFee.NORMAL.toString()));
_enableContinuousFocus = preferences.getBoolean(Constants.ENABLE_CONTINUOUS_FOCUS_SETTING, false);
_keyManagementLocked = preferences.getBoolean(Constants.KEY_MANAGEMENT_LOCKED_SETTING, false);
// Get the display metrics of this device
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) _applicationContext.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
_addressBookManager = new AddressBookManager(_applicationContext);
_storage = new MetadataStorage(_applicationContext);
_exploreHelper = new ExploreHelper();
_language = preferences.getString(Constants.LANGUAGE_SETTING, Locale.getDefault().getLanguage());
_versionManager = new VersionManager(_applicationContext, _language, new AndroidAsyncApi(_wapi, _eventBus), version, _eventBus);
Set<String> currencyList = getPreferences().getStringSet(Constants.SELECTED_CURRENCIES, null);
Set<String> fiatCurrencies = new HashSet<String>();
if (currencyList == null) {
//if there is no list take the default currency
fiatCurrencies.add(Constants.DEFAULT_CURRENCY);
} else {
//else take all dem currencies, yeah
fiatCurrencies.addAll(currencyList);
}
_exchangeRateManager = new ExchangeRateManager(_applicationContext, _wapi);
_currencySwitcher = new CurrencySwitcher(
_exchangeRateManager,
fiatCurrencies,
getPreferences().getString(Constants.FIAT_CURRENCY_SETTING, Constants.DEFAULT_CURRENCY),
Denomination.fromString(preferences.getString(Constants.BITCOIN_DENOMINATION_SETTING, Denomination.BTC.toString()))
);
// Check the device MemoryClass and set the scrypt-parameters for the PDF backup
ActivityManager am = (ActivityManager) _applicationContext.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
_deviceScryptParameters = memoryClass > 20
? MrdExport.V1.ScryptParameters.DEFAULT_PARAMS
: MrdExport.V1.ScryptParameters.LOW_MEM_PARAMS;
_trezorManager = new TrezorManager(_applicationContext, getNetwork(), getEventBus());
_keepkeyManager = new KeepKeyManager(_applicationContext, getNetwork(), getEventBus());
_ledgerManager = new LedgerManager(_applicationContext, getNetwork(), getEventBus());
_walletManager = createWalletManager(_applicationContext, _environment);
_eventTranslator = new EventTranslator(new Handler(), _eventBus);
_exchangeRateManager.subscribe(_eventTranslator);
_walletManager.addObserver(_eventTranslator);
_coinapultManager = createCoinapultManager();
if (_coinapultManager.isPresent()) {
addExtraAccounts(_coinapultManager.get());
}
// set the currency-list after we added all extra accounts, they may provide
// additional needed fiat currencies
setCurrencyList(fiatCurrencies);
migrateOldKeys();
createTempWalletManager();
_versionManager.initBackgroundVersionChecker();
_blockExplorerManager = new BlockExplorerManager(this,
_environment.getBlockExplorerList(),
getPreferences().getString(Constants.BLOCK_EXPLORER,
_environment.getBlockExplorerList().get(0).getIdentifier()));
}
public void addExtraAccounts(AccountProvider accounts) {
_walletManager.addExtraAccounts(accounts);
_hasCoinapultAccounts = null; // invalidate cache
}
@Subscribe()
public void onExtraAccountsChanged(ExtraAccountsChanged event) {
_walletManager.refreshExtraAccounts();
_hasCoinapultAccounts = null; // invalidate cache
}
private Optional<CoinapultManager> createCoinapultManager() {
if (_walletManager.hasBip32MasterSeed() && _storage.isPairedService(MetadataStorage.PAIRED_SERVICE_COINAPULT)) {
BitIdKeyDerivation derivation = new BitIdKeyDerivation() {
@Override
public InMemoryPrivateKey deriveKey(int accountIndex, String site) {
try {
Bip39.MasterSeed masterSeed = _walletManager.getMasterSeed(AesKeyCipher.defaultKeyCipher());
return createBip32WebsitePrivateKey(masterSeed.getBip32Seed(), accountIndex, site);
} catch (KeyCipher.InvalidKeyCipher invalidKeyCipher) {
throw new RuntimeException(invalidKeyCipher);
}
}
};
return Optional.of(new CoinapultManager(
_environment,
derivation,
_eventBus,
new Handler(_applicationContext.getMainLooper()),
_storage,
_exchangeRateManager,
retainingWapiLogger));
} else {
return Optional.absent();
}
}
private void createTempWalletManager() {
//for managing temp accounts created through scanning
_tempWalletManager = createTempWalletManager(_environment);
_tempWalletManager.addObserver(_eventTranslator);
}
private LtApiClient initLt() {
return new LtApiClient(_environment.getLtEndpoints(), new LtApiClient.Logger() {
@Override
public void logError(String message, Exception e) {
Log.e("", message, e);
retainLog(Level.SEVERE, message);
}
@Override
public void logError(String message) {
Log.e("", message);
retainLog(Level.SEVERE, message);
}
@Override
public void logInfo(String message) {
Log.i("", message);
retainLog(Level.INFO, message);
}
});
}
private synchronized void retainLog(Level level, String message) {
_wapiLogs.add(new LogEntry(message, level, new Date()));
}
public WapiLogger retainingWapiLogger = new WapiLogger() {
@Override
public void logError(String message) {
Log.e("Wapi", message);
retainLog(Level.SEVERE, message);
}
@Override
public void logError(String message, Exception e) {
Log.e("Wapi", message, e);
retainLog(Level.SEVERE, message);
}
@Override
public void logInfo(String message) {
Log.i("Wapi", message);
retainLog(Level.INFO, message);
}
};
private WapiClient initWapi() {
String version;
try {
PackageInfo packageInfo = _applicationContext.getPackageManager().getPackageInfo(_applicationContext.getPackageName(), 0);
if (packageInfo != null) {
version = String.valueOf(packageInfo.versionCode);
} else {
version = "na";
}
} catch (PackageManager.NameNotFoundException e) {
version = "na";
}
return new WapiClient(_environment.getWapiEndpoints(), retainingWapiLogger, version);
}
private void initTor() {
_torHandler = new Handler(Looper.getMainLooper());
if (_torMode == ServerEndpointType.Types.ONLY_TOR) {
this._torManager = new TorManagerOrbot();
} else {
throw new IllegalArgumentException();
}
_torManager.setStateListener(new TorManager.TorState() {
@Override
public void onStateChange(String status, final int percentage) {
Log.i("Tor init", status + ", " + String.valueOf(percentage));
retainLog(Level.INFO, "Tor: " + status + ", " + String.valueOf(percentage));
_torHandler.post(new Runnable() {
@Override
public void run() {
_eventBus.post(new TorStateChanged(percentage));
}
});
}
});
_environment.getWapiEndpoints().setTorManager(this._torManager);
_environment.getLtEndpoints().setTorManager(this._torManager);
}
private void migrateOldKeys() {
// We only migrate old keys if we don't have any accounts yet - otherwise, migration has already taken place
if (!_walletManager.getAccountIds().isEmpty()) {
return;
}
// Get the local trader address, may be null
Address localTraderAddress = _localTraderManager.getLocalTraderAddress();
if (localTraderAddress == null) {
_localTraderManager.unsetLocalTraderAccount();
}
//check which address was the last recently selected one
SharedPreferences prefs = _applicationContext.getSharedPreferences("selected", Context.MODE_PRIVATE);
String lastAddress = prefs.getString("last", null);
// Migrate all existing records to accounts
List<Record> records = loadClassicRecords();
for (Record record : records) {
// Create an account from this record
UUID account;
if (record.hasPrivateKey()) {
try {
account = _walletManager.createSingleAddressAccount(record.key, AesKeyCipher.defaultKeyCipher());
} catch (KeyCipher.InvalidKeyCipher invalidKeyCipher) {
throw new RuntimeException(invalidKeyCipher);
}
} else {
account = _walletManager.createSingleAddressAccount(record.address);
}
//check whether this was the selected record
if (record.address.toString().equals(lastAddress)) {
setSelectedAccount(account);
}
//check whether the record was archived
if (record.tag.equals(Record.Tag.ARCHIVE)) {
_walletManager.getAccount(account).archiveAccount();
}
// See if we need to migrate this account to local trader
if (record.address.equals(localTraderAddress)) {
if (record.hasPrivateKey()) {
_localTraderManager.setLocalTraderData(account, record.key, record.address, _localTraderManager.getNickname());
} else {
_localTraderManager.unsetLocalTraderAccount();
}
}
}
migrateAddressAndAccountLabelsToMetadataStorage();
}
private List<Record> loadClassicRecords() {
SharedPreferences prefs = _applicationContext.getSharedPreferences("data", Context.MODE_PRIVATE);
List<Record> recordList = new LinkedList<Record>();
// Load records
String records = prefs.getString("records", "");
for (String one : records.split(",")) {
one = one.trim();
if (one.length() == 0) {
continue;
}
Record record = Record.fromSerializedString(one);
if (record != null) {
recordList.add(record);
}
}
// Sort all records
Collections.sort(recordList);
return recordList;
}
private void migrateAddressAndAccountLabelsToMetadataStorage() {
List<AddressBookManager.Entry> entries = _addressBookManager.getEntries();
for (AddressBookManager.Entry entry : entries) {
Address address = entry.getAddress();
String label = entry.getName();
//check whether this is actually an addressbook entry, or the name of an account
UUID accountid = SingleAddressAccount.calculateId(address);
if (_walletManager.getAccountIds().contains(accountid)) {
//its one of our accounts, so we name it
_storage.storeAccountLabel(accountid, label);
} else {
//we just put it into the addressbook
_storage.storeAddressLabel(address, label);
}
}
}
/**
* Create a Wallet Manager instance
*
* @param context the application context
* @param environment the Mycelium environment
* @return a new wallet manager instance
*/
private WalletManager createWalletManager(final Context context, MbwEnvironment environment) {
WalletManagerBacking backing;
SecureKeyValueStore secureKeyValueStore;
// Create persisted account backing
backing = new SqliteWalletManagerBackingWrapper(context);
// Create persisted secure storage instance
secureKeyValueStore = new SecureKeyValueStore(backing,
new AndroidRandomSource());
ExternalSignatureProviderProxy externalSignatureProviderProxy = new ExternalSignatureProviderProxy(
getTrezorManager(),
getKeepKeyManager(),
getLedgerManager()
);
// Create and return wallet manager
WalletManager walletManager = new WalletManager(secureKeyValueStore,
backing, environment.getNetwork(), _wapi, externalSignatureProviderProxy);
// notify the walletManager about the current selected account
UUID lastSelectedAccountId = getLastSelectedAccountId();
if (lastSelectedAccountId != null) {
walletManager.setActiveAccount(lastSelectedAccountId);
}
return walletManager;
}
/**
* Create a Wallet Manager instance for temporary accounts just backed by in-memory persistence
*
* @param environment the Mycelium environment
* @return a new in memory backed wallet manager instance
*/
private WalletManager createTempWalletManager(MbwEnvironment environment) {
// Create in-memory account backing
WalletManagerBacking backing = new InMemoryWalletManagerBacking();
// Create secure storage instance
SecureKeyValueStore secureKeyValueStore = new SecureKeyValueStore(backing, new AndroidRandomSource());
// Create and return wallet manager
WalletManager walletManager = new WalletManager(secureKeyValueStore,
backing, environment.getNetwork(), _wapi, null);
walletManager.disableTransactionHistorySynchronization();
return walletManager;
}
public String getFiatCurrency() {
return _currencySwitcher.getCurrentFiatCurrency();
}
public boolean hasFiatCurrency() {
return !getCurrencyList().isEmpty();
}
private SharedPreferences getPreferences() {
return _applicationContext.getSharedPreferences(Constants.SETTINGS_NAME, Activity.MODE_PRIVATE);
}
public List<String> getCurrencyList() {
return _currencySwitcher.getCurrencyList();
}
public void setCurrencyList(Set<String> currencies) {
Set<String> allActiveFiatCurrencies = _walletManager.getAllActiveFiatCurrencies();
// let the exchange-rate manager fetch all currencies, that we might need
_exchangeRateManager.setCurrencyList(Sets.union(currencies, allActiveFiatCurrencies));
// but tell the currency-switcher only to switch over the user selected currencies
_currencySwitcher.setCurrencyList(currencies);
SharedPreferences.Editor editor = getEditor();
editor.putStringSet(Constants.SELECTED_CURRENCIES, new HashSet<String>(currencies));
editor.commit();
}
public String getNextCurrency(boolean includeBitcoin) {
return _currencySwitcher.getNextCurrency(includeBitcoin);
}
private SharedPreferences.Editor getEditor() {
return getPreferences().edit();
}
public LocalTraderManager getLocalTraderManager() {
return _localTraderManager;
}
public ExchangeRateManager getExchangeRateManager() {
return _exchangeRateManager;
}
public CurrencySwitcher getCurrencySwitcher() {
return _currencySwitcher;
}
public boolean isPinProtected() {
return getPin().isSet();
}
// returns the age of the PIN in blocks (~10min)
public Optional<Integer> getRemainingPinLockdownDuration() {
Optional<Integer> pinSetHeight = getMetadataStorage().getLastPinSetBlockheight();
int blockHeight = getSelectedAccount().getBlockChainHeight();
if (!pinSetHeight.isPresent() || blockHeight < pinSetHeight.get()) {
return Optional.absent();
}
int pinAge = blockHeight - pinSetHeight.get();
if (pinAge > Constants.MIN_PIN_BLOCKHEIGHT_AGE_ADDITIONAL_BACKUP) {
return Optional.of(0);
} else {
return Optional.of(Constants.MIN_PIN_BLOCKHEIGHT_AGE_ADDITIONAL_BACKUP - pinAge);
}
}
public boolean isPinOldEnough() {
if (!isPinProtected()) {
return false;
}
Optional<Integer> pinLockdownDuration = getRemainingPinLockdownDuration();
if (!pinLockdownDuration.isPresent()) {
// PIN height was not set (older version) - take the current height and let the user wait...
setPinBlockheight();
return false;
}
return !(pinLockdownDuration.get() > 0);
}
public Pin getPin() {
return _pin;
}
public void showClearPinDialog(final Activity activity, final Optional<Runnable> afterDialogClosed) {
this.runPinProtectedFunction(activity, new ClearPinDialog(activity, true), new Runnable() {
@Override
public void run() {
MbwManager.this.savePin(Pin.CLEAR_PIN);
Toast.makeText(_applicationContext, R.string.pin_cleared, Toast.LENGTH_LONG).show();
if (afterDialogClosed.isPresent()) {
afterDialogClosed.get().run();
}
}
});
}
public void showSetPinDialog(final Activity activity, final Optional<Runnable> afterDialogClosed) {
// Must make a backup before setting PIN
if (this.getMetadataStorage().getMasterSeedBackupState() != MetadataStorage.BackupState.VERIFIED) {
Utils.showSimpleMessageDialog(activity, R.string.pin_backup_first);
return;
}
final NewPinDialog _dialog = new NewPinDialog(activity, false);
_dialog.setOnPinValid(new PinDialog.OnPinEntered() {
private String newPin = null;
@Override
public void pinEntered(PinDialog dialog, Pin pin) {
if (newPin == null) {
newPin = pin.getPin();
dialog.setTitle(R.string.pin_confirm_pin);
} else if (newPin.equals(pin.getPin())) {
MbwManager.this.savePin(pin);
Toast.makeText(activity, R.string.pin_set, Toast.LENGTH_LONG).show();
dialog.dismiss();
if (afterDialogClosed.isPresent()) {
afterDialogClosed.get().run();
}
} else {
Toast.makeText(activity, R.string.pin_codes_dont_match, Toast.LENGTH_LONG).show();
MbwManager.this.vibrate(500);
dialog.dismiss();
if (afterDialogClosed.isPresent()) {
afterDialogClosed.get().run();
}
}
}
});
this.runPinProtectedFunction(activity, new Runnable() {
@Override
public void run() {
_dialog.show();
}
});
}
public void savePin(Pin pin) {
// if we were not pin protected and get a new pin, remember the blockheight
// at which the pin was set - so that we can measure the age of the pin.
if (!isPinProtected()) {
setPinBlockheight();
} else {
// if we were pin-protected and now the pin is removed, reset the blockheight
if (!pin.isSet()) {
getMetadataStorage().clearLastPinSetBlockheight();
}
}
_pin = pin;
getEditor().putString(Constants.PIN_SETTING, _pin.getPin()).commit();
getEditor().putString(Constants.PIN_SETTING_RESETTABLE, pin.isResettable() ? "1" : "0").commit();
}
private void setPinBlockheight() {
int blockHeight = getSelectedAccount().getBlockChainHeight();
getMetadataStorage().setLastPinSetBlockheight(blockHeight);
}
// returns the PinDialog or null, if no pin was needed
public PinDialog runPinProtectedFunction(final Activity activity, final Runnable fun, boolean cancelable) {
return runPinProtectedFunctionInternal(activity, fun, cancelable);
}
// returns the PinDialog or null, if no pin was needed
public PinDialog runPinProtectedFunction(final Activity activity, final Runnable fun) {
return runPinProtectedFunctionInternal(activity, fun, true);
}
// returns the PinDialog or null, if no pin was needed
private PinDialog runPinProtectedFunctionInternal(Activity activity, Runnable fun, boolean cancelable) {
if (isPinProtected() && !lastPinAgeOkay.get()) {
PinDialog d = new PinDialog(activity, true, cancelable);
runPinProtectedFunction(activity, d, fun);
return d;
} else {
fun.run();
return null;
}
}
protected void runPinProtectedFunction(final Activity activity, PinDialog pinDialog, final Runnable fun) {
if (isPinProtected()) {
failedPinCount = getPreferences().getInt(Constants.FAILED_PIN_COUNT, 0);
pinDialog.setOnPinValid(new PinDialog.OnPinEntered() {
@Override
public void pinEntered(final PinDialog pinDialog, Pin pin) {
if(failedPinCount > 0) {
long millis = (long) (Math.pow(1.2, failedPinCount) * 10);
try {
Thread.sleep(millis);
} catch (InterruptedException ignored) {
Toast.makeText(activity, "Something weird is happening. avoid getting to pin check", Toast.LENGTH_LONG).show();
vibrate(500);
pinDialog.dismiss();
return;
}
}
if (pin.equals(getPin())) {
failedPinCount = 0;
getPreferences().edit().putInt(Constants.FAILED_PIN_COUNT, failedPinCount).apply();
pinDialog.dismiss();
// as soon as you enter the correct pin once, abort the reset-pin-procedure
MbwManager.this.getMetadataStorage().clearResetPinStartBlockheight();
// if last Pin entry was 1sec ago, don't ask for it again.
// to prevent if there are two pin protected functions cascaded
// like startup-pin request and account-choose-pin request if opened by a bitcoin url
pinOkForOneS();
fun.run();
} else {
getPreferences().edit().putInt(Constants.FAILED_PIN_COUNT, ++failedPinCount).apply();
if (_pin.isResettable()) {
// Show hint, that this pin is resettable
new AlertDialog.Builder(activity)
.setTitle(R.string.pin_invalid_pin)
.setPositiveButton(activity.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
pinDialog.dismiss();
}
})
.setNeutralButton(activity.getString(R.string.reset_pin_button), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
pinDialog.dismiss();
MbwManager.this.showClearPinDialog(activity, Optional.<Runnable>absent());
}
})
.setMessage(activity.getString(R.string.wrong_pin_message))
.show();
} else {
// This pin is not resettable, you are out of luck
Toast.makeText(activity, R.string.pin_invalid_pin, Toast.LENGTH_LONG).show();
vibrate(500);
pinDialog.dismiss();
}
}
}
});
if(!activity.isFinishing()) {
pinDialog.show();
}
} else {
fun.run();
}
}
public void startResetPinProcedure() {
getMetadataStorage().setResetPinStartBlockheight(getSelectedAccount().getBlockChainHeight());
}
public Optional<Integer> getResetPinRemainingBlocksCount() {
Optional<Integer> resetPinStartBlockHeight = getMetadataStorage().getResetPinStartBlockHeight();
if (!resetPinStartBlockHeight.isPresent()) {
// no reset procedure ongoing
return Optional.absent();
} else {
int blockAge = getSelectedAccount().getBlockChainHeight() - resetPinStartBlockHeight.get();
return Optional.of(Math.max(0, Constants.MIN_PIN_BLOCKHEIGHT_AGE_RESET_PIN - blockAge));
}
}
public void vibrate() {
vibrate(500);
}
public void vibrate(int milliseconds) {
Vibrator v = (Vibrator) _applicationContext.getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
v.vibrate(milliseconds);
}
}
public MinerFee getMinerFee() {
return _minerFee;
}
public void setMinerFee(MinerFee minerFee) {
_minerFee = minerFee;
getEditor().putString(Constants.MINER_FEE_SETTING, _minerFee.toString()).commit();
}
public void setBlockExplorer(BlockExplorer blockExplorer) {
_blockExplorerManager.setBlockExplorer(blockExplorer);
getEditor().putString(Constants.BLOCK_EXPLORER, blockExplorer.getIdentifier()).commit();
}
public CoinUtil.Denomination getBitcoinDenomination() {
return _currencySwitcher.getBitcoinDenomination();
}
public void setBitcoinDenomination(CoinUtil.Denomination denomination) {
_currencySwitcher.setBitcoinDenomination(denomination);
getEditor().putString(Constants.BITCOIN_DENOMINATION_SETTING, denomination.toString()).commit();
}
public String getBtcValueString(long satoshis) {
return _currencySwitcher.getBtcValueString(satoshis);
}
public boolean isKeyManagementLocked() {
return _keyManagementLocked;
}
public void setKeyManagementLocked(boolean locked) {
_keyManagementLocked = locked;
getEditor().putBoolean(Constants.KEY_MANAGEMENT_LOCKED_SETTING, _keyManagementLocked).commit();
}
public boolean getContinuousFocus() {
return _enableContinuousFocus;
}
public void setContinuousFocus(boolean enableContinuousFocus) {
_enableContinuousFocus = enableContinuousFocus;
getEditor().putBoolean(Constants.ENABLE_CONTINUOUS_FOCUS_SETTING, _enableContinuousFocus).commit();
}
public void setProxy(String proxy) {
getEditor().putString(Constants.PROXY_SETTING, proxy).commit();
ImmutableList<String> vals = ImmutableList.copyOf(Splitter.on(":").split(proxy));
if (vals.size() != 2) {
noProxy();
return;
}
Integer portNumber = Ints.tryParse(vals.get(1));
if (portNumber == null || portNumber < 1 || portNumber > 65535) {
noProxy();
return;
}
String hostname = vals.get(0);
System.setProperty(PROXY_HOST, hostname);
System.setProperty(PROXY_PORT, portNumber.toString());
}
private void noProxy() {
System.clearProperty(PROXY_HOST);
System.clearProperty(PROXY_PORT);
}
public MrdExport.V1.EncryptionParameters getCachedEncryptionParameters() {
return _cachedEncryptionParameters;
}
public void setCachedEncryptionParameters(MrdExport.V1.EncryptionParameters cachedEncryptionParameters) {
_cachedEncryptionParameters = cachedEncryptionParameters;
}
public void clearCachedEncryptionParameters() {
_cachedEncryptionParameters = null;
}
public Bus getEventBus() {
return _eventBus;
}
/**
* Get the Bitcoin network parameters that the wallet operates on
*/
public NetworkParameters getNetwork() {
return _environment.getNetwork();
}
/**
* Get the brand of the wallet. This allows us to behave differently
* depending on the brand of the wallet.
*/
public String getBrand() {
return _environment.getBrand();
}
public ExploreHelper get_exploreHelper() {
return _exploreHelper;
}
public void reportIgnoredException(Throwable e) {
if (_httpErrorCollector != null) {
RuntimeException msg = new RuntimeException("We caught an exception that we chose to ignore.\n", e);
_httpErrorCollector.reportErrorToServer(msg);
}
}
public void reportIgnoredException(String Message, Throwable e) {
if (_httpErrorCollector != null) {
RuntimeException msg = new RuntimeException("We caught an exception that we chose to ignore.\n" + Message + "\n", e);
_httpErrorCollector.reportErrorToServer(msg);
}
}
public String getLanguage() {
return _language;
}
public Locale getLocale() {
return new Locale(_language);
}
public void setLanguage(String _language) {
this._language = _language;
SharedPreferences.Editor editor = getEditor();
editor.putString(Constants.LANGUAGE_SETTING, _language);
editor.commit();
}
public void setTorMode(ServerEndpointType.Types torMode) {
this._torMode = torMode;
SharedPreferences.Editor editor = getEditor();
editor.putString(Constants.TOR_MODE, torMode.toString());
editor.commit();
ServerEndpointType serverEndpointType = ServerEndpointType.fromType(torMode);
if (serverEndpointType.mightUseTor()) {
initTor();
} else {
if (_torManager != null) {
_torManager.stopClient();
}
}