Browse Source

Wallet encryption

pull/9/head
Aditya Kulkarni 5 years ago
parent
commit
cfc2f85b08
  1. 2
      lib/Cargo.toml
  2. 69
      src/controller.cpp
  3. 48
      src/controller.h
  4. 6
      src/datamodel.h
  5. 165
      src/encryption.ui
  6. 30
      src/liteinterface.cpp
  7. 5
      src/liteinterface.h
  8. 115
      src/mainwindow.cpp
  9. 3
      src/mainwindow.h
  10. 19
      src/mainwindow.ui
  11. 8
      src/settings.h
  12. 1
      zecwallet-lite.pro

2
lib/Cargo.toml

@ -11,4 +11,4 @@ crate-type = ["staticlib"]
[dependencies]
libc = "0.2.58"
lazy_static = "1.4.0"
zecwalletlitelib = { git = "https://github.com/adityapk00/zecwallet-light-cli", rev = "b928d5f09646cc94023ea25f99951fcf1b43e90d" }
zecwalletlitelib = { git = "https://github.com/adityapk00/zecwallet-light-cli", rev = "92d3804a5c67ca7621b141518a1f72451ca6ff40" }

69
src/controller.cpp

@ -161,8 +161,6 @@ void Controller::getInfoThenRefresh(bool force) {
bool doUpdate = force || (model->getLatestBlock() != curBlock);
model->setLatestBlock(curBlock);
qDebug() << "Refreshing. Full update: " << doUpdate;
// Connected, so display checkmark.
auto tooltip = Settings::getInstance()->getSettings().server + "\n" + QString::fromStdString(reply.dump());
QIcon i(":/icons/res/connected.gif");
@ -178,6 +176,14 @@ void Controller::getInfoThenRefresh(bool force) {
// See if recurring payments needs anything
Recurring::getInstance()->processPending(main);
// Check if the wallet is locked/encrypted
zrpc->fetchWalletEncryptionStatus([=] (const json& reply) {
bool isEncrypted = reply["encrypted"].get<json::boolean_t>();
bool isLocked = reply["locked"].get<json::boolean_t>();
model->setEncryptionStatus(isEncrypted, isLocked);
});
if ( doUpdate ) {
// Something changed, so refresh everything.
refreshBalances();
@ -405,6 +411,31 @@ void Controller::refreshTransactions() {
});
}
// If the wallet is encrpyted and locked, we need to unlock it
void Controller::unlockIfEncrypted(std::function<void(void)> cb, std::function<void(void)> error) {
auto encStatus = getModel()->getEncryptionStatus();
if (encStatus.first && encStatus.second) {
// Wallet is encrypted and locked. Ask for the password and unlock.
QString password = QInputDialog::getText(main, main->tr("Wallet Password"),
main->tr("Please enter your wallet password"), QLineEdit::Password);
zrpc->unlockWallet(password, [=](json reply) {
if (isJsonSuccess(reply)) {
cb();
} else {
QMessageBox::critical(main, main->tr("Wallet Decryption Failed"),
QString::fromStdString(reply["error"].get<json::string_t>()),
QMessageBox::Ok
);
error();
}
});
} else {
// Not locked, so just call the function
cb();
}
}
/**
* Execute a transaction with the standard UI. i.e., standard status bar message and standard error
* handling
@ -430,21 +461,25 @@ void Controller::executeStandardUITransaction(Tx tx) {
void Controller::executeTransaction(Tx tx,
const std::function<void(QString txid)> submitted,
const std::function<void(QString txid, QString errStr)> error) {
// First, create the json params
json params = json::array();
fillTxJsonParams(params, tx);
std::cout << std::setw(2) << params << std::endl;
zrpc->sendTransaction(QString::fromStdString(params.dump()), [=](const json& reply) {
if (reply.find("txid") == reply.end()) {
error("", "Couldn't understand Response: " + QString::fromStdString(reply.dump()));
} else {
QString txid = QString::fromStdString(reply["txid"].get<json::string_t>());
submitted(txid);
}
},
[=](QString errStr) {
error("", errStr);
unlockIfEncrypted([=] () {
// First, create the json params
json params = json::array();
fillTxJsonParams(params, tx);
std::cout << std::setw(2) << params << std::endl;
zrpc->sendTransaction(QString::fromStdString(params.dump()), [=](const json& reply) {
if (reply.find("txid") == reply.end()) {
error("", "Couldn't understand Response: " + QString::fromStdString(reply.dump()));
} else {
QString txid = QString::fromStdString(reply["txid"].get<json::string_t>());
submitted(txid);
}
},
[=](QString errStr) {
error("", errStr);
});
}, [=]() {
error("", main->tr("Failed to unlock wallet"));
});
}

48
src/controller.h

@ -38,8 +38,7 @@ public:
void checkForUpdate(bool silent = true);
void refreshZECPrice();
//void getZboardTopics(std::function<void(QMap<QString, QString>)> cb);
void executeStandardUITransaction(Tx tx);
void executeTransaction(Tx tx,
@ -54,11 +53,42 @@ public:
void noConnection();
bool isEmbedded() { return ezcashd != nullptr; }
void createNewZaddr(bool sapling, const std::function<void(json)>& cb) { zrpc->createNewZaddr(sapling, cb); }
void createNewTaddr(const std::function<void(json)>& cb) { zrpc->createNewTaddr(cb); }
void fetchPrivKey(QString addr, const std::function<void(json)>& cb) { zrpc->fetchPrivKey(addr, cb); }
void fetchAllPrivKeys(const std::function<void(json)> cb) { zrpc->fetchAllPrivKeys(cb); }
void encryptWallet(QString password, const std::function<void(json)>& cb) {
zrpc->encryptWallet(password, cb);
}
void removeWalletEncryption(QString password, const std::function<void(json)>& cb) {
zrpc->removeWalletEncryption(password, cb); }
void saveWallet(const std::function<void(json)>& cb) { zrpc->saveWallet(cb); }
void createNewZaddr(bool sapling, const std::function<void(json)>& cb) {
unlockIfEncrypted([=] () {
zrpc->createNewZaddr(sapling, cb);
}, [=](){});
}
void createNewTaddr(const std::function<void(json)>& cb) {
unlockIfEncrypted([=] () {
zrpc->createNewTaddr(cb);
}, [=](){});
}
void fetchPrivKey(QString addr, const std::function<void(json)>& cb) {
unlockIfEncrypted([=] () {
zrpc->fetchPrivKey(addr, cb);
},
[=]() {
cb({ {"error", "Failed to unlock wallet"} });
});
}
void fetchAllPrivKeys(const std::function<void(json)> cb) {
unlockIfEncrypted([=] () {
zrpc->fetchAllPrivKeys(cb);
},
[=]() {
cb({ {"error", "Failed to unlock wallet"} });
});
}
// void importZPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb) { zrpc->importZPrivKey(addr, rescan, cb); }
// void importTPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb) { zrpc->importTPrivKey(addr, rescan, cb); }
@ -74,7 +104,9 @@ private:
void processUnspent (const json& reply, QMap<QString, CAmount>* newBalances, QList<UnspentOutput>* newUnspentOutputs);
void updateUI (bool anyUnconfirmed);
void getInfoThenRefresh(bool force);
void getInfoThenRefresh (bool force);
void unlockIfEncrypted (std::function<void(void)> cb, std::function<void(void)> error);
QProcess* ezcashd = nullptr;

6
src/datamodel.h

@ -28,6 +28,9 @@ public:
void setLatestBlock(int blockHeight);
int getLatestBlock() { return this->latestBlock; }
void setEncryptionStatus(bool encrypted, bool locked) { this->isEncrypted = encrypted; this->isLocked = locked; }
QPair<bool, bool> getEncryptionStatus() { return qMakePair(this->isEncrypted, this->isLocked); }
const QList<QString> getAllZAddresses() { QReadLocker locker(lock); return *zaddresses; }
const QList<QString> getAllTAddresses() { QReadLocker locker(lock); return *taddresses; }
const QList<UnspentOutput> getUTXOs() { QReadLocker locker(lock); return *utxos; }
@ -42,6 +45,9 @@ public:
private:
int latestBlock;
bool isEncrypted = false;
bool isLocked = false;
QList<UnspentOutput>* utxos = nullptr;
QMap<QString, CAmount>* balances = nullptr;
QMap<QString, bool>* usedAddresses = nullptr;

165
src/encryption.ui

@ -0,0 +1,165 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>encryptionDialog</class>
<widget class="QDialog" name="encryptionDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Encrypt Your Wallet</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="3" column="0" colspan="2">
<widget class="Line" name="line_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Encryption Password:</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Confirm Password:</string>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QLineEdit" name="txtConfirmPassword">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
<item row="4" column="0" colspan="2">
<widget class="QLabel" name="lblPasswordMatch">
<property name="styleSheet">
<string notr="true">color: red;</string>
</property>
<property name="text">
<string>Passwords don't match</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QLineEdit" name="txtPassword">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
<item row="8" column="0" colspan="2">
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item row="1" column="0" colspan="2">
<widget class="QLabel" name="label_2">
<property name="text">
<string>WARNING: If you forget your password, the only way to recover the wallet is from the seed phrase.</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="9" column="0" colspan="2">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
<property name="centerButtons">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="0" colspan="2">
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="0" colspan="2">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<tabstops>
<tabstop>txtPassword</tabstop>
<tabstop>txtConfirmPassword</tabstop>
</tabstops>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>encryptionDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>encryptionDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

30
src/liteinterface.cpp

@ -77,6 +77,36 @@ void LiteInterface::saveWallet(const std::function<void(json)>& cb) {
conn->doRPCWithDefaultErrorHandling("save", "", cb);
}
void LiteInterface::unlockWallet(QString password, const std::function<void(json)>& cb) {
if (conn == nullptr)
return;
conn->doRPCWithDefaultErrorHandling("unlock", password, cb);
}
void LiteInterface::fetchWalletEncryptionStatus(const std::function<void(json)>& cb) {
if (conn == nullptr)
return;
conn->doRPCWithDefaultErrorHandling("encryptionstatus", "", cb);
}
void LiteInterface::encryptWallet(QString password, const std::function<void(json)>& cb) {
if (conn == nullptr)
return;
conn->doRPCWithDefaultErrorHandling("encrypt", password, cb);
}
void LiteInterface::removeWalletEncryption(QString password, const std::function<void(json)>& cb) {
if (conn == nullptr)
return;
conn->doRPCWithDefaultErrorHandling("decrypt", password, cb);
}
void LiteInterface::sendTransaction(QString params, const std::function<void(json)>& cb,
const std::function<void(QString)>& err) {
if (conn == nullptr)

5
src/liteinterface.h

@ -55,6 +55,11 @@ public:
void saveWallet(const std::function<void(json)>& cb);
void fetchWalletEncryptionStatus(const std::function<void(json)>& cb);
void encryptWallet(QString password, const std::function<void(json)>& cb);
void unlockWallet(QString password, const std::function<void(json)>& cb);
void removeWalletEncryption(QString password, const std::function<void(json)>& cb);
//void importZPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb);
//void importTPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb);

115
src/mainwindow.cpp

@ -1,6 +1,7 @@
#include "mainwindow.h"
#include "addressbook.h"
#include "viewalladdresses.h"
#include "ui_encryption.h"
#include "ui_mainwindow.h"
#include "ui_mobileappconnector.h"
#include "ui_addressbook.h"
@ -22,8 +23,6 @@ MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// Include css
QString theme_name;
try
@ -79,6 +78,15 @@ MainWindow::MainWindow(QWidget *parent) :
payZcashURI();
});
// Wallet encryption
QObject::connect(ui->actionEncrypt_Wallet, &QAction::triggered, [=]() {
encryptWallet();
});
QObject::connect(ui->actionRemove_Wallet_Encryption, &QAction::triggered, [=]() {
removeWalletEncryption();
});
// Export All Private Keys
QObject::connect(ui->actionExport_All_Private_Keys, &QAction::triggered, this, &MainWindow::exportAllKeys);
@ -211,6 +219,107 @@ void MainWindow::closeEvent(QCloseEvent* event) {
QMainWindow::closeEvent(event);
}
void MainWindow::encryptWallet() {
// Check if wallet is already encrypted
auto encStatus = rpc->getModel()->getEncryptionStatus();
if (encStatus.first) {
QMessageBox::information(this, tr("Wallet is already encrypted"),
tr("Your wallet is already encrypted with a password.\nPlease use 'Remove Wallet Encryption if you want to remove the wallet encryption."),
QMessageBox::Ok
);
return;
}
QDialog d(this);
Ui_encryptionDialog ed;
ed.setupUi(&d);
// Handle edits on the password box
auto fnPasswordEdited = [=](const QString&) {
// Enable the OK button if the passwords match.
if (!ed.txtPassword->text().isEmpty() &&
ed.txtPassword->text() == ed.txtConfirmPassword->text()) {
ed.lblPasswordMatch->setText("");
ed.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
} else {
ed.lblPasswordMatch->setText(tr("Passwords don't match"));
ed.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
}
};
ed.txtPassword->setText("");
QObject::connect(ed.txtConfirmPassword, &QLineEdit::textChanged, fnPasswordEdited);
QObject::connect(ed.txtPassword, &QLineEdit::textChanged, fnPasswordEdited);
auto fnShowError = [=](QString title, const json& res) {
QMessageBox::critical(this, title,
tr("Error was:\n") + QString::fromStdString(res.dump()),
QMessageBox::Ok
);
};
if (d.exec() == QDialog::Accepted) {
rpc->encryptWallet(ed.txtPassword->text(), [=](json res) {
if (isJsonSuccess(res)) {
// Save the wallet
rpc->saveWallet([=] (json reply) {
if (isJsonSuccess(reply)) {
QMessageBox::information(this, tr("Wallet Encrypted"),
tr("Your wallet was successfully encrypted! The password will be needed to send funds or export private keys."),
QMessageBox::Ok
);
} else {
fnShowError(tr("Wallet Encryption Failed"), reply);
}
});
} else {
fnShowError(tr("Wallet Encryption Failed"), res);
}
});
}
}
void MainWindow::removeWalletEncryption() {
// Check if wallet is already encrypted
auto encStatus = rpc->getModel()->getEncryptionStatus();
if (!encStatus.first) {
QMessageBox::information(this, tr("Wallet is not encrypted"),
tr("Your wallet is not encrypted with a password."),
QMessageBox::Ok
);
return;
}
QString password = QInputDialog::getText(this, tr("Wallet Password"),
tr("Please enter your wallet password"), QLineEdit::Password);
rpc->removeWalletEncryption(password, [=] (json res) {
if (isJsonSuccess(res)) {
// Save the wallet
rpc->saveWallet([=] (json reply) {
if(isJsonSuccess(reply)) {
QMessageBox::information(this, tr("Wallet Encryption Removed"),
tr("Your wallet was successfully decrypted! You will no longer need a password to send funds or export private keys."),
QMessageBox::Ok
);
} else {
QMessageBox::critical(this, tr("Wallet Decryption Failed"),
QString::fromStdString(reply["error"].get<json::string_t>()),
QMessageBox::Ok
);
}
});
} else {
QMessageBox::critical(this, tr("Wallet Decryption Failed"),
QString::fromStdString(res["error"].get<json::string_t>()),
QMessageBox::Ok
);
}
});
}
void MainWindow::setupStatusBar() {
// Status Bar
loadingLabel = new QLabel();
@ -602,7 +711,7 @@ void MainWindow::exportKeys(QString addr) {
if (! *(isDialogAlive.get()) ) return;
if (reply.is_discarded() || !reply.is_array()) {
pui.privKeyTxt->setPlainText(tr("Error loading private keys"));
pui.privKeyTxt->setPlainText(tr("Error loading private keys: ") + QString::fromStdString(reply.dump()));
pui.buttonBox->button(QDialogButtonBox::Save)->setEnabled(false);
return;

3
src/mainwindow.h

@ -96,6 +96,9 @@ private:
Tx createTxFromSendPage();
bool confirmTx(Tx tx, RecurringPaymentInfo* rpi);
void encryptWallet();
void removeWalletEncryption();
void cancelButton();
void sendButton();
void addAddressSection();

19
src/mainwindow.ui

@ -392,8 +392,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>1162</width>
<height>344</height>
<width>1226</width>
<height>504</height>
</rect>
</property>
<layout class="QVBoxLayout" name="sendToLayout">
@ -1088,7 +1088,7 @@
<x>0</x>
<y>0</y>
<width>1274</width>
<height>39</height>
<height>22</height>
</rect>
</property>
<widget class="QMenu" name="menuFile">
@ -1127,6 +1127,9 @@
<addaction name="action_Address_Book"/>
<addaction name="actionSettings"/>
<addaction name="action_Recurring_Payments"/>
<addaction name="separator"/>
<addaction name="actionEncrypt_Wallet"/>
<addaction name="actionRemove_Wallet_Encryption"/>
</widget>
<addaction name="menuFile"/>
<addaction name="menu_Edit"/>
@ -1213,6 +1216,16 @@
<string>File a bug...</string>
</property>
</action>
<action name="actionEncrypt_Wallet">
<property name="text">
<string>Encrypt Wallet</string>
</property>
</action>
<action name="actionRemove_Wallet_Encryption">
<property name="text">
<string>Remove Wallet Encryption</string>
</property>
</action>
</widget>
<layoutdefault spacing="6" margin="11"/>
<customwidgets>

8
src/settings.h

@ -4,6 +4,8 @@
#include "precompiled.h"
#include "camount.h"
using json = nlohmann::json;
struct Config {
QString server;
};
@ -119,4 +121,10 @@ private:
double zecPrice = 0.0;
};
inline bool isJsonSuccess(const json& res) {
return res.find("result") != res.end() &&
QString::fromStdString(res["result"].get<json::string_t>()) == "success";
}
#endif // SETTINGS_H

1
zecwallet-lite.pro

@ -93,6 +93,7 @@ HEADERS += \
lib/zecwalletlitelib.h
FORMS += \
src/encryption.ui \
src/mainwindow.ui \
src/migration.ui \
src/newseed.ui \

Loading…
Cancel
Save