forked from ciphrex/mSIGNA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainwindow.cpp
2657 lines (2292 loc) · 91 KB
/
mainwindow.cpp
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
///////////////////////////////////////////////////////////////////////////////
//
// mSIGNA
//
// mainwindow.cpp
//
// Copyright (c) 2013-2014 Eric Lombrozo
//
// All Rights Reserved.
#include "mainwindow.h"
#include <QtWidgets>
#include <QDir>
#include <QTreeWidgetItem>
#include <QTabWidget>
#include <QInputDialog>
#include <QItemSelectionModel>
#include "entropysource.h"
#include "settings.h"
//#include "versioninfo.h"
//#include "copyrightinfo.h"
#include "stylesheets.h"
// Random
#include "entropysource.h"
// Coin scripts
#include <CoinQ/CoinQ_script.h>
// Models/Views
#include "accountmodel.h"
#include "accountview.h"
#include "keychainmodel.h"
#include "keychainview.h"
#include "txmodel.h"
#include "txview.h"
// Actions
#include "txactions.h"
// Dialogs
#include "aboutdialog.h"
#include "entropydialog.h"
#include "newkeychaindialog.h"
#include "quicknewaccountdialog.h"
#include "newaccountdialog.h"
#include "rawtxdialog.h"
#include "createtxdialog.h"
#include "accounthistorydialog.h"
#include "scriptdialog.h"
#include "requestpaymentdialog.h"
#include "networksettingsdialog.h"
#include "keychainbackupdialog.h"
#include "viewbip32dialog.h"
#include "importbip32dialog.h"
#include "keychainbackupwizard.h"
#include "viewbip39dialog.h"
#include "importbip39dialog.h"
#include "passphrasedialog.h"
#include "setpassphrasedialog.h"
#include "currencyunitdialog.h"
//#include "resyncdialog.h"
// Logging
#include "severitylogger.h"
// Coin Parameters
#include "coinparams.h"
// File System
#include "docdir.h"
// Passphrases
#include <CoinDB/Passphrase.h>
#include <typeinfo>
boost::mutex repaintMutex;
using namespace CoinQ::Script;
using namespace std;
MainWindow::MainWindow() :
licenseAccepted(false),
synchedVault(getCoinParams()),
bQuitting(false),
syncHeight(0),
bestHeight(0),
networkState(NETWORK_STATE_STOPPED),
accountModel(nullptr),
keychainModel(nullptr),
txActions(nullptr)
{
loadSettings();
loadRecents();
createActions();
createToolBars();
createStatusBar();
//setCurrentFile("");
setUnifiedTitleAndToolBarOnMac(true);
// Keychain tab page
keychainModel = new KeychainModel();
keychainView = new KeychainView();
keychainView->setModel(keychainModel);
keychainView->setSelectionMode(KeychainView::MultiSelection);
connect(keychainModel, SIGNAL(keychainChanged()), keychainView, SLOT(updateColumns()));
keychainSelectionModel = keychainView->selectionModel();
connect(keychainSelectionModel, &QItemSelectionModel::currentChanged,
this, &MainWindow::updateCurrentKeychain);
connect(keychainSelectionModel, &QItemSelectionModel::selectionChanged,
this, &MainWindow::updateSelectedKeychains);
//synchedVault.subscribeKeychainUnlocked([this](const std::string& /*keychain_name*/) { keychainModel->update(); });
//synchedVault.subscribeKeychainLocked([this](const std::string& /*keychain_name*/) { keychainModel->update(); });
// Account tab page
accountModel = new AccountModel(synchedVault);
accountView = new AccountView();
accountView->setModel(accountModel);
accountView->updateColumns();
connect(accountView, SIGNAL(updateModel()), accountModel, SLOT(update()));
connect(keychainModel, SIGNAL(keychainChanged()), accountModel, SLOT(update()));
/*
qRegisterMetaType<bytes_t>("bytes_t");
connect(accountModel, SIGNAL(newTx(const bytes_t&)), this, SLOT(newTx(const bytes_t&)));
connect(accountModel, SIGNAL(newBlock(const bytes_t&, int)), this, SLOT(newBlock(const bytes_t&, int)));
connect(accountModel, &AccountModel::updateSyncHeight, [this](int height) { emit updateSyncHeight(height); });
*/
connect(accountModel, SIGNAL(error(const QString&)), this, SLOT(showError(const QString&)));
synchedVault.subscribeBestHeaderChanged([this](uint32_t height, const bytes_t& /*hash*/) { emit updateBestHeight((int)height); });
synchedVault.subscribeSyncHeaderChanged([this](uint32_t height, const bytes_t& /*hash*/) { emit updateSyncHeight((int)height); });
synchedVault.subscribeStatusChanged([this](CoinDB::SynchedVault::status_t status) {
switch (status)
{
case CoinDB::SynchedVault::STOPPED:
networkStopped();
break;
case CoinDB::SynchedVault::STARTING:
networkStarted();
break;
case CoinDB::SynchedVault::SYNCHING_HEADERS:
fetchingHeaders();
break;
case CoinDB::SynchedVault::SYNCHING_BLOCKS:
fetchingBlocks();
break;
case CoinDB::SynchedVault::SYNCHED:
blocksSynched();
break;
default:
break;
}
});
synchedVault.subscribeConnectionError([this](const std::string& error, int /*code*/) { emit signal_connectionClosed(); emit signal_error(tr("Connection error: ") + QString::fromStdString(error)); });
connect(this, SIGNAL(signal_connectionClosed()), this, SLOT(stopNetworkSync()));
//synchedVault.subscribeVaultError([this](const std::string& error, int /*code*/) { emit signal_error(tr("Vault error: ") + QString::fromStdString(error)); });
connect(this, SIGNAL(signal_error(const QString&)), this, SLOT(showError(const QString&)));
synchedVault.subscribeTxInserted([this](std::shared_ptr<CoinDB::Tx> /*tx*/) { if (isSynched()) emit signal_newTx(); });
synchedVault.subscribeTxUpdated([this](std::shared_ptr<CoinDB::Tx> /*tx*/) { if (isSynched()) emit signal_newTx(); });
synchedVault.subscribeMerkleBlockInserted([this](std::shared_ptr<CoinDB::MerkleBlock> /*merkleblock*/) { emit signal_newBlock(); });
connect(this, SIGNAL(signal_newTx()), this, SLOT(newTx()));
connect(this, SIGNAL(signal_newBlock()), this, SLOT(newBlock()));
connect(this, SIGNAL(signal_refreshAccounts()), this, SLOT(refreshAccounts()));
accountSelectionModel = accountView->selectionModel();
connect(accountSelectionModel, &QItemSelectionModel::currentChanged,
this, &MainWindow::updateCurrentAccount);
connect(accountSelectionModel, &QItemSelectionModel::selectionChanged,
this, &MainWindow::updateSelectedAccounts);
connect(keychainModel, SIGNAL(error(const QString&)), this, SLOT(showError(const QString&)));
// Transaction tab page
txModel = new TxModel();
connect(txModel, SIGNAL(txSigned(const QString&)), this, SLOT(showUpdate(const QString&)));
txView = new TxView();
txView->setModel(txModel);
txActions = new TxActions(txModel, txView, accountModel, keychainModel, &synchedVault, this);
connect(txActions, SIGNAL(txsChanged()), this, SLOT(refreshAccounts()));
connect(txActions, SIGNAL(error(const QString&)), this, SLOT(showError(const QString&)));
// Menus
createMenus();
updateRecentsMenu();
accountView->setMenu(accountMenu);
txView->setMenu(txActions->getMenu());
keychainView->setMenu(keychainMenu);
tabWidget = new QTabWidget();
tabWidget->addTab(accountView, tr("Accounts"));
tabWidget->addTab(txView, tr("Transactions"));
tabWidget->addTab(keychainView, tr("Keychains"));
setCentralWidget(tabWidget);
connect(txActions, SIGNAL(setCurrentWidget(QWidget*)), tabWidget, SLOT(setCurrentWidget(QWidget*)));
requestPaymentDialog = new RequestPaymentDialog(accountModel, accountView, this);
// Vault open and close
synchedVault.subscribeVaultOpened([this](CoinDB::Vault* vault) { emit vaultOpened(vault); });
synchedVault.subscribeVaultClosed([this]() { emit vaultClosed(); });
connect(this, &MainWindow::vaultOpened, [this](CoinDB::Vault* vault) {
keychainModel->setVault(vault);
keychainModel->update();
keychainView->updateColumns();
accountModel->update();
accountView->updateColumns();
txModel->setVault(vault);
txModel->update();
txView->updateColumns();
selectAccount(0);
});
connect(this, &MainWindow::vaultClosed, [this]() {
if (bQuitting) return;
keychainModel->setVault(nullptr);
keychainModel->update();
accountModel->update();
txModel->setVault(nullptr);
txModel->update();
txView->updateColumns();
updateStatusMessage(tr("Closed vault"));
updateRecentsMenu();
});
// status updates
connect(this, &MainWindow::status, [this](const QString& message) { updateStatusMessage(message); });
connect(this, &MainWindow::updateSyncHeight, [this](int height) {
LOGGER(debug) << "MainWindow::updateBestHeight emitted. New best height: " << height << std::endl;
syncHeight = height;
updateSyncLabel();
});
connect(this, &MainWindow::updateBestHeight, [this](int height) {
LOGGER(debug) << "MainWindow::updateBestHeight emitted. New best height: " << height << std::endl;
bestHeight = height;
updateSyncLabel();
});
connect(this, &MainWindow::signal_currencyUnitChanged, [this]() {
refreshAccounts();
});
setAcceptDrops(true);
updateFonts(fontSize);
}
void MainWindow::loadHeaders()
{
synchedVault.loadHeaders(blockTreeFile.toStdString(), false,
[this](const CoinQBlockTreeMem& blockTree) {
std::stringstream progress;
progress << "Height: " << blockTree.getBestHeight() << " / " << "Total Work: " << blockTree.getTotalWork().getDec();
emit headersLoadProgress(QString::fromStdString(progress.str()));
return true;
});
emit updateBestHeight(synchedVault.getBestHeight());
}
void MainWindow::tryConnect()
{
if (!autoConnect) return;
startNetworkSync();
}
void MainWindow::updateStatusMessage(const QString& message)
{
LOGGER(debug) << "MainWindow::updateStatusMessage - " << message.toStdString() << std::endl;
// boost::lock_guard<boost::mutex> lock(repaintMutex);
// statusBar()->showMessage(message);
}
void MainWindow::closeEvent(QCloseEvent* event)
{
bQuitting = true;
synchedVault.stopSync();
saveSettings();
joinEntropyThread();
event->accept();
}
void MainWindow::dragEnterEvent(QDragEnterEvent* event)
{
//if (event->mimeData()->hasFormat("text/plain"))
event->acceptProposedAction();
}
void MainWindow::dropEvent(QDropEvent* event)
{
const QMimeData* mimeData = event->mimeData();
if (mimeData->hasUrls()) {
for (auto& url: mimeData->urls()) {
if (url.isLocalFile()) {
processFile(url.toLocalFile());
}
}
return;
}
QMessageBox::information(this, tr("Drop Event"), mimeData->text());
}
void MainWindow::updateFonts(int fontSize)
{
switch (fontSize)
{
case SMALL_FONTS:
smallFontsAction->setChecked(true);
setStyleSheet(getSmallFontsStyle());
break;
case MEDIUM_FONTS:
mediumFontsAction->setChecked(true);
setStyleSheet(getMediumFontsStyle());
break;
case LARGE_FONTS:
largeFontsAction->setChecked(true);
setStyleSheet(getLargeFontsStyle());
break;
default:
return;
}
accountView->updateColumns();
keychainView->updateColumns();
txView->updateColumns();
QSettings settings("Ciphrex", getDefaultSettings().getSettingsRoot());
settings.setValue("fontsize", fontSize);
}
void MainWindow::updateSyncLabel()
{
syncLabel->setText(QString::number(syncHeight) + "/" + QString::number(bestHeight));
}
void MainWindow::updateNetworkState(network_state_t newState)
{
if (newState != networkState)
{
networkState = newState;
switch (networkState)
{
case NETWORK_STATE_STOPPED:
networkStateLabel->setPixmap(*stoppedIcon);
emit signal_refreshAccounts();
break;
case NETWORK_STATE_STARTED:
case NETWORK_STATE_SYNCHING:
networkStateLabel->setMovie(synchingMovie);
break;
case NETWORK_STATE_SYNCHED:
networkStateLabel->setPixmap(*synchedIcon);
emit signal_refreshAccounts();
break;
default:
// We should never get here
;
}
connectAction->setEnabled(!isConnected());
shortConnectAction->setEnabled(!isConnected());
disconnectAction->setEnabled(isConnected());
shortDisconnectAction->setEnabled(isConnected());
sendRawTxAction->setEnabled(isConnected());
}
}
void MainWindow::updateVaultStatus(const QString& name)
{
bool isOpen = !name.isEmpty();
// vault actions
importVaultAction->setEnabled(isOpen);
exportVaultAction->setEnabled(isOpen);
exportPublicVaultAction->setEnabled(isOpen);
closeVaultAction->setEnabled(isOpen);
// keychain actions
newKeychainAction->setEnabled(isOpen);
lockAllKeychainsAction->setEnabled(keychainModel && keychainModel->rowCount());
importKeychainAction->setEnabled(isOpen);
importBIP32Action->setEnabled(isOpen);
importBIP39Action->setEnabled(isOpen);
// account actions
quickNewAccountAction->setEnabled(isOpen);
newAccountAction->setEnabled(isOpen);
importAccountAction->setEnabled(isOpen);
// transaction actions
insertRawTxAction->setEnabled(isOpen);
createRawTxAction->setEnabled(isOpen);
//createTxAction->setEnabled(isOpen);
signRawTxAction->setEnabled(isOpen);
if (isOpen) {
setWindowTitle(getDefaultSettings().getAppName() + " - " + name);
}
else {
setWindowTitle(getDefaultSettings().getAppName());
}
if (txActions) txActions->updateVaultStatus();
}
void MainWindow::showError(const QString& errorMsg)
{
updateStatusMessage(tr("Operation failed"));
QMessageBox::critical(this, tr("Error"), errorMsg);
}
void MainWindow::showUpdate(const QString& updateMsg)
{
QMessageBox::information(this, tr("Update"), updateMsg);
}
void MainWindow::selectCurrencyUnit()
{
try
{
CurrencyUnitDialog dlg(this);
if (dlg.exec())
{
QString newCurrencyUnitPrefix = dlg.getCurrencyUnitPrefix();
if (newCurrencyUnitPrefix != currencyUnitPrefix)
{
currencyUnitPrefix = newCurrencyUnitPrefix;
saveSettings();
setCurrencyUnitPrefix(currencyUnitPrefix);
emit signal_currencyUnitChanged();
}
}
}
catch (const exception& e) {
LOGGER(debug) << "MainWindow::createTx - " << e.what() << std::endl;
showError(e.what());
}
}
void MainWindow::selectCurrencyUnit(const QString& newCurrencyUnitPrefix)
{
if (newCurrencyUnitPrefix != currencyUnitPrefix)
{
currencyUnitPrefix = newCurrencyUnitPrefix;
saveSettings();
setCurrencyUnitPrefix(currencyUnitPrefix);
emit signal_currencyUnitChanged();
}
}
void MainWindow::selectTrailingDecimals(bool newShowTrailingDecimals)
{
if (newShowTrailingDecimals != showTrailingDecimals)
{
showTrailingDecimals = newShowTrailingDecimals;
saveSettings();
setTrailingDecimals(showTrailingDecimals);
emit signal_currencyUnitChanged();
}
}
void MainWindow::newVault(QString fileName)
{
if (fileName.isEmpty()) {
fileName = QFileDialog::getSaveFileName(
this,
tr("Create New Vault"),
getDocDir(),
tr("Vaults (*.vault)"));
}
if (fileName.isEmpty()) return;
QFileInfo fileInfo(fileName);
setDocDir(fileInfo.dir().absolutePath());
saveSettings();
try
{
synchedVault.openVault(fileName.toStdString(), true, SCHEMA_VERSION, getCoinParams().network_name());
updateVaultStatus(fileName);
addToRecents(fileName);
}
catch (const CoinDB::VaultFailedToOpenDatabaseException& e)
{
LOGGER(error) << "MainWindow::newVault - VaultFailedToOpenDatabaseException: " << e.dberror() << std::endl;
showError(tr("Error creating database: ") + QString::fromStdString(e.dberror()));
}
catch (const exception& e)
{
LOGGER(debug) << "MainWindow::newVault - " << e.what() << std::endl;
showError(e.what());
}
}
void MainWindow::promptSync()
{
if (!isConnected())
{
QMessageBox msgBox;
msgBox.setText(tr("You are not connected to network."));
msgBox.setInformativeText(tr("Would you like to connect to network to synchronize your accounts?"));
msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Ok);
if (msgBox.exec() == QMessageBox::Ok) {
startNetworkSync();
}
}
else
{
syncBlocks();
}
}
void MainWindow::openVault(QString fileName)
{
if (fileName.isEmpty()) {
fileName = QFileDialog::getOpenFileName(
this,
tr("Open Vault"),
getDocDir(),
tr("Vaults (*.vault)"));
}
if (fileName.isEmpty()) return;
fileName = QFileInfo(fileName).absoluteFilePath();
QFileInfo fileInfo(fileName);
setDocDir(fileInfo.dir().absolutePath());
saveSettings();
try
{
try
{
closeVault();
synchedVault.openVault(fileName.toStdString(), false, SCHEMA_VERSION, getCoinParams().network_name(), false);
}
catch (const CoinDB::VaultNeedsSchemaMigrationException& e)
{
QMessageBox msgBox;
msgBox.setText(tr("File was created using schema ") + QString::number(e.schema_version()) + tr(". Current schema version is ") + QString::number(e.current_version())
+ tr("."));
msgBox.setInformativeText(tr("Schema can be upgraded. Would you like to make a backup and migrate the file to the new schema now?"));
msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Cancel);
if (msgBox.exec() != QMessageBox::Ok) return;
// Construct backup file name. xxxxx.vault will be copied to xxxxx.<schema version>.vault - if file already exists, then xxxxx1.<schema version>.vault will be tried, etc...
QString baseFileName;
QString extension;
QString backupFileName;
if (fileName.right(6).toLower() == ".vault")
{
baseFileName = fileName.left(fileName.size() - 6);
extension = ".vault";
}
else
{
baseFileName = fileName;
extension = "";
}
int n = 0;
while (true)
{
QString nString = (n > 0 ? QString::number(n) : QString());
backupFileName = baseFileName + nString + ".schema" + QString::number(e.schema_version()) + extension;
if (QFile::copy(fileName, backupFileName)) break;
n++;
}
synchedVault.openVault(fileName.toStdString(), false, SCHEMA_VERSION, getCoinParams().network_name(), true);
QMessageBox::information(this, tr("Backup Made"), tr("Your vault file has been backed up to ") + backupFileName);
}
updateVaultStatus(fileName);
updateStatusMessage(tr("Opened ") + fileName);
addToRecents(fileName);
//if (synchedVault.isConnected()) { synchedVault.syncBlocks(); }
//promptSync();
}
catch (const CoinDB::VaultWrongSchemaVersionException& e)
{
LOGGER(error) << "MainWindow::openVault - VaultWrongSchemaVersionException." << std::endl;
showError(tr("This vault file was created using schema version ") + QString::number(e.schema_version()) +
tr(". You are currently using schema version ") + QString::number(SCHEMA_VERSION) + tr(". Please export the account using a compatible version of this program and import it into a newly created vault."));
}
catch (const CoinDB::VaultWrongNetworkException& e)
{
LOGGER(error) << "MainWindow::openVault - VaultWrongNetworkException." << std::endl;
showError(tr("This vault file was created for the ") + QString::fromStdString(e.network()) + tr(" network."));
}
catch (const CoinDB::VaultFailedToOpenDatabaseException& e)
{
LOGGER(error) << "MainWindow::openVault - VaultFailedToOpenDatabaseException: " << e.dberror() << std::endl;
showError(tr("Error opening database: \n") + QString::fromStdString(e.dberror()));
}
catch (const exception& e)
{
LOGGER(error) << "MainWindow::openVault - " << e.what() << " " << typeid(e).name() << std::endl;
showError(e.what());
}
catch (...)
{
LOGGER(error) << "MainWindow::openVault - exception type not known." << std::endl;
showError(tr("Error opening database. Either this is an unsupported filetype or the file is corrupt."));
}
}
void MainWindow::importVault(QString /* fileName */)
{
}
void MainWindow::exportVault(QString fileName, bool exportPrivKeys)
{
if (fileName.isEmpty()) {
fileName = QFileDialog::getSaveFileName(
this,
tr("Export Vault"),
getDocDir(),
tr("Portable Vault (*.vault.all)"));
}
if (fileName.isEmpty()) return;
QFileInfo fileInfo(fileName);
setDocDir(fileInfo.dir().absolutePath());
saveSettings();
try
{
if (!synchedVault.isVaultOpen()) throw std::runtime_error("No vault is open.");
CoinDB::VaultLock lock(synchedVault);
if (!synchedVault.isVaultOpen()) throw std::runtime_error("No vault is open.");
synchedVault.getVault()->exportVault(fileName.toStdString(), exportPrivKeys);
}
catch (const exception& e)
{
LOGGER(debug) << "MainWindow::exportVault - " << e.what() << std::endl;
showError(e.what());
}
}
void MainWindow::closeVault()
{
try
{
synchedVault.closeVault();
updateVaultStatus();
}
catch (const exception& e)
{
LOGGER(debug) << "MainWindow::closeVault - " << e.what() << std::endl;
showError(e.what());
}
}
void MainWindow::newKeychain()
{
try {
if (!synchedVault.isVaultOpen()) throw std::runtime_error("No vault is open.");
NewKeychainDialog dlg(this);
if (dlg.exec()) {
QString name = dlg.getName();
//unsigned long numKeys = dlg.getNumKeys();
//updateStatusMessage(tr("Generating ") + QString::number(numKeys) + tr(" keys..."));
if (keychainModel->exists(name)) throw std::runtime_error("A keychain with that name already exists.");
{
// TODO: Randomize using user input for entropy
secure_bytes_t seed = getRandomBytes(32);
// Prompt user to write down and verify word list
KeychainBackupWizard backupWizard(name, seed, this);
if (!backupWizard.exec()) return;
/*
while (true)
{
try
{
ImportBIP39Dialog checkDlg(name, this);
if (!checkDlg.exec()) return; // User canceled out
secure_bytes_t seed2 = checkDlg.getSeed();
if (seed == seed2) break;
else throw std::runtime_error("Wordlists do not match.");
}
catch (const exception& e)
{
showError(e.what());
}
}
*/
CoinDB::VaultLock lock(synchedVault);
if (!synchedVault.isVaultOpen()) throw std::runtime_error("No vault is open.");
synchedVault.getVault()->newKeychain(name.toStdString(), seed);
}
keychainModel->update();
keychainView->updateColumns();
tabWidget->setCurrentWidget(keychainView);
updateStatusMessage(tr("Created keychain ") + name);
}
}
catch (const exception& e) {
LOGGER(debug) << "MainWindow::newKeyChain - " << e.what() << std::endl;
showError(e.what());
}
}
bool MainWindow::unlockKeychain(QString name)
{
try
{
if (name.isNull())
{
QModelIndex index = keychainSelectionModel->currentIndex();
int row = index.row();
if (row < 0)
{
showError(tr("No keychain is selected."));
return false;
}
QStandardItem* nameItem = keychainModel->item(row, 0);
name = nameItem->data(Qt::DisplayRole).toString();
}
secure_bytes_t hash;
if (keychainModel->isEncrypted(name))
{
PassphraseDialog dlg(tr("Enter unlock passphrase for ") + name + tr(":"));
while (true)
{
if (!dlg.exec()) return false;
try
{
hash = passphraseHash(dlg.getPassphrase().toStdString());
break;
}
catch (const std::exception& e)
{
showError(e.what());
}
}
}
return keychainModel->unlockKeychain(name, hash);
}
catch (const std::exception& e)
{
showError(e.what());
}
return false;
}
void MainWindow::lockKeychain(QString name)
{
if (name.isNull())
{
QModelIndex index = keychainSelectionModel->currentIndex();
int row = index.row();
if (row < 0)
{
showError(tr("No keychain is selected."));
return;
}
QStandardItem* nameItem = keychainModel->item(row, 0);
name = nameItem->data(Qt::DisplayRole).toString();
}
keychainModel->lockKeychain(name);
}
void MainWindow::lockAllKeychains()
{
keychainModel->lockAllKeychains();
}
int MainWindow::setKeychainPassphrase(const QString& keychainName)
{
QString name;
bool bLocked;
bool bEncrypted;
if (keychainName.isEmpty())
{
QModelIndex index = keychainSelectionModel->currentIndex();
int row = index.row();
if (row < 0)
{
showError(tr("No keychain is selected."));
return QDialog::Rejected;
}
bLocked = (keychainModel->getStatus(row) == KeychainModel::LOCKED);
bEncrypted = keychainModel->isEncrypted(row);
QStandardItem* nameItem = keychainModel->item(row, 0);
name = nameItem->data(Qt::DisplayRole).toString();
}
else
{
if (!keychainModel->exists(keychainName))
{
showError(tr("Keychain not found."));
return QDialog::Rejected;
}
bLocked = keychainModel->isLocked(keychainName);
bEncrypted = keychainModel->isEncrypted(keychainName);
name = keychainName;
}
try
{
if (!synchedVault.isVaultOpen()) throw std::runtime_error("No vault is open.");
CoinDB::VaultLock lock(synchedVault);
if (!synchedVault.isVaultOpen()) throw std::runtime_error("No vault is open.");
if (bLocked && !unlockKeychain(name)) return QDialog::Rejected;
SetPassphraseDialog dlg(tr("keychain \"") + name + "\"", tr("WARNING: IF YOU FORGET THIS PASSPHRASE THERE IS NO WAY TO RECOVER IT!!!"), this);
while (dlg.exec())
{
try
{
QString passphrase = dlg.getPassphrase();
if (passphrase.isEmpty())
{
QString prompt(tr("You did not enter a passphrase."));
if (bEncrypted)
{
prompt += tr(" Are you sure you want to remove keychain encryption from ") + name + "?";
}
else
{
prompt += tr(" Leave keychain ") + name + tr(" unencrypted?");
}
if (QMessageBox::Yes == QMessageBox::question(this, tr("Confirm"), prompt))
{
keychainModel->decryptKeychain(name);
if (bLocked) { lockKeychain(name); }
return QDialog::Accepted;
}
}
else
{
secure_bytes_t hash = passphraseHash(dlg.getPassphrase().toStdString());
keychainModel->encryptKeychain(name, hash);
if (bLocked) { lockKeychain(name); }
return QDialog::Accepted;
}
}
catch (const std::exception& e)
{
showError(e.what());
}
}
}
catch (const exception& e)
{
LOGGER(error) << "MainWindow::setKeychainPassphrase - " << e.what() << std::endl;
if (bLocked) { lockKeychain(name); }
showError(e.what());
}
return QDialog::Rejected;
SetPassphraseDialog dlg(tr("keychain \"") + name + "\"", tr("WARNING: IF YOU FORGET THIS PASSPHRASE THERE IS NO WAY TO RECOVER IT!!!"), this);
while (dlg.exec())
{
try
{
QString passphrase = dlg.getPassphrase();
if (passphrase.isEmpty())
{
QString prompt(tr("You did not enter a passphrase."));
if (bEncrypted)
{
prompt += tr(" Are you sure you want to remove keychain encryption from ") + name + "?";
}
else
{
prompt += tr(" Leave keychain ") + name + tr(" unencrypted?");
}
if (QMessageBox::Yes == QMessageBox::question(this, tr("Confirm"), prompt))
{
keychainModel->decryptKeychain(name);
if (bLocked) { keychainModel->lockKeychain(name); }
return QDialog::Accepted;
}
}
else
{
secure_bytes_t hash = passphraseHash(dlg.getPassphrase().toStdString());
keychainModel->encryptKeychain(name, hash);
if (bLocked) { keychainModel->lockKeychain(name); }
return QDialog::Accepted;
}
}
catch (const std::exception& e)
{
showError(e.what());
}
}
return QDialog::Rejected;
}
int MainWindow::makeKeychainBackup(const QString& keychainName)
{
QString name;
bool bLocked;
if (keychainName.isEmpty())
{
QModelIndex index = keychainSelectionModel->currentIndex();
int row = index.row();
if (row < 0) {
showError(tr("No keychain is selected."));
return QDialog::Rejected;
}
if (!keychainModel->hasSeed(row))
{
showError(tr("Entropy seed for keychain is not known. Please use another backup format."));
return QDialog::Rejected;
}
bLocked = (keychainModel->getStatus(row) == KeychainModel::LOCKED);
QStandardItem* nameItem = keychainModel->item(row, 0);
name = nameItem->data(Qt::DisplayRole).toString();
}
else
{
if (!keychainModel->exists(keychainName))
{
showError(tr("Keychain not found."));
return QDialog::Rejected;
}
if (!keychainModel->hasSeed(keychainName))
{
showError(tr("Entropy seed for keychain is not known. Please use another backup format."));
return QDialog::Rejected;
}
bLocked = keychainModel->isLocked(keychainName);
name = keychainName;
}
try
{
if (!synchedVault.isVaultOpen()) throw std::runtime_error("No vault is open.");
CoinDB::VaultLock lock(synchedVault);
if (!synchedVault.isVaultOpen()) throw std::runtime_error("No vault is open.");
if (bLocked && !unlockKeychain(name)) return QDialog::Rejected;
secure_bytes_t seed = synchedVault.getVault()->exportBIP39(name.toStdString());
KeychainBackupWizard wizard(name, seed, this);
if (bLocked) { lockKeychain(name); }
return wizard.exec();
}