-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
MainViewModel.java
1346 lines (1188 loc) · 62.4 KB
/
MainViewModel.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
/*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.desktop.main;
import bisq.desktop.common.model.ViewModel;
import bisq.desktop.components.BalanceWithConfirmationTextField;
import bisq.desktop.components.TxIdTextField;
import bisq.desktop.main.overlays.notifications.NotificationCenter;
import bisq.desktop.main.overlays.popups.Popup;
import bisq.desktop.main.overlays.windows.DisplayAlertMessageWindow;
import bisq.desktop.main.overlays.windows.TacWindow;
import bisq.desktop.main.overlays.windows.TorNetworkSettingsWindow;
import bisq.desktop.main.overlays.windows.WalletPasswordWindow;
import bisq.desktop.main.overlays.windows.downloadupdate.DisplayUpdateDownloadWindow;
import bisq.desktop.util.BSFormatter;
import bisq.desktop.util.GUIUtil;
import bisq.core.alert.Alert;
import bisq.core.alert.AlertManager;
import bisq.core.alert.PrivateNotificationManager;
import bisq.core.alert.PrivateNotificationPayload;
import bisq.core.app.AppOptionKeys;
import bisq.core.app.BisqEnvironment;
import bisq.core.app.SetupUtils;
import bisq.core.arbitration.ArbitratorManager;
import bisq.core.arbitration.Dispute;
import bisq.core.arbitration.DisputeManager;
import bisq.core.btc.AddressEntry;
import bisq.core.btc.listeners.BalanceListener;
import bisq.core.btc.wallet.BtcWalletService;
import bisq.core.btc.wallet.WalletsManager;
import bisq.core.btc.wallet.WalletsSetup;
import bisq.core.dao.DaoSetup;
import bisq.core.filter.FilterManager;
import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.FiatCurrency;
import bisq.core.locale.Res;
import bisq.core.locale.TradeCurrency;
import bisq.core.offer.OpenOffer;
import bisq.core.offer.OpenOfferManager;
import bisq.core.payment.AccountAgeWitnessService;
import bisq.core.payment.CryptoCurrencyAccount;
import bisq.core.payment.PaymentAccount;
import bisq.core.payment.PerfectMoneyAccount;
import bisq.core.payment.payload.PaymentMethod;
import bisq.core.provider.fee.FeeService;
import bisq.core.provider.price.MarketPrice;
import bisq.core.provider.price.PriceFeedService;
import bisq.core.trade.Trade;
import bisq.core.trade.TradeManager;
import bisq.core.trade.closed.ClosedTradableManager;
import bisq.core.trade.failed.FailedTradesManager;
import bisq.core.trade.statistics.TradeStatisticsManager;
import bisq.core.user.DontShowAgainLookup;
import bisq.core.user.Preferences;
import bisq.core.user.User;
import bisq.network.crypto.DecryptedDataTuple;
import bisq.network.crypto.EncryptionService;
import bisq.network.p2p.BootstrapListener;
import bisq.network.p2p.P2PService;
import bisq.network.p2p.P2PServiceListener;
import bisq.network.p2p.network.CloseConnectionReason;
import bisq.network.p2p.network.Connection;
import bisq.network.p2p.network.ConnectionListener;
import bisq.network.p2p.peers.keepalive.messages.Ping;
import bisq.common.Clock;
import bisq.common.Timer;
import bisq.common.UserThread;
import bisq.common.app.DevEnv;
import bisq.common.app.Version;
import bisq.common.crypto.CryptoException;
import bisq.common.crypto.KeyRing;
import bisq.common.crypto.SealedAndSigned;
import bisq.common.proto.ProtobufferException;
import bisq.common.storage.CorruptedDatabaseFilesHandler;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.ChainFileLockedException;
import com.google.inject.Inject;
import com.google.common.net.InetAddresses;
import org.fxmisc.easybind.EasyBind;
import org.fxmisc.easybind.Subscription;
import org.fxmisc.easybind.monadic.MonadicBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.SetChangeListener;
import java.security.Security;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
@Slf4j
public class MainViewModel implements ViewModel {
private static final long STARTUP_TIMEOUT_MINUTES = 4;
private final WalletsManager walletsManager;
private final WalletsSetup walletsSetup;
private final BtcWalletService btcWalletService;
private final ArbitratorManager arbitratorManager;
private final P2PService p2PService;
private final TradeManager tradeManager;
private final OpenOfferManager openOfferManager;
private final DisputeManager disputeManager;
final Preferences preferences;
private final AlertManager alertManager;
private final PrivateNotificationManager privateNotificationManager;
@SuppressWarnings({"unused", "FieldCanBeLocal"})
private final FilterManager filterManager;
private final WalletPasswordWindow walletPasswordWindow;
private final TradeStatisticsManager tradeStatisticsManager;
private final NotificationCenter notificationCenter;
private final TacWindow tacWindow;
private final Clock clock;
private final FeeService feeService;
private final DaoSetup daoSetup;
private final EncryptionService encryptionService;
private final KeyRing keyRing;
private final BisqEnvironment bisqEnvironment;
private final FailedTradesManager failedTradesManager;
private final ClosedTradableManager closedTradableManager;
private final AccountAgeWitnessService accountAgeWitnessService;
final TorNetworkSettingsWindow torNetworkSettingsWindow;
private final CorruptedDatabaseFilesHandler corruptedDatabaseFilesHandler;
private final BSFormatter formatter;
// BTC network
final StringProperty btcInfo = new SimpleStringProperty(Res.get("mainView.footer.btcInfo.initializing"));
@SuppressWarnings("ConstantConditions")
final DoubleProperty btcSyncProgress = new SimpleDoubleProperty(-1);
final StringProperty walletServiceErrorMsg = new SimpleStringProperty();
final StringProperty btcSplashSyncIconId = new SimpleStringProperty();
private final StringProperty marketPriceCurrencyCode = new SimpleStringProperty("");
final ObjectProperty<PriceFeedComboBoxItem> selectedPriceFeedComboBoxItemProperty = new SimpleObjectProperty<>();
final BooleanProperty isFiatCurrencyPriceFeedSelected = new SimpleBooleanProperty(true);
final BooleanProperty isCryptoCurrencyPriceFeedSelected = new SimpleBooleanProperty(false);
final BooleanProperty isExternallyProvidedPrice = new SimpleBooleanProperty(true);
final BooleanProperty isPriceAvailable = new SimpleBooleanProperty(false);
final BooleanProperty newVersionAvailableProperty = new SimpleBooleanProperty(false);
final IntegerProperty marketPriceUpdated = new SimpleIntegerProperty(0);
final StringProperty availableBalance = new SimpleStringProperty();
final StringProperty reservedBalance = new SimpleStringProperty();
final StringProperty lockedBalance = new SimpleStringProperty();
@SuppressWarnings("FieldCanBeLocal")
private MonadicBinding<String> btcInfoBinding;
private final StringProperty marketPrice = new SimpleStringProperty(Res.get("shared.na"));
// P2P network
final StringProperty p2PNetworkInfo = new SimpleStringProperty();
@SuppressWarnings("FieldCanBeLocal")
private MonadicBinding<String> p2PNetworkInfoBinding;
final BooleanProperty splashP2PNetworkAnimationVisible = new SimpleBooleanProperty(true);
final StringProperty p2pNetworkWarnMsg = new SimpleStringProperty();
final StringProperty p2PNetworkIconId = new SimpleStringProperty();
final BooleanProperty bootstrapComplete = new SimpleBooleanProperty();
final BooleanProperty showAppScreen = new SimpleBooleanProperty();
final StringProperty numPendingTradesAsString = new SimpleStringProperty();
final BooleanProperty showPendingTradesNotification = new SimpleBooleanProperty();
final StringProperty numOpenDisputesAsString = new SimpleStringProperty();
final BooleanProperty showOpenDisputesNotification = new SimpleBooleanProperty();
private final BooleanProperty isSplashScreenRemoved = new SimpleBooleanProperty();
final StringProperty p2pNetworkLabelId = new SimpleStringProperty("footer-pane");
@SuppressWarnings("FieldCanBeLocal")
private MonadicBinding<Boolean> allServicesDone, tradesAndUIReady;
final PriceFeedService priceFeedService;
private final User user;
private int numBtcPeers = 0;
private Timer checkNumberOfBtcPeersTimer;
private Timer checkNumberOfP2pNetworkPeersTimer;
private final Map<String, Subscription> disputeIsClosedSubscriptionsMap = new HashMap<>();
final ObservableList<PriceFeedComboBoxItem> priceFeedComboBoxItems = FXCollections.observableArrayList();
@SuppressWarnings("FieldCanBeLocal")
private MonadicBinding<String> marketPriceBinding;
@SuppressWarnings({"unused", "FieldCanBeLocal"})
private Subscription priceFeedAllLoadedSubscription;
private BooleanProperty p2pNetWorkReady;
private final BooleanProperty walletInitialized = new SimpleBooleanProperty();
private boolean allBasicServicesInitialized;
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////
@SuppressWarnings("WeakerAccess")
@Inject
public MainViewModel(WalletsManager walletsManager, WalletsSetup walletsSetup,
BtcWalletService btcWalletService, PriceFeedService priceFeedService,
ArbitratorManager arbitratorManager, P2PService p2PService, TradeManager tradeManager,
OpenOfferManager openOfferManager, DisputeManager disputeManager, Preferences preferences,
User user, AlertManager alertManager, PrivateNotificationManager privateNotificationManager,
FilterManager filterManager, WalletPasswordWindow walletPasswordWindow, TradeStatisticsManager tradeStatisticsManager,
NotificationCenter notificationCenter, TacWindow tacWindow, Clock clock, FeeService feeService,
DaoSetup daoSetup, EncryptionService encryptionService,
KeyRing keyRing, BisqEnvironment bisqEnvironment, FailedTradesManager failedTradesManager,
ClosedTradableManager closedTradableManager, AccountAgeWitnessService accountAgeWitnessService,
TorNetworkSettingsWindow torNetworkSettingsWindow,
CorruptedDatabaseFilesHandler corruptedDatabaseFilesHandler, BSFormatter formatter) {
this.walletsManager = walletsManager;
this.walletsSetup = walletsSetup;
this.btcWalletService = btcWalletService;
this.priceFeedService = priceFeedService;
this.user = user;
this.arbitratorManager = arbitratorManager;
this.p2PService = p2PService;
this.tradeManager = tradeManager;
this.openOfferManager = openOfferManager;
this.disputeManager = disputeManager;
this.preferences = preferences;
this.alertManager = alertManager;
this.privateNotificationManager = privateNotificationManager;
this.filterManager = filterManager; // Reference so it's initialized and eventListener gets registered
this.walletPasswordWindow = walletPasswordWindow;
this.tradeStatisticsManager = tradeStatisticsManager;
this.notificationCenter = notificationCenter;
this.tacWindow = tacWindow;
this.clock = clock;
this.feeService = feeService;
this.daoSetup = daoSetup;
this.encryptionService = encryptionService;
this.keyRing = keyRing;
this.bisqEnvironment = bisqEnvironment;
this.failedTradesManager = failedTradesManager;
this.closedTradableManager = closedTradableManager;
this.accountAgeWitnessService = accountAgeWitnessService;
this.torNetworkSettingsWindow = torNetworkSettingsWindow;
this.corruptedDatabaseFilesHandler = corruptedDatabaseFilesHandler;
this.formatter = formatter;
TxIdTextField.setPreferences(preferences);
// TODO
TxIdTextField.setWalletService(btcWalletService);
BalanceWithConfirmationTextField.setWalletService(btcWalletService);
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public void start() {
// We do the delete of the spv file at startup before BitcoinJ is initialized to avoid issues with locked files under Windows.
if (preferences.isResyncSpvRequested()) {
try {
walletsSetup.reSyncSPVChain();
} catch (IOException e) {
log.error(e.toString());
e.printStackTrace();
}
}
//noinspection ConstantConditions,ConstantConditions,PointlessBooleanExpression
if (!preferences.isTacAccepted() && !DevEnv.isDevMode()) {
UserThread.runAfter(() -> {
tacWindow.onAction(() -> {
preferences.setTacAccepted(true);
checkIfLocalHostNodeIsRunning();
}).show();
}, 1);
} else {
checkIfLocalHostNodeIsRunning();
}
}
private void readMapsFromResources() {
SetupUtils.readFromResources(p2PService.getP2PDataStorage()).addListener((observable, oldValue, newValue) -> {
if (newValue)
startBasicServices();
});
// TODO can be removed in jdk 9
checkCryptoSetup();
}
private void startBasicServices() {
log.info("startBasicServices");
ChangeListener<Boolean> walletInitializedListener = (observable, oldValue, newValue) -> {
// TODO that seems to be called too often if Tor takes longer to start up...
if (newValue && !p2pNetWorkReady.get())
showTorNetworkSettingsWindow();
};
Timer startupTimeout = UserThread.runAfter(() -> {
log.warn("startupTimeout called");
if (walletsManager.areWalletsEncrypted())
walletInitialized.addListener(walletInitializedListener);
else
showTorNetworkSettingsWindow();
}, STARTUP_TIMEOUT_MINUTES, TimeUnit.MINUTES);
p2pNetWorkReady = initP2PNetwork();
// We only init wallet service here if not using Tor for bitcoinj.
// When using Tor, wallet init must be deferred until Tor is ready.
if (!preferences.getUseTorForBitcoinJ() || bisqEnvironment.isBitcoinLocalhostNodeRunning())
initWalletService();
// need to store it to not get garbage collected
allServicesDone = EasyBind.combine(walletInitialized, p2pNetWorkReady,
(a, b) -> {
log.debug("\nwalletInitialized={}\n" +
"p2pNetWorkReady={}",
a, b);
return a && b;
});
allServicesDone.subscribe((observable, oldValue, newValue) -> {
if (newValue) {
startupTimeout.stop();
walletInitialized.removeListener(walletInitializedListener);
onBasicServicesInitialized();
if (torNetworkSettingsWindow != null)
torNetworkSettingsWindow.hide();
}
});
}
private void showTorNetworkSettingsWindow() {
torNetworkSettingsWindow.show();
}
///////////////////////////////////////////////////////////////////////////////////////////
// Initialisation
///////////////////////////////////////////////////////////////////////////////////////////
private BooleanProperty initP2PNetwork() {
log.info("initP2PNetwork");
StringProperty bootstrapState = new SimpleStringProperty();
StringProperty bootstrapWarning = new SimpleStringProperty();
BooleanProperty hiddenServicePublished = new SimpleBooleanProperty();
BooleanProperty initialP2PNetworkDataReceived = new SimpleBooleanProperty();
p2PNetworkInfoBinding = EasyBind.combine(bootstrapState, bootstrapWarning, p2PService.getNumConnectedPeers(), hiddenServicePublished, initialP2PNetworkDataReceived,
(state, warning, numPeers, hiddenService, dataReceived) -> {
String result = "";
int peers = (int) numPeers;
if (warning != null && peers == 0) {
result = warning;
} else {
String p2pInfo = Res.get("mainView.footer.p2pInfo", numPeers);
if (dataReceived && hiddenService) {
result = p2pInfo;
} else if (peers == 0)
result = state;
else
result = state + " / " + p2pInfo;
}
return result;
});
p2PNetworkInfoBinding.subscribe((observable, oldValue, newValue) -> {
p2PNetworkInfo.set(newValue);
});
bootstrapState.set(Res.get("mainView.bootstrapState.connectionToTorNetwork"));
p2PService.getNetworkNode().addConnectionListener(new ConnectionListener() {
@Override
public void onConnection(Connection connection) {
}
@Override
public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) {
// We only check at seed nodes as they are running the latest version
// Other disconnects might be caused by peers running an older version
if (connection.getPeerType() == Connection.PeerType.SEED_NODE &&
closeConnectionReason == CloseConnectionReason.RULE_VIOLATION) {
log.warn("RULE_VIOLATION onDisconnect closeConnectionReason=" + closeConnectionReason);
log.warn("RULE_VIOLATION onDisconnect connection=" + connection);
}
}
@Override
public void onError(Throwable throwable) {
}
});
final BooleanProperty p2pNetworkInitialized = new SimpleBooleanProperty();
p2PService.start(new P2PServiceListener() {
@Override
public void onTorNodeReady() {
log.debug("onTorNodeReady");
bootstrapState.set(Res.get("mainView.bootstrapState.torNodeCreated"));
p2PNetworkIconId.set("image-connection-tor");
if (preferences.getUseTorForBitcoinJ())
initWalletService();
// We want to get early connected to the price relay so we call it already now
priceFeedService.setCurrencyCodeOnInit();
priceFeedService.initialRequestPriceFeed();
}
@Override
public void onHiddenServicePublished() {
log.debug("onHiddenServicePublished");
hiddenServicePublished.set(true);
bootstrapState.set(Res.get("mainView.bootstrapState.hiddenServicePublished"));
}
@Override
public void onDataReceived() {
log.debug("onRequestingDataCompleted");
initialP2PNetworkDataReceived.set(true);
bootstrapState.set(Res.get("mainView.bootstrapState.initialDataReceived"));
splashP2PNetworkAnimationVisible.set(false);
p2pNetworkInitialized.set(true);
}
@Override
public void onNoSeedNodeAvailable() {
log.warn("onNoSeedNodeAvailable");
if (p2PService.getNumConnectedPeers().get() == 0)
bootstrapWarning.set(Res.get("mainView.bootstrapWarning.noSeedNodesAvailable"));
else
bootstrapWarning.set(null);
splashP2PNetworkAnimationVisible.set(false);
p2pNetworkInitialized.set(true);
}
@Override
public void onNoPeersAvailable() {
log.warn("onNoPeersAvailable");
if (p2PService.getNumConnectedPeers().get() == 0) {
p2pNetworkWarnMsg.set(Res.get("mainView.p2pNetworkWarnMsg.noNodesAvailable"));
bootstrapWarning.set(Res.get("mainView.bootstrapWarning.noNodesAvailable"));
p2pNetworkLabelId.set("splash-error-state-msg");
} else {
bootstrapWarning.set(null);
p2pNetworkLabelId.set("footer-pane");
}
splashP2PNetworkAnimationVisible.set(false);
p2pNetworkInitialized.set(true);
}
@Override
public void onUpdatedDataReceived() {
log.debug("onBootstrapComplete");
splashP2PNetworkAnimationVisible.set(false);
bootstrapComplete.set(true);
}
@Override
public void onSetupFailed(Throwable throwable) {
log.warn("onSetupFailed");
p2pNetworkWarnMsg.set(Res.get("mainView.p2pNetworkWarnMsg.connectionToP2PFailed", throwable.getMessage()));
splashP2PNetworkAnimationVisible.set(false);
bootstrapWarning.set(Res.get("mainView.bootstrapWarning.bootstrappingToP2PFailed"));
p2pNetworkLabelId.set("splash-error-state-msg");
}
@Override
public void onRequestCustomBridges() {
showTorNetworkSettingsWindow();
}
});
return p2pNetworkInitialized;
}
private void initWalletService() {
log.info("initWalletService");
ObjectProperty<Throwable> walletServiceException = new SimpleObjectProperty<>();
btcInfoBinding = EasyBind.combine(walletsSetup.downloadPercentageProperty(), walletsSetup.numPeersProperty(), walletServiceException,
(downloadPercentage, numPeers, exception) -> {
String result = "";
if (exception == null) {
double percentage = (double) downloadPercentage;
int peers = (int) numPeers;
btcSyncProgress.set(percentage);
if (percentage == 1) {
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.synchronizedWith"),
getBtcNetworkAsString());
btcSplashSyncIconId.set("image-connection-synced");
if (allBasicServicesInitialized)
checkForLockedUpFunds();
} else if (percentage > 0.0) {
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.synchronizedWith"),
getBtcNetworkAsString() + ": " + formatter.formatToPercentWithSymbol(percentage));
} else {
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.connectingTo"),
getBtcNetworkAsString());
}
} else {
result = Res.get("mainView.footer.btcInfo",
numBtcPeers,
Res.get("mainView.footer.btcInfo.connectionFailed"),
getBtcNetworkAsString());
log.error(exception.getMessage());
if (exception instanceof TimeoutException) {
walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.timeout"));
} else if (exception.getCause() instanceof BlockStoreException) {
if (exception.getCause().getCause() instanceof ChainFileLockedException) {
new Popup<>().warning(Res.get("popup.warning.startupFailed.twoInstances"))
.useShutDownButton()
.show();
} else {
new Popup<>().warning(Res.get("error.spvFileCorrupted", exception.getMessage()))
.actionButtonText(Res.get("settings.net.reSyncSPVChainButton"))
.onAction(() -> GUIUtil.reSyncSPVChain(walletsSetup, preferences))
.show();
}
} else {
walletServiceErrorMsg.set(Res.get("mainView.walletServiceErrorMsg.connectionError", exception.toString()));
}
}
return result;
});
btcInfoBinding.subscribe((observable, oldValue, newValue) -> {
btcInfo.set(newValue);
});
walletsSetup.initialize(null,
() -> {
log.debug("walletsSetup.onInitialized");
numBtcPeers = walletsSetup.numPeersProperty().get();
// We only check one as we apply encryption to all or none
if (walletsManager.areWalletsEncrypted()) {
if (p2pNetWorkReady.get())
splashP2PNetworkAnimationVisible.set(false);
walletPasswordWindow
.onAesKey(aesKey -> {
walletsManager.setAesKey(aesKey);
if (preferences.isResyncSpvRequested()) {
showFirstPopupIfResyncSPVRequested();
} else {
walletInitialized.set(true);
}
})
.hideCloseButton()
.show();
} else {
if (preferences.isResyncSpvRequested()) {
showFirstPopupIfResyncSPVRequested();
} else {
walletInitialized.set(true);
}
}
},
walletServiceException::set);
}
private void onBasicServicesInitialized() {
log.info("onBasicServicesInitialized");
clock.start();
PaymentMethod.onAllServicesInitialized();
// disputeManager
disputeManager.onAllServicesInitialized();
disputeManager.getDisputesAsObservableList().addListener((ListChangeListener<Dispute>) change -> {
change.next();
onDisputesChangeListener(change.getAddedSubList(), change.getRemoved());
});
onDisputesChangeListener(disputeManager.getDisputesAsObservableList(), null);
// tradeManager
tradeManager.onAllServicesInitialized();
tradeManager.getTradableList().addListener((ListChangeListener<Trade>) c -> updateBalance());
tradeManager.getTradableList().addListener((ListChangeListener<Trade>) change -> onTradesChanged());
onTradesChanged();
// We handle the trade period here as we display a global popup if we reached dispute time
tradesAndUIReady = EasyBind.combine(isSplashScreenRemoved, tradeManager.pendingTradesInitializedProperty(), (a, b) -> a && b);
tradesAndUIReady.subscribe((observable, oldValue, newValue) -> {
if (newValue)
applyTradePeriodState();
});
tradeManager.setTakeOfferRequestErrorMessageHandler(errorMessage -> new Popup<>()
.warning(Res.get("popup.error.takeOfferRequestFailed", errorMessage))
.show());
// walletService
btcWalletService.addBalanceListener(new BalanceListener() {
@Override
public void onBalanceChanged(Coin balance, Transaction tx) {
updateBalance();
}
});
openOfferManager.getObservableList().addListener((ListChangeListener<OpenOffer>) c -> updateBalance());
tradeManager.getTradableList().addListener((ListChangeListener<Trade>) c -> updateBalance());
openOfferManager.onAllServicesInitialized();
removeOffersWithoutAccountAgeWitness();
arbitratorManager.onAllServicesInitialized();
alertManager.alertMessageProperty().addListener((observable, oldValue, newValue) -> displayAlertIfPresent(newValue, false));
privateNotificationManager.privateNotificationProperty().addListener((observable, oldValue, newValue) -> displayPrivateNotification(newValue));
displayAlertIfPresent(alertManager.alertMessageProperty().get(), false);
p2PService.onAllServicesInitialized();
feeService.onAllServicesInitialized();
GUIUtil.setFeeService(feeService);
daoSetup.onAllServicesInitialized(errorMessage -> new Popup<>().error(errorMessage).show());
tradeStatisticsManager.onAllServicesInitialized();
accountAgeWitnessService.onAllServicesInitialized();
priceFeedService.setCurrencyCodeOnInit();
filterManager.onAllServicesInitialized();
filterManager.addListener(filter -> {
if (filter != null) {
if (filter.getSeedNodes() != null && !filter.getSeedNodes().isEmpty())
new Popup<>().warning(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.seed"))).show();
if (filter.getPriceRelayNodes() != null && !filter.getPriceRelayNodes().isEmpty())
new Popup<>().warning(Res.get("popup.warning.nodeBanned", Res.get("popup.warning.priceRelay"))).show();
}
});
setupBtcNumPeersWatcher();
setupP2PNumPeersWatcher();
updateBalance();
if (DevEnv.isDevMode()) {
preferences.setShowOwnOffersInOfferBook(true);
setupDevDummyPaymentAccounts();
}
fillPriceFeedComboBoxItems();
setupMarketPriceFeed();
swapPendingOfferFundingEntries();
showAppScreen.set(true);
String key = "remindPasswordAndBackup";
user.getPaymentAccountsAsObservable().addListener((SetChangeListener<PaymentAccount>) change -> {
if (!walletsManager.areWalletsEncrypted() && preferences.showAgain(key) && change.wasAdded()) {
new Popup<>().headLine(Res.get("popup.securityRecommendation.headline"))
.information(Res.get("popup.securityRecommendation.msg"))
.dontShowAgainId(key)
.show();
}
});
checkIfOpenOffersMatchTradeProtocolVersion();
if (walletsSetup.downloadPercentageProperty().get() == 1)
checkForLockedUpFunds();
checkForCorruptedDataBaseFiles();
String bitcoinLocalhostNodeKey = "bitcoinLocalhostNode";
if (bisqEnvironment.isBitcoinLocalhostNodeRunning() && preferences.showAgain(bitcoinLocalhostNodeKey) && !DevEnv.isDevMode()) {
new Popup<>().backgroundInfo(Res.get("popup.bitcoinLocalhostNode.msg"))
.dontShowAgainId(bitcoinLocalhostNodeKey)
.show();
}
allBasicServicesInitialized = true;
}
private void showFirstPopupIfResyncSPVRequested() {
Popup firstPopup = new Popup<>();
firstPopup.information(Res.get("settings.net.reSyncSPVAfterRestart")).show();
if (btcSyncProgress.get() == 1) {
showSecondPopupIfResyncSPVRequested(firstPopup);
} else {
btcSyncProgress.addListener((observable, oldValue, newValue) -> {
if ((double) newValue == 1)
showSecondPopupIfResyncSPVRequested(firstPopup);
});
}
}
private void showSecondPopupIfResyncSPVRequested(Popup firstPopup) {
firstPopup.hide();
preferences.setResyncSpvRequested(false);
new Popup<>().information(Res.get("settings.net.reSyncSPVAfterRestartCompleted"))
.hideCloseButton()
.useShutDownButton()
.show();
}
private void checkIfLocalHostNodeIsRunning() {
Thread checkIfLocalHostNodeIsRunningThread = new Thread() {
@Override
public void run() {
Thread.currentThread().setName("checkIfLocalHostNodeIsRunningThread");
Socket socket = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(InetAddresses.forString("127.0.0.1"),
BisqEnvironment.getBaseCurrencyNetwork().getParameters().getPort()), 5000);
log.info("Localhost peer detected.");
UserThread.execute(() -> {
bisqEnvironment.setBitcoinLocalhostNodeRunning(true);
readMapsFromResources();
});
} catch (Throwable e) {
log.info("Localhost peer not detected.");
UserThread.execute(MainViewModel.this::readMapsFromResources);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ignore) {
}
}
}
}
};
checkIfLocalHostNodeIsRunningThread.start();
}
private void checkCryptoSetup() {
BooleanProperty result = new SimpleBooleanProperty();
// We want to test if the client is compiled with the correct crypto provider (BountyCastle)
// and if the unlimited Strength for cryptographic keys is set.
// If users compile themselves they might miss that step and then would get an exception in the trade.
// To avoid that we add here at startup a sample encryption and signing to see if it don't causes an exception.
// See: https://github.com/bisq-network/exchange/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys
Thread checkCryptoThread = new Thread() {
@Override
public void run() {
try {
Thread.currentThread().setName("checkCryptoThread");
log.trace("Run crypto test");
// just use any simple dummy msg
Ping payload = new Ping(1, 1);
SealedAndSigned sealedAndSigned = EncryptionService.encryptHybridWithSignature(payload,
keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey());
DecryptedDataTuple tuple = encryptionService.decryptHybridWithSignature(sealedAndSigned, keyRing.getEncryptionKeyPair().getPrivate());
if (tuple.getNetworkEnvelope() instanceof Ping &&
((Ping) tuple.getNetworkEnvelope()).getNonce() == payload.getNonce() &&
((Ping) tuple.getNetworkEnvelope()).getLastRoundTripTime() == payload.getLastRoundTripTime()) {
log.debug("Crypto test succeeded");
if (Security.getProvider("BC") != null) {
UserThread.execute(() -> result.set(true));
} else {
throw new CryptoException("Security provider BountyCastle is not available.");
}
} else {
throw new CryptoException("Payload not correct after decryption");
}
} catch (CryptoException | ProtobufferException e) {
e.printStackTrace();
String msg = Res.get("popup.warning.cryptoTestFailed", e.getMessage());
log.error(msg);
UserThread.execute(() -> new Popup<>().warning(msg)
.useShutDownButton()
.useReportBugButton()
.show());
}
}
};
checkCryptoThread.start();
}
private void checkIfOpenOffersMatchTradeProtocolVersion() {
List<OpenOffer> outDatedOffers = openOfferManager.getObservableList()
.stream()
.filter(e -> e.getOffer().getProtocolVersion() != Version.TRADE_PROTOCOL_VERSION)
.collect(Collectors.toList());
if (!outDatedOffers.isEmpty()) {
String offers = outDatedOffers.stream()
.map(e -> e.getId() + "\n")
.collect(Collectors.toList()).toString()
.replace("[", "").replace("]", "");
new Popup<>()
.warning(Res.get("popup.warning.oldOffers.msg", offers))
.actionButtonText(Res.get("popup.warning.oldOffers.buttonText"))
.onAction(() -> openOfferManager.removeOpenOffers(outDatedOffers, null))
.useShutDownButton()
.show();
}
}
///////////////////////////////////////////////////////////////////////////////////////////
// UI handlers
///////////////////////////////////////////////////////////////////////////////////////////
// After showAppScreen is set and splash screen is faded out
void onSplashScreenRemoved() {
isSplashScreenRemoved.set(true);
// Delay that as we want to know what is the current path of the navigation which is set
// in MainView showAppScreen handler
notificationCenter.onAllServicesAndViewsInitialized();
}
///////////////////////////////////////////////////////////////////////////////////////////
// States
///////////////////////////////////////////////////////////////////////////////////////////
private void applyTradePeriodState() {
updateTradePeriodState();
clock.addListener(new Clock.Listener() {
@Override
public void onSecondTick() {
}
@Override
public void onMinuteTick() {
updateTradePeriodState();
}
@Override
public void onMissedSecondTick(long missed) {
}
});
}
private void updateTradePeriodState() {
tradeManager.getTradableList().forEach(trade -> {
if (!trade.isPayoutPublished()) {
Date maxTradePeriodDate = trade.getMaxTradePeriodDate();
Date halfTradePeriodDate = trade.getHalfTradePeriodDate();
if (maxTradePeriodDate != null && halfTradePeriodDate != null) {
Date now = new Date();
if (now.after(maxTradePeriodDate))
trade.setTradePeriodState(Trade.TradePeriodState.TRADE_PERIOD_OVER);
else if (now.after(halfTradePeriodDate))
trade.setTradePeriodState(Trade.TradePeriodState.SECOND_HALF);
String key;
switch (trade.getTradePeriodState()) {
case FIRST_HALF:
break;
case SECOND_HALF:
key = "displayHalfTradePeriodOver" + trade.getId();
if (DontShowAgainLookup.showAgain(key)) {
DontShowAgainLookup.dontShowAgain(key, true);
new Popup<>().warning(Res.get("popup.warning.tradePeriod.halfReached",
trade.getShortId(),
formatter.formatDateTime(maxTradePeriodDate)))
.show();
}
break;
case TRADE_PERIOD_OVER:
key = "displayTradePeriodOver" + trade.getId();
if (DontShowAgainLookup.showAgain(key)) {
DontShowAgainLookup.dontShowAgain(key, true);
new Popup<>().warning(Res.get("popup.warning.tradePeriod.ended",
trade.getShortId(),
formatter.formatDateTime(maxTradePeriodDate)))
.show();
}
break;
}
}
}
});
}
///////////////////////////////////////////////////////////////////////////////////////////
// Private
///////////////////////////////////////////////////////////////////////////////////////////
private void setupP2PNumPeersWatcher() {
p2PService.getNumConnectedPeers().addListener((observable, oldValue, newValue) -> {
int numPeers = (int) newValue;
if ((int) oldValue > 0 && numPeers == 0) {
// give a bit of tolerance
if (checkNumberOfP2pNetworkPeersTimer != null)
checkNumberOfP2pNetworkPeersTimer.stop();
checkNumberOfP2pNetworkPeersTimer = UserThread.runAfter(() -> {
// check again numPeers
if (p2PService.getNumConnectedPeers().get() == 0) {
p2pNetworkWarnMsg.set(Res.get("mainView.networkWarning.allConnectionsLost", Res.get("shared.P2P")));
p2pNetworkLabelId.set("splash-error-state-msg");
} else {
p2pNetworkWarnMsg.set(null);
p2pNetworkLabelId.set("footer-pane");
}
}, 5);
} else if ((int) oldValue == 0 && numPeers > 0) {
if (checkNumberOfP2pNetworkPeersTimer != null)
checkNumberOfP2pNetworkPeersTimer.stop();
p2pNetworkWarnMsg.set(null);
p2pNetworkLabelId.set("footer-pane");
}
});
}
private void setupBtcNumPeersWatcher() {
walletsSetup.numPeersProperty().addListener((observable, oldValue, newValue) -> {
int numPeers = (int) newValue;
if ((int) oldValue > 0 && numPeers == 0) {
if (checkNumberOfBtcPeersTimer != null)
checkNumberOfBtcPeersTimer.stop();
checkNumberOfBtcPeersTimer = UserThread.runAfter(() -> {
// check again numPeers
if (walletsSetup.numPeersProperty().get() == 0) {
if (bisqEnvironment.isBitcoinLocalhostNodeRunning())
walletServiceErrorMsg.set(Res.get("mainView.networkWarning.localhostBitcoinLost", Res.getBaseCurrencyName().toLowerCase()));
else
walletServiceErrorMsg.set(Res.get("mainView.networkWarning.allConnectionsLost", Res.getBaseCurrencyName().toLowerCase()));
} else {
walletServiceErrorMsg.set(null);
}
}, 5);
} else if ((int) oldValue == 0 && numPeers > 0) {
if (checkNumberOfBtcPeersTimer != null)
checkNumberOfBtcPeersTimer.stop();
walletServiceErrorMsg.set(null);
}
});
}
private void setupMarketPriceFeed() {
priceFeedService.requestPriceFeed(price -> marketPrice.set(formatter.formatMarketPrice(price, priceFeedService.getCurrencyCode())),
(errorMessage, throwable) -> marketPrice.set(Res.get("shared.na")));
marketPriceBinding = EasyBind.combine(
marketPriceCurrencyCode, marketPrice,
(currencyCode, price) -> formatter.getCurrencyPair(currencyCode) + ": " + price);
marketPriceBinding.subscribe((observable, oldValue, newValue) -> {
if (newValue != null && !newValue.equals(oldValue)) {
setMarketPriceInItems();
String code = priceFeedService.currencyCodeProperty().get();
Optional<PriceFeedComboBoxItem> itemOptional = findPriceFeedComboBoxItem(code);
if (itemOptional.isPresent()) {
itemOptional.get().setDisplayString(newValue);
selectedPriceFeedComboBoxItemProperty.set(itemOptional.get());
} else {
if (CurrencyUtil.isCryptoCurrency(code)) {