diff --git a/.gitignore b/.gitignore index 104bfd1..708ea83 100644 --- a/.gitignore +++ b/.gitignore @@ -12,11 +12,11 @@ src/ui_*.h *.autosave src/precompiled.h.cpp .qmake.stash -silentdragon -silentdragon.app +silentdragonlite +silentdragonlite.app silentdragon-lite-mingw* silentdragon-lite.vcxproj* -silentdragon.vcxproj* +silentdragonlite.vcxproj* silentdragon-lite.sln silentdragon-lite.pro.user /Makefile @@ -37,3 +37,6 @@ IDEWorkspaceChecks.plist *.sln node_modules silentdragonlite.pro.user.4.10-pre1 +silentdragonlite +silentdragonlite_plugin_import.cpp +silentdragonlite_resource.rc diff --git a/README.md b/README.md index d1a6433..457524b 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,31 @@ # SilentDragonLite -SilentDragonLite is a GUI wallet for the [Hush](https://myhush.org) cryptocoin, which does not require you to download the full blockchain! +SilentDragonLite is a lightwallet for HUSH ($HUSH) runs on Linux and Windows which does not require you to download the full blockchain. This is experimental software under active development! +## PRIVACY NOTICE + +SilentDragonLite contacts a few different external websites to get various bits of data. * coingecko.com for price data API * explorer.myhush.org for explorer links * dexstats.info for address utilities, hush-lightwallet.de to get Data. + +This means your IP address is known to these servers. Enable Tor setting in SilentDragon to prevent this, or better yet, use TAILS: https://tails.boum.org/ + +## Installation + +Go to the releases page and grab the latest installers or binary. https://github.com/MyHush/SilentDragonLite/releases ## Compiling from source - -* silentdragon is written in C++ 14, and can be compiled with g++/clang++/visual c++. +* SilentDragonLite is written in C++ 14, and can be compiled with g++/clang++/visual c++. * It also depends on Qt5, which you can get from [here](https://www.qt.io/download). * You'll need Rust v1.37 + -### Building on Linux +## Building on Linux ``` -git clone https://github.com/MyHush/SilenDragonLite -cd SilentDragonLite -qmake silentdragon-lite.pro CONFIG+=debug +git clone https://github.com/MyHush/SilenDragonLite.git +cd silentdragonlite +/path/to/qt5/bin/qmake silentdragon-lite.pro CONFIG+=debug make -j$(nproc) -``` -And to run the binary: -``` ./silentdragonlite ``` + + diff --git a/lib/Cargo.lock b/lib/Cargo.lock index 6d809c1..7b6162e 100644 --- a/lib/Cargo.lock +++ b/lib/Cargo.lock @@ -1051,7 +1051,7 @@ version = "0.1.0" dependencies = [ "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", - "silentdragonlitelib 0.1.0 (git+https://github.com/DenioD/silentdragonlite-cli?rev=89ee34ba526d9d45a72787b07af9407bd96a337c)", + "silentdragonlitelib 0.1.0 (git+https://github.com/MyHush/silentdragonlite-cli?rev=099ad194dac6ee51474b3637d357aca0665a8181)", ] [[package]] @@ -1467,7 +1467,7 @@ dependencies = [ [[package]] name = "silentdragonlitelib" version = "0.1.0" -source = "git+https://github.com/DenioD/silentdragonlite-cli?rev=89ee34ba526d9d45a72787b07af9407bd96a337c#89ee34ba526d9d45a72787b07af9407bd96a337c" +source = "git+https://github.com/MyHush/silentdragonlite-cli?rev=099ad194dac6ee51474b3637d357aca0665a8181#099ad194dac6ee51474b3637d357aca0665a8181" dependencies = [ "base58 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "bellman 0.1.0 (git+https://github.com/DenioD/librustzcash.git?rev=caaee693c47c2ee9ecd1e1546b8fe3c714f342bc)", @@ -2481,7 +2481,7 @@ dependencies = [ "checksum serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)" = "2f72eb2a68a7dc3f9a691bfda9305a1c017a6215e5a4545c258500d2099a37c2" "checksum serde_yaml 0.8.11 (registry+https://github.com/rust-lang/crates.io-index)" = "691b17f19fc1ec9d94ec0b5864859290dff279dbd7b03f017afda54eb36c3c35" "checksum sha2 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7b4d8bfd0e469f417657573d8451fb33d16cfe0989359b93baf3a1ffc639543d" -"checksum silentdragonlitelib 0.1.0 (git+https://github.com/DenioD/silentdragonlite-cli?rev=89ee34ba526d9d45a72787b07af9407bd96a337c)" = "" +"checksum silentdragonlitelib 0.1.0 (git+https://github.com/MyHush/silentdragonlite-cli?rev=099ad194dac6ee51474b3637d357aca0665a8181)" = "" "checksum slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" "checksum smallvec 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)" = "ab606a9c5e214920bb66c458cd7be8ef094f813f20fe77a54cc7dbfff220d4b7" "checksum sodiumoxide 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "585232e78a4fc18133eef9946d3080befdf68b906c51b621531c37e91787fa2b" diff --git a/lib/Cargo.toml b/lib/Cargo.toml index 327b017..2681097 100644 --- a/lib/Cargo.toml +++ b/lib/Cargo.toml @@ -11,4 +11,4 @@ crate-type = ["staticlib"] [dependencies] libc = "0.2.58" lazy_static = "1.4.0" -silentdragonlitelib = { git = "https://github.com/DenioD/silentdragonlite-cli", rev = "89ee34ba526d9d45a72787b07af9407bd96a337c" } +silentdragonlitelib = { git = "https://github.com/MyHush/silentdragonlite-cli", rev = "099ad194dac6ee51474b3637d357aca0665a8181" } diff --git a/lib/Makefile b/lib/Makefile index 788c55e..9dbe82a 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -1,24 +1,28 @@ ifeq ($(shell uname),Darwin) EXT := dylib + CFLAGS := "-mmacosx-version-min=10.11" else EXT := a + CFLAGS := "" endif +PWD := $(shell pwd) + all: release winrelease: target/x86_64-pc-windows-gnu/release/silentdragonlite.lib target/x86_64-pc-windows-gnu/release/silentdragonlite.lib: src/lib.rs Cargo.toml - cargo build --lib --release --target x86_64-pc-windows-gnu + SODIUM_LIB_DIR="$(PWD)/libsodium-mingw/" cargo build --lib --release --target x86_64-pc-windows-gnu release: target/release/silentdragonlite.$(EXT) debug: target/debug/silentdragonlite.$(EXT) target/release/silentdragonlite.$(EXT): src/lib.rs Cargo.toml - cargo build --lib --release + LIBS="" CFLAGS=$(CFLAGS) cargo build --lib --release target/debug/silentdragonlite.$(EXT): src/lib.rs Cargo.toml - cargo build --lib + LIBS="" CFLAGS=$(CFLAGS) cargo build --lib clean: rm -rf target \ No newline at end of file diff --git a/lib/libsodium-mingw/libsodium.a b/lib/libsodium-mingw/libsodium.a new file mode 100644 index 0000000..363c743 Binary files /dev/null and b/lib/libsodium-mingw/libsodium.a differ diff --git a/lib/src/lib.rs b/lib/src/lib.rs index d6f5a1f..932ded9 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -105,14 +105,6 @@ pub extern fn litelib_initialize_new_from_phrase(dangerous: bool, server: *const } }; - let seed = match lightclient.do_seed_phrase() { - Ok(s) => s.dump(), - Err(e) => { - let e_str = CString::new(format!("Error: {}", e)).unwrap(); - return e_str.into_raw(); - } - }; - LIGHTCLIENT.lock().unwrap().replace(Some(Arc::new(lightclient))); let c_str = CString::new("OK").unwrap(); diff --git a/res/logo.svg b/res/logo.svg index 9378773..70f95bc 100644 --- a/res/logo.svg +++ b/res/logo.svg @@ -14,12 +14,25 @@ xml:space="preserve" style="clip-rule:evenodd;fill-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:1.5" id="svg947" - sodipodi:docname="logo2.svg" - inkscape:version="0.92.3 (2405546, 2018-03-11)">image/svg+xml + + + + + + + + + + + + + - + id="g906" + transform="matrix(8.0134463,-0.61542838,0.57707593,7.5140325,-224.79791,-183.45367)"> - - + style="fill:#403c3c;stroke:#676767;stroke-width:1.55999994px" + d="m 101.667,55.665 c 0,-4.644 -3.536,-8.415 -7.891,-8.415 H 34.391 c -4.355,0 -7.891,3.771 -7.891,8.415 v 32.67 c 0,4.644 3.536,8.415 7.891,8.415 h 59.385 c 4.355,0 7.891,-3.771 7.891,-8.415 z" /> + - - - + + - - + height="10.333" + width="123.333" + y="15.958" + x="30.333" /> + - - - - - + - - + - - - - - - -image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/res/wxsbanner.bmp b/res/wxsbanner.bmp index 6040470..ede9d60 100644 Binary files a/res/wxsbanner.bmp and b/res/wxsbanner.bmp differ diff --git a/res/wxsdialog.bmp b/res/wxsdialog.bmp index 44cb85f..5e129dd 100644 Binary files a/res/wxsdialog.bmp and b/res/wxsdialog.bmp differ diff --git a/res/zecwallet.xpm b/res/zecwallet-lite.xpm similarity index 100% rename from res/zecwallet.xpm rename to res/zecwallet-lite.xpm diff --git a/silentdragon-lite.pro b/silentdragon-lite.pro index de67ff7..e54460a 100644 --- a/silentdragon-lite.pro +++ b/silentdragon-lite.pro @@ -13,7 +13,7 @@ PRECOMPILED_HEADER = src/precompiled.h QT += widgets QT += websockets -TARGET = silentdragonlite +TARGET = Silentdragonlite TEMPLATE = app @@ -60,7 +60,8 @@ SOURCES += \ src/viewalladdresses.cpp \ src/datamodel.cpp \ src/controller.cpp \ - src/liteinterface.cpp + src/liteinterface.cpp \ + src/camount.cpp HEADERS += \ src/firsttimewizard.h \ @@ -88,9 +89,11 @@ HEADERS += \ src/datamodel.h \ src/controller.h \ src/liteinterface.h \ + src/camount.h \ lib/silentdragonlitelib.h FORMS += \ + src/encryption.ui \ src/mainwindow.ui \ src/migration.ui \ src/newseed.ui \ @@ -110,7 +113,7 @@ FORMS += \ src/recurringdialog.ui \ src/newrecurring.ui \ src/requestdialog.ui \ - src/recurringmultiple.ui + src/recurringmultiple.ui TRANSLATIONS = res/zec_qt_wallet_es.ts \ @@ -145,6 +148,8 @@ else:win32: librust.target = $$PWD/lib/target/x86_64-pc-windows-gnu/release/s unix: librust.commands = $(MAKE) -C $$PWD/lib else:win32: librust.commands = $(MAKE) -C $$PWD/lib winrelease +librust.depends = lib/Cargo.toml lib/src/lib.rs + librustclean.commands = "rm -rf $$PWD/lib/target" distclean.depends += librustclean diff --git a/silentdragonlite b/silentdragonlite deleted file mode 100755 index ffde6d1..0000000 Binary files a/silentdragonlite and /dev/null differ diff --git a/src/about.ui b/src/about.ui index adc856d..2d28f7d 100644 --- a/src/about.ui +++ b/src/about.ui @@ -17,7 +17,7 @@ - silentdragon FullNode + SilentDragon Lite @@ -41,7 +41,7 @@ 0 0 463 - 517 + 534 @@ -51,17 +51,18 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.1pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">Copyright (c) 2018 Aditya Kulkarni. (MIT License)</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Ubuntu'; font-size:11pt;"><br /></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">Special thanks to:</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">JSON for Modern C++ : </span><a href="https://nlohmann.github.io/json/"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">https://nlohmann.github.io/json/</span></a></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">QR Code generator library Nayuki : </span><a href="https://www.nayuki.io/page/qr-code-generator-library"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">https://www.nayuki.io/page/qr-code-ge…</span></a></p> -<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">Made with QT : </span><a href="https://www.qt.io/"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">https://www.qt.io/</span></a></p> -<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">LICENSE:</span></p> -<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Ubuntu'; font-size:11pt;">Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the &quot;Software&quot;), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</span></p> -<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" font-family:'Ubuntu'; font-size:11pt;" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</li> -<li style=" font-family:'Ubuntu'; font-size:11pt;" style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The Software is provided &quot;as is&quot;, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software.</li></ul></body></html> +</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Copyright (c) 2018-2019 DenioD (MIT License)</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Special thanks to:</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Aditya Kulkarni for the awesome open source code</p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">JSON for Modern C++ : <a href="https://nlohmann.github.io/json/"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">https://nlohmann.github.io/json/</span></a></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">QR Code generator library Nayuki : <a href="https://www.nayuki.io/page/qr-code-generator-library"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">https://www.nayuki.io/page/qr-code-ge…</span></a></p> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Made with QT : <a href="https://www.qt.io/"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">https://www.qt.io/</span></a></p> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">LICENSE:</p> +<p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the &quot;Software&quot;), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</p> +<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</li> +<li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The Software is provided &quot;as is&quot;, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software.</li></ul></body></html> true diff --git a/src/addresscombo.cpp b/src/addresscombo.cpp index 7957d9c..2fc7031 100644 --- a/src/addresscombo.cpp +++ b/src/addresscombo.cpp @@ -24,16 +24,16 @@ void AddressCombo::setCurrentText(const QString& text) { } } -void AddressCombo::addItem(const QString& text, double bal) { +void AddressCombo::addItem(const QString& text, CAmount bal) { QString txt = AddressBook::addLabelToAddress(text); - if (bal > 0) - txt = txt % "(" % Settings::gethushDisplayFormat(bal) % ")"; + if (bal.toqint64() > 0) + txt = txt % "(" % bal.toDecimalhushString() % ")"; QComboBox::addItem(txt); } -void AddressCombo::insertItem(int index, const QString& text, double bal) { +void AddressCombo::insertItem(int index, const QString& text, CAmount bal) { QString txt = AddressBook::addLabelToAddress(text) % - "(" % Settings::gethushDisplayFormat(bal) % ")"; + "(" % bal.toDecimalhushString() % ")"; QComboBox::insertItem(index, txt); } \ No newline at end of file diff --git a/src/addresscombo.h b/src/addresscombo.h index 8088906..ee1c8ed 100644 --- a/src/addresscombo.h +++ b/src/addresscombo.h @@ -1,6 +1,7 @@ #ifndef ADDRESSCOMBO_H #define ADDRESSCOMBO_H +#include "camount.h" #include "precompiled.h" class AddressCombo : public QComboBox @@ -12,8 +13,8 @@ public: QString itemText(int i); QString currentText(); - void addItem(const QString& itemText, double bal); - void insertItem(int index, const QString& text, double bal = 0.0); + void addItem(const QString& itemText, CAmount bal); + void insertItem(int index, const QString& text, CAmount bal = CAmount::fromqint64(0)); public slots: void setCurrentText(const QString& itemText); diff --git a/src/balancestablemodel.cpp b/src/balancestablemodel.cpp index 673b3bb..22a40bb 100644 --- a/src/balancestablemodel.cpp +++ b/src/balancestablemodel.cpp @@ -1,32 +1,45 @@ #include "balancestablemodel.h" #include "addressbook.h" #include "settings.h" +#include "camount.h" BalancesTableModel::BalancesTableModel(QObject *parent) : QAbstractTableModel(parent) { } -void BalancesTableModel::setNewData(const QMap balances, - const QList outputs) +void BalancesTableModel::setNewData(const QList zaddrs, const QList taddrs, + const QMap balances, const QList outputs) { loading = false; int currentRows = rowCount(QModelIndex()); // Copy over the utxos for our use - delete utxos; - utxos = new QList(); + delete unspentOutputs; + unspentOutputs = new QList(); // This is a QList deep copy. - *utxos = outputs; + *unspentOutputs = outputs; // Process the address balances into a list delete modeldata; - modeldata = new QList>(); + modeldata = new QList>(); std::for_each(balances.keyBegin(), balances.keyEnd(), [=] (auto keyIt) { - if (balances.value(keyIt) > 0) - modeldata->push_back(std::make_tuple(keyIt, balances.value(keyIt))); + modeldata->push_back(std::make_tuple(keyIt, balances.value(keyIt))); }); + // Add all addresses that have no balances as well + for (auto zaddr: zaddrs) { + if (!balances.contains(zaddr)) { + modeldata->push_back(std::make_tuple(zaddr, CAmount::fromqint64(0))); + } + } + + for (auto taddr: taddrs) { + if (!balances.contains(taddr)) { + modeldata->push_back(std::make_tuple(taddr, CAmount::fromqint64(0))); + } + } + // And then update the data dataChanged(index(0, 0), index(modeldata->size()-1, columnCount(index(0,0))-1)); @@ -37,7 +50,7 @@ void BalancesTableModel::setNewData(const QMap balances, BalancesTableModel::~BalancesTableModel() { delete modeldata; - delete utxos; + delete unspentOutputs; } int BalancesTableModel::rowCount(const QModelIndex&) const @@ -70,8 +83,9 @@ QVariant BalancesTableModel::data(const QModelIndex &index, int role) const if (role == Qt::ForegroundRole) { // If any of the UTXOs for this address has zero confirmations, paint it in red const auto& addr = std::get<0>(modeldata->at(index.row())); - for (auto utxo : *utxos) { - if (utxo.address == addr && !utxo.spendable) { + for (auto unconfirmedOutput : *unspentOutputs) { + if (unconfirmedOutput.address == addr && + (!unconfirmedOutput.spendable || unconfirmedOutput.pending)) { QBrush b; b.setColor(Qt::red); return b; @@ -87,14 +101,14 @@ QVariant BalancesTableModel::data(const QModelIndex &index, int role) const if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return AddressBook::addLabelToAddress(std::get<0>(modeldata->at(index.row()))); - case 1: return Settings::gethushDisplayFormat(std::get<1>(modeldata->at(index.row()))); + case 1: return std::get<1>(modeldata->at(index.row())).toDecimalhushString(); } } if(role == Qt::ToolTipRole) { switch (index.column()) { case 0: return AddressBook::addLabelToAddress(std::get<0>(modeldata->at(index.row()))); - case 1: return Settings::getUSDFormat(std::get<1>(modeldata->at(index.row()))); + case 1: return std::get<1>(modeldata->at(index.row())).toDecimalhushString(); } } diff --git a/src/balancestablemodel.h b/src/balancestablemodel.h index e712f62..f46e5fe 100644 --- a/src/balancestablemodel.h +++ b/src/balancestablemodel.h @@ -3,6 +3,7 @@ #include "precompiled.h" #include "datamodel.h" +#include "camount.h" class BalancesTableModel : public QAbstractTableModel @@ -11,7 +12,7 @@ public: BalancesTableModel(QObject* parent); ~BalancesTableModel(); - void setNewData(const QMap balances, const QList outputs); + void setNewData(const QList zaddrs, const QList taddrs, const QMap balances, const QList outputs); int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; @@ -19,8 +20,8 @@ public: QVariant headerData(int section, Qt::Orientation orientation, int role) const; private: - QList>* modeldata = nullptr; - QList* utxos = nullptr; + QList>* modeldata = nullptr; + QList* unspentOutputs = nullptr; bool loading = true; }; diff --git a/src/camount.cpp b/src/camount.cpp new file mode 100644 index 0000000..9c4b590 --- /dev/null +++ b/src/camount.cpp @@ -0,0 +1,64 @@ +#include "camount.h" +#include "settings.h" + +#include "precompiled.h" + +const int NUMPLACES = 8; +const qint64 COIN = 100000000; + +double CAmount::toDecimalDouble() const { + return static_cast(this->amount) / COIN; +} + +QString CAmount::toDecimalString() const { + if (amount < 0) { + CAmount negative(-1 * this->amount); + return "-" + negative.toDecimalString(); + } + + int wholePart = amount / COIN; + int decimalPart = amount % COIN; + + QString r = QString::number(wholePart); + if (decimalPart > 0) { + QString decimalPartStr = QString::number(decimalPart); + r = r + "." + decimalPartStr.rightJustified(NUMPLACES, '0'); + + // Trim tailing 0s + while (r.right(1) == "0") { + r = r.left(r.length() - 1); + } + } + + return r; +} + +QString CAmount::toDecimalUSDString() const { + double dblAmount = static_cast(this->amount) / COIN; + double price = Settings::getInstance()->getZECPrice(); + + return "$" + QLocale(QLocale::English).toString(dblAmount*price, 'f', 2); +} + +QString CAmount::toDecimalhushString() const { + return this->toDecimalString() % " " % Settings::getTokenName(); +} + +QString CAmount::toDecimalhushUSDString() const { + auto usdString = this->toDecimalUSDString(); + if (!usdString.isEmpty()) + return this->toDecimalhushString() % " (" % usdString % ")"; + else + return this->toDecimalhushString(); +} + +CAmount CAmount::fromDecimalString(QString decimalString) { + auto amtParts = decimalString.split("."); + qint64 r = amtParts[0].toULongLong() * COIN; + if (amtParts.length() == 2) { + auto trailingZeros = QString("0").repeated(NUMPLACES - amtParts[1].length()); + r += QString(amtParts[1] + trailingZeros).toULongLong(); + } + + return CAmount(r); +} \ No newline at end of file diff --git a/src/camount.h b/src/camount.h new file mode 100644 index 0000000..08c4cb3 --- /dev/null +++ b/src/camount.h @@ -0,0 +1,55 @@ +#ifndef CAMOUNT_H +#define CAMOUNT_H + +#include "precompiled.h" + +class CAmount { +private: + CAmount(qint64 amount) { + this->amount = amount; + } + + qint64 amount; + +public: + static CAmount fromDecimalString(QString decimalString); + static CAmount fromqint64(qint64 a) { + return CAmount(a); + } + static CAmount fromDouble(double d) { + return CAmount::fromDecimalString(QString::number(d, 'f', 8)); + } + + CAmount() : amount(0) {}; + CAmount(const CAmount&) = default; + ~CAmount() = default; + + double toDecimalDouble() const; + QString toDecimalString() const; + QString toDecimalUSDString() const; + QString toDecimalhushString() const; + QString toDecimalhushUSDString() const; + qint64 toqint64() const { return amount; }; + + CAmount operator+ (const CAmount& other) const { + return CAmount(this->amount + other.amount); + } + + CAmount operator- (const CAmount& other) const { + return CAmount(this->amount - other.amount); + } + + bool operator< (const CAmount& other) const { + return this->amount < other.amount; + } + + bool operator< (const qint64& other) const { + return this->amount < other; + } + + bool operator> (const CAmount& other) const { + return this->amount > other.amount; + } +}; + +#endif // CAMOUNT_H diff --git a/src/confirm.ui b/src/confirm.ui index 7bf4df6..5babfd4 100644 --- a/src/confirm.ui +++ b/src/confirm.ui @@ -6,33 +6,14 @@ 0 0 - 538 - 458 + 626 + 713 Confirm Transaction - - - - From - - - - - - - - - true - - - - - - @@ -174,19 +155,6 @@ - - - - color: red; - - - hushd doesn't seem to have any peers. You might not be connected to the internet, so this transaction might not work. - - - true - - - @@ -200,19 +168,6 @@ - - - - color: red; - - - You are using a custom fee. Since fees are transparent, you are giving up some privacy. Please use this only if you know what you are doing! - - - true - - - diff --git a/src/connection.cpp b/src/connection.cpp index 439e9e1..7e90358 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -43,20 +43,20 @@ void ConnectionLoader::doAutoConnect() { auto config = std::shared_ptr(new ConnectionConfig()); config->dangerous = true; - config->server = QString("https://hush-lightwallet.de:439"); + config->server = Settings::getInstance()->getSettings().server; // Initialize the library - main->logger->write(QObject::tr("Attempting to initialize")); + main->logger->write(QObject::tr("Attempting to initialize library with ") + config->server); // Check to see if there's an existing wallet if (litelib_wallet_exists(Settings::getChainName().toStdString().c_str())) { main->logger->write(QObject::tr("Using existing wallet.")); - char* resp = litelib_initialize_existing(config->dangerous, config->server.toStdString().c_str()); + char* resp = litelib_initialize_existing(config->dangerous, config->server.toStdString().c_str()); QString response = litelib_process_response(resp); if (response.toUpper().trimmed() != "OK") { showError(response); - return; + return; } } else { main->logger->write(QObject::tr("Create/restore wallet.")); @@ -65,9 +65,10 @@ void ConnectionLoader::doAutoConnect() { } auto connection = makeConnection(config); + auto me = this; // After the lib is initialized, try to do get info - connection->doRPC("info", "", [=](auto reply) { + connection->doRPC("info", "", [=](auto) { // If success, set the connection main->logger->write("Connection is online."); @@ -95,7 +96,7 @@ void ConnectionLoader::doAutoConnect() { if (isSyncing != nullptr && reply.find("synced_blocks") != reply.end()) { qint64 synced = reply["synced_blocks"].get(); qint64 total = reply["total_blocks"].get(); - showInformation("Synced " + QString::number(synced) + " / " + QString::number(total)); + me->showInformation("Synced " + QString::number(synced) + " / " + QString::number(total)); } }, [=](QString err) { @@ -173,15 +174,11 @@ void Executor::run() { QString reply = litelib_process_response(resp); - qDebug() << "Reply=" << reply; + //qDebug() << "RPC Reply=" << reply; auto parsed = json::parse(reply.toStdString().c_str(), nullptr, false); if (parsed.is_discarded() || parsed.is_null()) { emit handleError(reply); } else { - const bool isGuiThread = - QThread::currentThread() == QCoreApplication::instance()->thread(); - qDebug() << "executing RPC: isGUI=" << isGuiThread; - emit responseReady(parsed); } } @@ -216,7 +213,7 @@ void Connection::doRPC(const QString cmd, const QString args, const std::functio return; } - qDebug() << "Doing RPC: " << cmd; + //qDebug() << "Doing RPC: " << cmd; // Create a runner. auto runner = new Executor(cmd, args); diff --git a/src/controller.cpp b/src/controller.cpp index 3c01f1b..24476e7 100644 --- a/src/controller.cpp +++ b/src/controller.cpp @@ -3,6 +3,7 @@ #include "addressbook.h" #include "settings.h" #include "version.h" +#include "camount.h" #include "websockets.h" using json = nlohmann::json; @@ -28,7 +29,7 @@ Controller::Controller(MainWindow* main) { priceTimer = new QTimer(main); QObject::connect(priceTimer, &QTimer::timeout, [=]() { if (Settings::getInstance()->getAllowFetchPrices()) - refreshhushPrice(); + refreshZECPrice(); }); priceTimer->start(Settings::priceRefreshSpeed); // Every hour @@ -64,16 +65,11 @@ void Controller::setConnection(Connection* c) { this->zrpc->setConnection(c); - ui->statusBar->showMessage("Connectet with https://hush-lightwallet.de"); + ui->statusBar->showMessage(""); - // See if we need to remove the reindex/rescan flags from the hush.conf file - auto hushConfLocation = Settings::getInstance()->gethushdConfLocation(); - Settings::removeFromhushConf(hushConfLocation, "rescan"); - Settings::removeFromhushConf(hushConfLocation, "reindex"); - - // If we're allowed to get the hush Price, get the prices + // If we're allowed to get the Hush Price, get the prices if (Settings::getInstance()->getAllowFetchPrices()) - refreshhushPrice(); + refreshZECPrice(); // If we're allowed to check for updates, check for a new release if (Settings::getInstance()->getCheckForUpdates()) @@ -96,18 +92,12 @@ void Controller::fillTxJsonParams(json& allRecepients, Tx tx) { // Construct the JSON params json rec = json::object(); rec["address"] = toAddr.addr.toStdString(); - rec["amount"] = toAddr.amount * 100000000; + rec["amount"] = toAddr.amount.toqint64(); if (Settings::isZAddress(toAddr.addr) && !toAddr.memo.trimmed().isEmpty()) rec["memo"] = toAddr.memo.toStdString(); allRecepients.push_back(rec); } - - // // Add fees if custom fees are allowed. - // if (Settings::getInstance()->getAllowCustomFees()) { - // params.push_back(1); // minconf - // params.push_back(tx.fee); - // } } @@ -120,9 +110,10 @@ void Controller::noConnection() { main->ui->statusBar->showMessage(QObject::tr("No Connection"), 1000); // Clear balances table. - QMap emptyBalances; + QMap emptyBalances; QList emptyOutputs; - balancesTableModel->setNewData(emptyBalances, emptyOutputs); + QList emptyAddresses; + balancesTableModel->setNewData(emptyAddresses, emptyAddresses, emptyBalances, emptyOutputs); // Clear Transactions table. QList emptyTxs; @@ -136,9 +127,6 @@ void Controller::noConnection() { ui->balSheilded->setToolTip(""); ui->balTransparent->setToolTip(""); ui->balTotal->setToolTip(""); - - // Clear send tab from address - ui->inputsCombo->clear(); } /// This will refresh all the balance data from hushd @@ -156,8 +144,6 @@ void Controller::getInfoThenRefresh(bool force) { static bool prevCallSucceeded = false; zrpc->fetchInfo([=] (const json& reply) { - qDebug() << "Info updated"; - prevCallSucceeded = true; // Testnet? @@ -171,18 +157,21 @@ void Controller::getInfoThenRefresh(bool force) { if (!Settings::getInstance()->isTestnet()) main->disableRecurring(); - static int lastBlock = 0; int curBlock = reply["latest_block_height"].get(); + bool doUpdate = force || (model->getLatestBlock() != curBlock); model->setLatestBlock(curBlock); ui->blockHeight->setText(QString::number(curBlock)); // Connected, so display checkmark. + auto tooltip = Settings::getInstance()->getSettings().server + "\n" + QString::fromStdString(reply.dump()); QIcon i(":/icons/res/connected.gif"); - main->statusLabel->setText( "connected" "(" + QString::number(curBlock) + ")"); - main->statusLabel->setText(" HUSH/USD=$" + QString::number( (double) Settings::getInstance()->gethushPrice() )); + main->statusLabel->setText(chainName + "(" + QString::number(curBlock) + ")"); + main->statusLabel->setText(" HUSH/USD=$" + QString::number( (double) Settings::getInstance()->getZECPrice() )); + main->statusLabel->setToolTip(tooltip); main->statusIcon->setPixmap(i.pixmap(16, 16)); - - //int version = reply["version"].get(); + main->statusIcon->setToolTip(tooltip); + + //int version = reply["version"].get(); int version = 1; Settings::getInstance()->sethushdVersion(version); ui->Version->setText(QString::fromStdString(reply["version"].get())); @@ -194,10 +183,16 @@ void Controller::getInfoThenRefresh(bool force) { // See if recurring payments needs anything Recurring::getInstance()->processPending(main); - if ( force || (curBlock != lastBlock) ) { - // Something changed, so refresh everything. - lastBlock = curBlock; + // Check if the wallet is locked/encrypted + zrpc->fetchWalletEncryptionStatus([=] (const json& reply) { + bool isEncrypted = reply["encrypted"].get(); + bool isLocked = reply["locked"].get(); + model->setEncryptionStatus(isEncrypted, isLocked); + }); + + if ( doUpdate ) { + // Something changed, so refresh everything. refreshBalances(); refreshAddresses(); // This calls refreshZSentTransactions() and refreshReceivedZTrans() refreshTransactions(); @@ -255,71 +250,105 @@ void Controller::updateUI(bool anyUnconfirmed) { ui->unconfirmedWarning->setVisible(anyUnconfirmed); // Update balances model data, which will update the table too - balancesTableModel->setNewData(model->getAllBalances(), model->getUTXOs()); - - // Update from address - main->updateFromCombo(); + balancesTableModel->setNewData(model->getAllZAddresses(), model->getAllTAddresses(), model->getAllBalances(), model->getUTXOs()); }; // Function to process reply of the listunspent and z_listunspent API calls, used below. -bool Controller::processUnspent(const json& reply, QMap* balancesMap, QList* newUtxos) { - bool anyUnconfirmed = false; - - auto processFn = [=](const json& array) { +void Controller::processUnspent(const json& reply, QMap* balancesMap, QList* unspentOutputs) { + auto processFn = [=](const json& array) { for (auto& it : array) { QString qsAddr = QString::fromStdString(it["address"]); int block = it["created_in_block"].get(); QString txid = QString::fromStdString(it["created_in_txid"]); - QString amount = Settings::getDecimalString(it["value"].get()); + CAmount amount = CAmount::fromqint64(it["value"].get()); - newUtxos->push_back(UnspentOutput{ qsAddr, txid, amount, block, true }); + bool spendable = it["unconfirmed_spent"].is_null() && it["spent"].is_null(); // TODO: Wait for 4 confirmations + bool pending = !it["unconfirmed_spent"].is_null(); - (*balancesMap)[qsAddr] = ((*balancesMap)[qsAddr] + (it["value"].get()) /100000000); - } + unspentOutputs->push_back(UnspentOutput{ qsAddr, txid, amount, block, spendable, pending }); + if (spendable) { + (*balancesMap)[qsAddr] = (*balancesMap)[qsAddr] + + CAmount::fromqint64(it["value"].get()); + } + } }; processFn(reply["unspent_notes"].get()); processFn(reply["utxos"].get()); - - return anyUnconfirmed; + processFn(reply["pending_notes"].get()); + processFn(reply["pending_utxos"].get()); }; +void Controller::updateUIBalances() { + CAmount balT = getModel()->getBalT(); + CAmount balZ = getModel()->getBalZ(); + CAmount balVerified = getModel()->getBalVerified(); + + // Reduce the BalanceZ by the pending outgoing amount. We're adding + // here because totalPending is already negative for outgoing txns. + balZ = balZ + getModel()->getTotalPending(); + + CAmount balTotal = balT + balZ; + CAmount balAvailable = balT + balVerified; + + // Balances table + ui->balSheilded ->setText(balZ.toDecimalhushString()); + ui->balVerified ->setText(balVerified.toDecimalhushString()); + ui->balTransparent->setText(balT.toDecimalhushString()); + ui->balTotal ->setText(balTotal.toDecimalhushString()); + + ui->balSheilded ->setToolTip(balZ.toDecimalUSDString()); + ui->balVerified ->setToolTip(balVerified.toDecimalUSDString()); + ui->balTransparent->setToolTip(balT.toDecimalUSDString()); + ui->balTotal ->setToolTip(balTotal.toDecimalUSDString()); + + // Send tab + ui->txtAvailablehush->setText(balAvailable.toDecimalhushString()); + ui->txtAvailableUSD->setText(balAvailable.toDecimalUSDString()); +} + void Controller::refreshBalances() { if (!zrpc->haveConnection()) return noConnection(); // 1. Get the Balances zrpc->fetchBalance([=] (json reply) { - auto balT = reply["tbalance"].get(); - auto balZ = reply["zbalance"].get(); - auto balTotal = balT + balZ; + CAmount balT = CAmount::fromqint64(reply["tbalance"].get()); + CAmount balZ = CAmount::fromqint64(reply["zbalance"].get()); + CAmount balVerified = CAmount::fromqint64(reply["verified_zbalance"].get()); + + model->setBalT(balT); + model->setBalZ(balZ); + model->setBalVerified(balVerified); + // This is for the websockets AppDataModel::getInstance()->setBalances(balT, balZ); + + // This is for the datamodel + CAmount balAvailable = balT + balVerified; + model->setAvailableBalance(balAvailable); - ui->balSheilded ->setText(Settings::gethushDisplayFormat(balZ /100000000)); - ui->balTransparent->setText(Settings::gethushDisplayFormat(balT /100000000)); - ui->balTotal ->setText(Settings::gethushDisplayFormat(balTotal /100000000)); - - - ui->balSheilded ->setToolTip(Settings::gethushDisplayFormat(balZ /100000000)); - ui->balTransparent->setToolTip(Settings::gethushDisplayFormat(balT /100000000)); - ui->balTotal ->setToolTip(Settings::gethushDisplayFormat(balTotal /100000000)); - - + updateUIBalances(); }); // 2. Get the UTXOs // First, create a new UTXO list. It will be replacing the existing list when everything is processed. - auto newUtxos = new QList(); - auto newBalances = new QMap(); + auto newUnspentOutputs = new QList(); + auto newBalances = new QMap(); // Call the Transparent and Z unspent APIs serially and then, once they're done, update the UI zrpc->fetchUnspent([=] (json reply) { - auto anyUnconfirmed = processUnspent(reply, newBalances, newUtxos); + processUnspent(reply, newBalances, newUnspentOutputs); // Swap out the balances and UTXOs model->replaceBalances(newBalances); - model->replaceUTXOs(newUtxos); + model->replaceUTXOs(newUnspentOutputs); + + // Find if any output is not spendable or is pending + bool anyUnconfirmed = std::find_if(newUnspentOutputs->constBegin(), newUnspentOutputs->constEnd(), + [=](const UnspentOutput& u) -> bool { + return !u.spendable || u.pending; + }) != newUnspentOutputs->constEnd(); updateUI(anyUnconfirmed); @@ -336,15 +365,27 @@ void Controller::refreshTransactions() { for (auto& it : reply.get()) { QString address; - quint64 total_amount; + CAmount total_amount; QList items; + long confirmations; + if (it.find("unconfirmed") != it.end() && it["unconfirmed"].get()) { + confirmations = 0; + } else { + confirmations = model->getLatestBlock() - it["block_height"].get() + 1; + } + + auto txid = QString::fromStdString(it["txid"]); + auto datetime = it["datetime"].get(); + // First, check if there's outgoing metadata if (!it["outgoing_metadata"].is_null()) { for (auto o: it["outgoing_metadata"].get()) { QString address = QString::fromStdString(o["address"]); - double amount = -1 * o ["value"].get() /100000000; // Sent items are -ve + + // Sent items are -ve + CAmount amount = CAmount::fromqint64(-1 * o["value"].get()); // Check for Memos @@ -355,42 +396,40 @@ void Controller::refreshTransactions() { } items.push_back(TransactionItemDetail{address, amount, memo}); - total_amount += amount; + total_amount = total_amount + amount; } - if (items.length() == 1) { - address = items[0].address; - } else { - address = "(Multiple)"; + { + // Concat all the addresses + QList addresses; + for (auto item : items) { + addresses.push_back(item.address); + } + address = addresses.join(","); } txdata.push_back(TransactionItem{ - "Sent", - it["datetime"].get(), - address, - QString::fromStdString(it["txid"]), - model->getLatestBlock() - it["block_height"].get(), - items + "Sent", datetime, address, txid,confirmations, items }); } else { // Incoming Transaction address = (it["address"].is_null() ? "" : QString::fromStdString(it["address"])); model->markAddressUsed(address); + QString memo; + if (!it["memo"].is_null()) { + memo = QString::fromStdString(it["memo"]); + } + items.push_back(TransactionItemDetail{ address, - it["amount"].get() /100000000, - "" + CAmount::fromqint64(it["amount"].get()), + memo }); TransactionItem tx{ - "Receive", - it["datetime"].get(), - address, - QString::fromStdString(it["txid"]), - model->getLatestBlock() - it["block_height"].get(), - items + "Receive", datetime, address, txid,confirmations, items }; txdata.push_back(tx); @@ -398,11 +437,63 @@ void Controller::refreshTransactions() { } + // Calculate the total unspent amount that's pending. This will need to be + // shown in the UI so the user can keep track of pending funds + CAmount totalPending; + for (auto txitem : txdata) { + if (txitem.confirmations == 0) { + for (auto item: txitem.items) { + totalPending = totalPending + item.amount; + } + } + } + getModel()->setTotalPending(totalPending); + + // Update UI Balance + updateUIBalances(); + // Update model data, which updates the table view transactionsTableModel->replaceData(txdata); }); } +// If the wallet is encrpyted and locked, we need to unlock it +void Controller::unlockIfEncrypted(std::function cb, std::function 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("Your wallet is encrypted.\nPlease enter your wallet password"), QLineEdit::Password); + + if (password.isEmpty()) { + QMessageBox::critical(main, main->tr("Wallet Decryption Failed"), + main->tr("Please enter a valid password"), + QMessageBox::Ok + ); + error(); + return; + } + + zrpc->unlockWallet(password, [=](json reply) { + if (isJsonResultSuccess(reply)) { + cb(); + + // Refresh the wallet so the encryption status is now in sync. + refresh(true); + } else { + QMessageBox::critical(main, main->tr("Wallet Decryption Failed"), + QString::fromStdString(reply["error"].get()), + 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 @@ -428,21 +519,25 @@ void Controller::executeStandardUITransaction(Tx tx) { void Controller::executeTransaction(Tx tx, const std::function submitted, const std::function error) { - // First, create the json params - json params = json::array(); - fillTxJsonParams(params, tx); - std::cout << std::setw(2) << params << std::endl; + 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())); - } - - QString txid = QString::fromStdString(reply["txid"].get()); - submitted(txid); - }, - [=](QString errStr) { - error("", errStr); + 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()); + submitted(txid); + } + }, + [=](QString errStr) { + error("", errStr); + }); + }, [=]() { + error("", main->tr("Failed to unlock wallet")); }); } @@ -451,7 +546,7 @@ void Controller::checkForUpdate(bool silent) { if (!zrpc->haveConnection()) return noConnection(); - QUrl cmcURL("https://api.github.com/repos/MyHush/SilentDragonLite/releases"); + QUrl cmcURL("https://api.github.com/repos/DenioD/SilentDragonLite/releases"); QNetworkRequest req; req.setUrl(cmcURL); @@ -499,7 +594,7 @@ void Controller::checkForUpdate(bool silent) { .arg(currentVersion.toString()), QMessageBox::Yes, QMessageBox::Cancel); if (ans == QMessageBox::Yes) { - QDesktopServices::openUrl(QUrl("https://github.com/MyHush/SilentDragonLite/releases")); + QDesktopServices::openUrl(QUrl("https://github.com/DenioD/SilentDragonLite/releases")); } else { // If the user selects cancel, don't bother them again for this version s.setValue("update/lastversion", maxVersion.toString()); @@ -521,7 +616,7 @@ void Controller::checkForUpdate(bool silent) { } // Get the hush->USD price from coinmarketcap using their API -void Controller::refreshhushPrice() { +void Controller::refreshZECPrice() { if (!zrpc->haveConnection()) return noConnection(); @@ -546,7 +641,7 @@ void Controller::refreshhushPrice() { } else { qDebug() << reply->errorString(); } - Settings::getInstance()->sethushPrice(0); + Settings::getInstance()->setZECPrice(0); return; } @@ -555,7 +650,7 @@ void Controller::refreshhushPrice() { auto all = reply->readAll(); auto parsed = json::parse(all, nullptr, false); if (parsed.is_discarded()) { - Settings::getInstance()->sethushPrice(0); + Settings::getInstance()->setZECPrice(0); return; } @@ -569,7 +664,7 @@ void Controller::refreshhushPrice() { // TODO: support BTC/EUR prices as well //QString price = QString::fromStdString(hush["usd"].get()); qDebug() << "HUSH = $" << QString::number((double)hush["usd"]); - Settings::getInstance()->sethushPrice( hush["usd"] ); + Settings::getInstance()->setZECPrice( hush["usd"] ); return; } } catch (const std::exception& e) { @@ -578,7 +673,7 @@ void Controller::refreshhushPrice() { } // If nothing, then set the price to 0; - Settings::getInstance()->sethushPrice(0); + Settings::getInstance()->setZECPrice(0); }); } diff --git a/src/controller.h b/src/controller.h index b66d2c0..8dd9ff9 100644 --- a/src/controller.h +++ b/src/controller.h @@ -3,6 +3,7 @@ #include "precompiled.h" +#include "camount.h" #include "datamodel.h" #include "balancestablemodel.h" #include "txtablemodel.h" @@ -21,15 +22,6 @@ struct WatchedTx { }; -struct MigrationStatus { - bool available; // Whether the underlying hushd supports migration? - bool enabled; - QString saplingAddress; - double unmigrated; - double migrated; - QList txids; -}; - class Controller { public: @@ -44,9 +36,8 @@ public: void refreshAddresses(); void checkForUpdate(bool silent = true); - void refreshhushPrice(); - //void getZboardTopics(std::function)> cb); - + void refreshZECPrice(); + void executeStandardUITransaction(Tx tx); void executeTransaction(Tx tx, @@ -61,11 +52,52 @@ public: void noConnection(); bool isEmbedded() { return ehushd != nullptr; } - void createNewZaddr(bool sapling, const std::function& cb) { zrpc->createNewZaddr(sapling, cb); } - void createNewTaddr(const std::function& cb) { zrpc->createNewTaddr(cb); } + void encryptWallet(QString password, const std::function& cb) { + zrpc->encryptWallet(password, cb); + } + + void removeWalletEncryption(QString password, const std::function& cb) { + zrpc->removeWalletEncryption(password, cb); } - void fetchPrivKey(QString addr, const std::function& cb) { zrpc->fetchPrivKey(addr, cb); } - void fetchAllPrivKeys(const std::function cb) { zrpc->fetchAllPrivKeys(cb); } + void saveWallet(const std::function& cb) { zrpc->saveWallet(cb); } + + void createNewZaddr(bool sapling, const std::function& cb) { + unlockIfEncrypted([=] () { + zrpc->createNewZaddr(sapling, cb); + }, [=](){}); + } + void createNewTaddr(const std::function& cb) { + unlockIfEncrypted([=] () { + zrpc->createNewTaddr(cb); + }, [=](){}); + } + + void fetchPrivKey(QString addr, const std::function& cb) { + unlockIfEncrypted([=] () { + zrpc->fetchPrivKey(addr, cb); + }, + [=]() { + cb({ {"error", "Failed to unlock wallet"} }); + }); + } + + void fetchAllPrivKeys(const std::function cb) { + unlockIfEncrypted([=] () { + zrpc->fetchAllPrivKeys(cb); + }, + [=]() { + cb({ {"error", "Failed to unlock wallet"} }); + }); + } + + void fetchSeed(const std::function cb) { + unlockIfEncrypted([=] () { + zrpc->fetchSeed(cb); + }, + [=]() { + cb({ {"error", "Failed to unlock wallet"} }); + }); + } // void importZPrivKey(QString addr, bool rescan, const std::function& cb) { zrpc->importZPrivKey(addr, rescan, cb); } // void importTPrivKey(QString addr, bool rescan, const std::function& cb) { zrpc->importTPrivKey(addr, rescan, cb); } @@ -78,10 +110,13 @@ private: void refreshTransactions(); - bool processUnspent (const json& reply, QMap* newBalances, QList* newUtxos); + void processUnspent (const json& reply, QMap* newBalances, QList* newUnspentOutputs); void updateUI (bool anyUnconfirmed); + void updateUIBalances (); - void getInfoThenRefresh(bool force); + void getInfoThenRefresh (bool force); + + void unlockIfEncrypted (std::function cb, std::function error); QProcess* ehushd = nullptr; @@ -89,7 +124,7 @@ private: BalancesTableModel* balancesTableModel = nullptr; DataModel* model; - LiteInterface* zrpc; + LiteInterface* zrpc; QTimer* timer; QTimer* txTimer; diff --git a/src/datamodel.cpp b/src/datamodel.cpp index d86259c..c1c4d66 100644 --- a/src/datamodel.cpp +++ b/src/datamodel.cpp @@ -7,7 +7,7 @@ DataModel::DataModel() { QWriteLocker locker(lock); utxos = new QList(); - balances = new QMap(); + balances = new QMap(); usedAddresses = new QMap(); zaddresses = new QList(); taddresses = new QList(); @@ -24,6 +24,7 @@ DataModel::~DataModel() { } void DataModel::setLatestBlock(int blockHeight) { + QReadLocker locker(lock); this->latestBlock = blockHeight; } @@ -44,7 +45,7 @@ void DataModel::replaceTaddresses(QList* newT) { taddresses = newT; } -void DataModel::replaceBalances(QMap* newBalances) { +void DataModel::replaceBalances(QMap* newBalances) { QWriteLocker locker(lock); Q_ASSERT(newBalances); diff --git a/src/datamodel.h b/src/datamodel.h index c3dd12c..4d2ac06 100644 --- a/src/datamodel.h +++ b/src/datamodel.h @@ -1,15 +1,17 @@ #ifndef DATAMODEL_H #define DATAMODEL_H +#include "camount.h" #include "precompiled.h" struct UnspentOutput { QString address; QString txid; - QString amount; + CAmount amount; int blockCreated; bool spendable; + bool pending; }; @@ -18,34 +20,60 @@ class DataModel { public: void replaceZaddresses(QList* newZ); void replaceTaddresses(QList* newZ); - void replaceBalances(QMap* newBalances); + void replaceBalances(QMap* newBalances); void replaceUTXOs(QList* utxos); void markAddressUsed(QString address); void setLatestBlock(int blockHeight); - int getLatestBlock() { return this->latestBlock; } + int getLatestBlock() { QReadLocker locker(lock); return this->latestBlock; } + + void setEncryptionStatus(bool encrypted, bool locked) { this->isEncrypted = encrypted; this->isLocked = locked; } + QPair getEncryptionStatus() { return qMakePair(this->isEncrypted, this->isLocked); } const QList getAllZAddresses() { QReadLocker locker(lock); return *zaddresses; } const QList getAllTAddresses() { QReadLocker locker(lock); return *taddresses; } const QList getUTXOs() { QReadLocker locker(lock); return *utxos; } - const QMap getAllBalances() { QReadLocker locker(lock); return *balances; } - const QMap getUsedAddresses() { QReadLocker locker(lock); return *usedAddresses; } + const QMap getAllBalances() { QReadLocker locker(lock); return *balances; } + const QMap getUsedAddresses() { QReadLocker locker(lock); return *usedAddresses; } + + CAmount getAvailableBalance() { QReadLocker locker(lock); return availableBalance; } + void setAvailableBalance(CAmount a) { QReadLocker locker(lock); this->availableBalance = a; } + CAmount getBalT() { QReadLocker locker(lock); return balT; } + void setBalT(CAmount a) { QReadLocker locker(lock); this->balT = a; } + + CAmount getBalZ() { QReadLocker locker(lock); return balZ; } + void setBalZ(CAmount a) { QReadLocker locker(lock); this->balZ = a; } + + CAmount getBalVerified() { QReadLocker locker(lock); return balVerified; } + void setBalVerified(CAmount a) { QReadLocker locker(lock); this->balVerified = a; } + + CAmount getTotalPending() { QReadLocker locker(lock); return totalPending; } + void setTotalPending(CAmount a) { QReadLocker locker(lock); this->totalPending = a; } DataModel(); ~DataModel(); private: int latestBlock; + bool isEncrypted = false; + bool isLocked = false; + QList* utxos = nullptr; - QMap* balances = nullptr; + QMap* balances = nullptr; QMap* usedAddresses = nullptr; QList* zaddresses = nullptr; QList* taddresses = nullptr; - QReadWriteLock* lock; + CAmount availableBalance; + CAmount totalPending; // Outgoing pending is -ve + CAmount balT; + CAmount balZ; + CAmount balVerified; + + QReadWriteLock* lock; }; #endif // DATAMODEL_H \ No newline at end of file diff --git a/src/encryption.ui b/src/encryption.ui new file mode 100644 index 0000000..b4ab606 --- /dev/null +++ b/src/encryption.ui @@ -0,0 +1,165 @@ + + + encryptionDialog + + + + 0 + 0 + 400 + 300 + + + + Encrypt Your Wallet + + + + + + Qt::Horizontal + + + + + + + Encryption Password: + + + + + + + Confirm Password: + + + + + + + QLineEdit::Password + + + + + + + color: red; + + + Passwords don't match + + + Qt::AlignCenter + + + + + + + QLineEdit::Password + + + + + + + Qt::Horizontal + + + + + + + WARNING: If you forget your password, the only way to recover the wallet is from the seed phrase. + + + Qt::AlignCenter + + + true + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + true + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + txtPassword + txtConfirmPassword + + + + + buttonBox + accepted() + encryptionDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + encryptionDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/src/liteinterface.cpp b/src/liteinterface.cpp index de77a7b..82f2dd1 100644 --- a/src/liteinterface.cpp +++ b/src/liteinterface.cpp @@ -39,7 +39,7 @@ void LiteInterface::createNewZaddr(bool, const std::function& cb) { if (conn == nullptr) return; - conn->doRPCWithDefaultErrorHandling("new", "zs1", cb); + conn->doRPCWithDefaultErrorHandling("new", "zs", cb); } void LiteInterface::createNewTaddr(const std::function& cb) { @@ -56,6 +56,13 @@ void LiteInterface::fetchPrivKey(QString addr, const std::function& conn->doRPCWithDefaultErrorHandling("export", addr, cb); } +void LiteInterface::fetchSeed(const std::function& cb) { + if (conn == nullptr) + return; + + conn->doRPCWithDefaultErrorHandling("seed", "", cb); +} + void LiteInterface::fetchBalance(const std::function& cb) { if (conn == nullptr) return; @@ -77,6 +84,36 @@ void LiteInterface::saveWallet(const std::function& cb) { conn->doRPCWithDefaultErrorHandling("save", "", cb); } +void LiteInterface::unlockWallet(QString password, const std::function& cb) { + if (conn == nullptr) + return; + + conn->doRPCWithDefaultErrorHandling("unlock", password, cb); +} + +void LiteInterface::fetchWalletEncryptionStatus(const std::function& cb) { + if (conn == nullptr) + return; + + conn->doRPCWithDefaultErrorHandling("encryptionstatus", "", cb); +} + +void LiteInterface::encryptWallet(QString password, const std::function& cb) { + if (conn == nullptr) + return; + + conn->doRPCWithDefaultErrorHandling("encrypt", password, cb); +} + + +void LiteInterface::removeWalletEncryption(QString password, const std::function& cb) { + if (conn == nullptr) + return; + + conn->doRPCWithDefaultErrorHandling("decrypt", password, cb); +} + + void LiteInterface::sendTransaction(QString params, const std::function& cb, const std::function& err) { if (conn == nullptr) diff --git a/src/liteinterface.h b/src/liteinterface.h index 5e71cb4..33c3446 100644 --- a/src/liteinterface.h +++ b/src/liteinterface.h @@ -3,6 +3,7 @@ #include "precompiled.h" +#include "camount.h" #include "connection.h" using json = nlohmann::json; @@ -11,7 +12,7 @@ using json = nlohmann::json; // into a struct with address, amount, memo struct TransactionItemDetail { QString address; - double amount; + CAmount amount; QString memo; }; @@ -52,9 +53,15 @@ public: void fetchPrivKey(QString addr, const std::function& cb); void fetchAllPrivKeys(const std::function); + void fetchSeed(const std::function&); void saveWallet(const std::function& cb); + void fetchWalletEncryptionStatus(const std::function& cb); + void encryptWallet(QString password, const std::function& cb); + void unlockWallet(QString password, const std::function& cb); + void removeWalletEncryption(QString password, const std::function& cb); + //void importZPrivKey(QString addr, bool rescan, const std::function& cb); //void importTPrivKey(QString addr, bool rescan, const std::function& cb); diff --git a/src/main.cpp b/src/main.cpp index 1353c97..8d85d26 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -150,9 +150,8 @@ public: parser.setApplicationDescription("Shielded desktop light wallet for hush"); parser.addHelpOption(); - // Positional argument will specify a hush payment URI - parser.addPositionalArgument("HUSHURI", "An optional hush URI to pay"); + parser.addPositionalArgument("hushURI", "An optional hush URI to pay"); parser.process(a); @@ -165,7 +164,7 @@ public: return 0; } - QCoreApplication::setOrganizationName("myhush.org"); + QCoreApplication::setOrganizationName("Hush"); QCoreApplication::setApplicationName("SilentDragonLite"); QString locale = QLocale::system().name(); @@ -173,7 +172,7 @@ public: qDebug() << "Loading locale " << locale; QTranslator translator; - translator.load(QString(":/translations/res/zec_qt_wallet_") + locale); + translator.load(QString(":/translations/res/hush_qt_wallet_") + locale); a.installTranslator(&translator); QIcon icon(":/icons/res/icon.ico"); @@ -203,9 +202,10 @@ public: } Settings::getInstance()->setUseEmbedded(false); + w = new MainWindow(); - w->setWindowTitle("SilentDragonLite v" + QString(APP_VERSION)); + w->setWindowTitle("SilentDragon Lite v" + QString(APP_VERSION)); // If there was a payment URI on the command line, pay it if (parser.positionalArguments().length() > 0) { diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 3616ff4..862d7e1 100644 --- a/src/mainwindow.cpp +++ b/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 @@ -37,9 +36,8 @@ MainWindow::MainWindow(QWidget *parent) : this->slot_change_theme(theme_name); - ui->setupUi(this); - logger = new Logger(this, QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)).filePath("silentdragonlite-cli-wallet.log")); + logger = new Logger(this, QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)).filePath("silentdragonlite-wallet.log")); // Status Bar setupStatusBar(); @@ -59,7 +57,7 @@ MainWindow::MainWindow(QWidget *parent) : // File a bug QObject::connect(ui->actionFile_a_bug, &QAction::triggered, [=]() { - QDesktopServices::openUrl(QUrl("https://github.com/MyHush/silentdragonlite/issues/new")); + QDesktopServices::openUrl(QUrl("https://github.com/DenioD/SilentDragonLite/issues/new")); }); // Set up check for updates action @@ -83,11 +81,20 @@ MainWindow::MainWindow(QWidget *parent) : payhushURI(); }); + // 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); // Backup wallet.dat - QObject::connect(ui->actionBackup_wallet_dat, &QAction::triggered, this, &MainWindow::backupWalletDat); + QObject::connect(ui->actionExport_Seed, &QAction::triggered, this, &MainWindow::exportSeed); // Export transactions QObject::connect(ui->actionExport_transactions, &QAction::triggered, this, &MainWindow::exportTransactions); @@ -179,13 +186,19 @@ void MainWindow::restoreSavedStates() { QSettings s; restoreGeometry(s.value("geometry").toByteArray()); - ui->balancesTable->horizontalHeader()->restoreState(s.value("baltablegeometry").toByteArray()); - ui->transactionsTable->horizontalHeader()->restoreState(s.value("tratablegeometry").toByteArray()); + auto balance_geom = s.value("baltablegeom"); + if (balance_geom == QVariant()) { + ui->balancesTable->setColumnWidth(0, 500); + } else { + ui->balancesTable->horizontalHeader()->restoreState(balance_geom.toByteArray()); + } - // Explicitly set the tx table resize headers, since some previous values may have made them - // non-expandable. - ui->transactionsTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Interactive); - ui->transactionsTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Interactive); + auto tx_geom = s.value("tratablegeom"); + if (tx_geom == QVariant()) { + ui->transactionsTable->setColumnWidth(1, 500); + } else { + ui->transactionsTable->horizontalHeader()->restoreState(tx_geom.toByteArray()); + } } void MainWindow::doClose() { @@ -196,8 +209,8 @@ void MainWindow::closeEvent(QCloseEvent* event) { QSettings s; s.setValue("geometry", saveGeometry()); - s.setValue("baltablegeometry", ui->balancesTable->horizontalHeader()->saveState()); - s.setValue("tratablegeometry", ui->transactionsTable->horizontalHeader()->saveState()); + s.setValue("baltablegeom", ui->balancesTable->horizontalHeader()->saveState()); + s.setValue("tratablegeom", ui->transactionsTable->horizontalHeader()->saveState()); s.sync(); @@ -209,6 +222,128 @@ 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); + } + }; + + QObject::connect(ed.txtConfirmPassword, &QLineEdit::textChanged, fnPasswordEdited); + QObject::connect(ed.txtPassword, &QLineEdit::textChanged, fnPasswordEdited); + + ed.txtPassword->setText(""); + ed.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); + + 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 (isJsonResultSuccess(res)) { + // Save the wallet + rpc->saveWallet([=] (json reply) { + if (isJsonResultSuccess(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); + } + }); + + // And then refresh the UI + rpc->refresh(true); + } 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; + } + + bool ok; + QString password = QInputDialog::getText(this, tr("Wallet Password"), + tr("Please enter your wallet password"), QLineEdit::Password, "", &ok); + + // If cancel was pressed, just return + if (!ok) { + return; + } + + if (password.isEmpty()) { + QMessageBox::critical(this, tr("Wallet Decryption Failed"), + tr("Please enter a password to decrypt your wallet!"), + QMessageBox::Ok + ); + return; + } + + rpc->removeWalletEncryption(password, [=] (json res) { + if (isJsonResultSuccess(res)) { + // Save the wallet + rpc->saveWallet([=] (json reply) { + if(isJsonResultSuccess(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()), + QMessageBox::Ok + ); + } + }); + + // And then refresh the UI + rpc->refresh(true); + } else { + QMessageBox::critical(this, tr("Wallet Decryption Failed"), + QString::fromStdString(res["error"].get()), + QMessageBox::Ok + ); + } + }); +} + void MainWindow::setupStatusBar() { // Status Bar loadingLabel = new QLabel(); @@ -259,11 +394,6 @@ void MainWindow::setupSettingsModal() { settings.setupUi(&settingsDialog); Settings::saveRestore(&settingsDialog); - // Setup save sent check box - QObject::connect(settings.chkSaveTxs, &QCheckBox::stateChanged, [=](auto checked) { - Settings::getInstance()->setSaveZtxs(checked); - }); - // Setup theme combo int theme_index = settings.comboBoxTheme->findText(Settings::getInstance()->get_theme_name(), Qt::MatchExactly); settings.comboBoxTheme->setCurrentIndex(theme_index); @@ -274,55 +404,15 @@ void MainWindow::setupSettingsModal() { QMessageBox::information(this, tr("Restart"), tr("Please restart Silentdragonlite to have the theme apply"), QMessageBox::Ok); }); - // Save sent transactions - settings.chkSaveTxs->setChecked(Settings::getInstance()->getSaveZtxs()); - - // Custom fees - settings.chkCustomFees->setChecked(Settings::getInstance()->getAllowCustomFees()); - - // Auto shielding - settings.chkAutoShield->setChecked(Settings::getInstance()->getAutoShield()); - // Check for updates settings.chkCheckUpdates->setChecked(Settings::getInstance()->getCheckForUpdates()); // Fetch prices settings.chkFetchPrices->setChecked(Settings::getInstance()->getAllowFetchPrices()); - - // Use Tor - bool isUsingTor = false; - if (rpc->getConnection() != nullptr) { - isUsingTor = !rpc->getConnection()->config->proxy.isEmpty(); - } - settings.chkTor->setChecked(isUsingTor); - // Connection Settings - QIntValidator validator(0, 65535); - settings.port->setValidator(&validator); - - // If values are coming from hush.conf, then disable all the fields - auto hushConfLocation = Settings::getInstance()->gethushdConfLocation(); - if (!hushConfLocation.isEmpty()) { - settings.confMsg->setText("Settings are being read from \n" + hushConfLocation); - settings.hostname->setEnabled(false); - settings.port->setEnabled(false); - settings.rpcuser->setEnabled(false); - settings.rpcpassword->setEnabled(false); - } - else { - settings.confMsg->setText("No local HUSH3.conf found. Please configure connection manually."); - settings.hostname->setEnabled(true); - settings.port->setEnabled(true); - settings.rpcuser->setEnabled(true); - settings.rpcpassword->setEnabled(true); - } - // Load current values into the dialog auto conf = Settings::getInstance()->getSettings(); - settings.hostname->setText(conf.host); - settings.port->setText(conf.port); - settings.rpcuser->setText(conf.rpcuser); - settings.rpcpassword->setText(conf.rpcpassword); + settings.txtServer->setText(conf.server); // Connection tab by default settings.tabWidget->setCurrentIndex(0); @@ -331,78 +421,25 @@ void MainWindow::setupSettingsModal() { if (!rpc->isEmbedded()) { settings.chkRescan->setEnabled(false); settings.chkRescan->setToolTip(tr("You're using an external hushd. Please restart hushd with -rescan")); - - settings.chkReindex->setEnabled(false); - settings.chkReindex->setToolTip(tr("You're using an external hushd. Please restart hushd with -reindex")); } if (settingsDialog.exec() == QDialog::Accepted) { - // Custom fees - bool customFees = settings.chkCustomFees->isChecked(); - Settings::getInstance()->setAllowCustomFees(customFees); - ui->minerFeeAmt->setReadOnly(!customFees); - if (!customFees) - ui->minerFeeAmt->setText(Settings::getDecimalString(Settings::getMinerFee())); - - // Auto shield - Settings::getInstance()->setAutoShield(settings.chkAutoShield->isChecked()); - // Check for updates Settings::getInstance()->setCheckForUpdates(settings.chkCheckUpdates->isChecked()); // Allow fetching prices Settings::getInstance()->setAllowFetchPrices(settings.chkFetchPrices->isChecked()); - if (!isUsingTor && settings.chkTor->isChecked()) { - // If "use tor" was previously unchecked and now checked - Settings::addTohushConf(hushConfLocation, "proxy=127.0.0.1:9050"); - rpc->getConnection()->config->proxy = "proxy=127.0.0.1:9050"; + // Save the server + Settings::getInstance()->saveSettings(settings.txtServer->text().trimmed()); - QMessageBox::information(this, tr("Enable Tor"), - tr("Connection over Tor has been enabled. To use this feature, you need to restart Silentdragonlite."), - QMessageBox::Ok); - } - - if (isUsingTor && !settings.chkTor->isChecked()) { - // If "use tor" was previously checked and now is unchecked - Settings::removeFromhushConf(hushConfLocation, "proxy"); - rpc->getConnection()->config->proxy.clear(); - - QMessageBox::information(this, tr("Disable Tor"), - tr("Connection over Tor has been disabled. To fully disconnect from Tor, you need to restart silentdragon."), - QMessageBox::Ok); - } - - if (hushConfLocation.isEmpty()) { + if (false /* connection needs reloading?*/) { // Save settings - Settings::getInstance()->saveSettings( - settings.hostname->text(), - settings.port->text(), - settings.rpcuser->text(), - settings.rpcpassword->text()); + Settings::getInstance()->saveSettings(settings.txtServer->text()); auto cl = new ConnectionLoader(this, rpc); cl->loadConnection(); } - - // Check to see if rescan or reindex have been enabled - bool showRestartInfo = false; - if (settings.chkRescan->isChecked()) { - Settings::addTohushConf(hushConfLocation, "rescan=1"); - showRestartInfo = true; - } - - if (settings.chkReindex->isChecked()) { - Settings::addTohushConf(hushConfLocation, "reindex=1"); - showRestartInfo = true; - } - - if (showRestartInfo) { - auto desc = tr("silentdragon needs to restart to rescan/reindex. silentdragon will now close, please restart silentdragon to continue"); - - QMessageBox::information(this, tr("Restart silentdragon"), desc, QMessageBox::Ok); - QTimer::singleShot(1, [=]() { this->close(); }); - } } }); } @@ -541,13 +578,9 @@ void MainWindow::payhushURI(QString uri, QString myAddr) { // Now, set the fields on the send tab clearSendForm(); - if (!myAddr.isEmpty()) { - ui->inputsCombo->setCurrentText(myAddr); - } - ui->Address1->setText(paymentInfo.addr); ui->Address1->setCursorPosition(0); - ui->Amount1->setText(Settings::getDecimalString(paymentInfo.amt.toDouble())); + ui->Amount1->setText(paymentInfo.amt); ui->MemoTxt1->setText(paymentInfo.memo); // And switch to the send tab. @@ -627,97 +660,110 @@ void MainWindow::exportTransactions() { } /** - * Backup the wallet.dat file. This is kind of a hack, since it has to read from the filesystem rather than an RPC call - * This might fail for various reasons - Remote hushd, non-standard locations, custom params passed to hushd, many others + * Export the seed phrase. */ -void MainWindow::backupWalletDat() { +void MainWindow::exportSeed() { if (!rpc->getConnection()) return; + + + + rpc->fetchSeed([=](json reply) { + if (isJsonError(reply)) { + return; + } + + QDialog d(this); + Ui_PrivKey pui; + pui.setupUi(&d); + + // Make the window big by default + auto ps = this->geometry(); + QMargins margin = QMargins() + 50; + d.setGeometry(ps.marginsRemoved(margin)); + + Settings::saveRestore(&d); + + pui.privKeyTxt->setReadOnly(true); + pui.privKeyTxt->setLineWrapMode(QPlainTextEdit::LineWrapMode::NoWrap); + pui.privKeyTxt->setPlainText(QString::fromStdString(reply.dump())); + + pui.helpLbl->setText(tr("This is your wallet seed. Please back it up carefully and safely.")); + + // Wire up save button + QObject::connect(pui.buttonBox->button(QDialogButtonBox::Save), &QPushButton::clicked, [=] () { + QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), + "Hush-seed.txt"); + QFile file(fileName); + if (!file.open(QIODevice::WriteOnly)) { + QMessageBox::information(this, tr("Unable to open file"), file.errorString()); + return; + } + QTextStream out(&file); + out << pui.privKeyTxt->toPlainText(); + }); + + pui.buttonBox->button(QDialogButtonBox::Save)->setEnabled(true); + + d.exec(); + }); } - // QDir hushdir(rpc->getConnection()->config->hushDir); - // QString backupDefaultName = "hush-wallet-backup-" + QDateTime::currentDateTime().toString("yyyyMMdd") + ".dat"; - - // if (Settings::getInstance()->isTestnet()) { - // hushdir.cd("testnet3"); - // backupDefaultName = "testnet-" + backupDefaultName; - // } - - // QFile wallet(hushdir.filePath("wallet.dat")); - // if (!wallet.exists()) { - // QMessageBox::critical(this, tr("No wallet.dat"), tr("Couldn't find the wallet.dat on this computer") + "\n" + - // tr("You need to back it up from the machine hushd is running on"), QMessageBox::Ok); - // return; - // } - - // QUrl backupName = QFileDialog::getSaveFileUrl(this, tr("Backup wallet.dat"), backupDefaultName, "Data file (*.dat)"); - // if (backupName.isEmpty()) - // return; - - // if (!wallet.copy(backupName.toLocalFile())) { - // QMessageBox::critical(this, tr("Couldn't backup"), tr("Couldn't backup the wallet.dat file.") + - // tr("You need to back it up manually."), QMessageBox::Ok); - // } - - void MainWindow::exportAllKeys() { exportKeys(""); } void MainWindow::exportKeys(QString addr) { + if (!rpc->getConnection()) + return; + bool allKeys = addr.isEmpty() ? true : false; - QDialog d(this); - Ui_PrivKey pui; - pui.setupUi(&d); - - // Make the window big by default - auto ps = this->geometry(); - QMargins margin = QMargins() + 50; - d.setGeometry(ps.marginsRemoved(margin)); - - Settings::saveRestore(&d); - - pui.privKeyTxt->setPlainText(tr("Loading...")); - pui.privKeyTxt->setReadOnly(true); - pui.privKeyTxt->setLineWrapMode(QPlainTextEdit::LineWrapMode::NoWrap); - - if (allKeys) - pui.helpLbl->setText(tr("These are all the private keys for all the addresses in your wallet")); - else - pui.helpLbl->setText(tr("Private key for ") + addr); - - // Disable the save button until it finishes loading - pui.buttonBox->button(QDialogButtonBox::Save)->setEnabled(false); - pui.buttonBox->button(QDialogButtonBox::Ok)->setVisible(false); - - // Wire up save button - QObject::connect(pui.buttonBox->button(QDialogButtonBox::Save), &QPushButton::clicked, [=] () { - QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), - allKeys ? "hush-all-privatekeys.txt" : "hush-privatekey.txt"); - QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::information(this, tr("Unable to open file"), file.errorString()); - return; - } - QTextStream out(&file); - out << pui.privKeyTxt->toPlainText(); - }); - - // Call the API - auto isDialogAlive = std::make_shared(true); - auto fnUpdateUIWithKeys = [=](json reply) { - // Check to see if we are still showing. - if (! *(isDialogAlive.get()) ) return; + if (isJsonError(reply)) { + return; + } if (reply.is_discarded() || !reply.is_array()) { - pui.privKeyTxt->setPlainText(tr("Error loading private keys")); - pui.buttonBox->button(QDialogButtonBox::Save)->setEnabled(false); - + QMessageBox::critical(this, tr("Error getting private keys"), + tr("Error loading private keys: ") + QString::fromStdString(reply.dump()), + QMessageBox::Ok); return; } + + QDialog d(this); + Ui_PrivKey pui; + pui.setupUi(&d); + // Make the window big by default + auto ps = this->geometry(); + QMargins margin = QMargins() + 50; + d.setGeometry(ps.marginsRemoved(margin)); + + Settings::saveRestore(&d); + + pui.privKeyTxt->setReadOnly(true); + pui.privKeyTxt->setLineWrapMode(QPlainTextEdit::LineWrapMode::NoWrap); + + if (allKeys) + pui.helpLbl->setText(tr("These are all the private keys for all the addresses in your wallet")); + else + pui.helpLbl->setText(tr("Private key for ") + addr); + + + // Wire up save button + QObject::connect(pui.buttonBox->button(QDialogButtonBox::Save), &QPushButton::clicked, [=] () { + QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), + allKeys ? "Hush-all-privatekeys.txt" : "Hush-privatekey.txt"); + QFile file(fileName); + if (!file.open(QIODevice::WriteOnly)) { + QMessageBox::information(this, tr("Unable to open file"), file.errorString()); + return; + } + QTextStream out(&file); + out << pui.privKeyTxt->toPlainText(); + }); + QString allKeysTxt; for (auto i : reply.get()) { allKeysTxt = allKeysTxt % QString::fromStdString(i["private_key"]) % " # addr=" % QString::fromStdString(i["address"]) % "\n"; @@ -725,6 +771,8 @@ void MainWindow::exportKeys(QString addr) { pui.privKeyTxt->setPlainText(allKeysTxt); pui.buttonBox->button(QDialogButtonBox::Save)->setEnabled(true); + + d.exec(); }; if (allKeys) { @@ -732,10 +780,7 @@ void MainWindow::exportKeys(QString addr) { } else { rpc->fetchPrivKey(addr, fnUpdateUIWithKeys); - } - - d.exec(); - *isDialogAlive = false; + } } void MainWindow::setupBalancesTab() { @@ -743,40 +788,6 @@ void MainWindow::setupBalancesTab() { ui->lblSyncWarning->setVisible(false); ui->lblSyncWarningReceive->setVisible(false); - // Double click on balances table - auto fnDoSendFrom = [=](const QString& addr, const QString& to = QString(), bool sendMax = false) { - // Find the inputs combo - for (int i = 0; i < ui->inputsCombo->count(); i++) { - auto inputComboAddress = ui->inputsCombo->itemText(i); - if (inputComboAddress.startsWith(addr)) { - ui->inputsCombo->setCurrentIndex(i); - break; - } - } - - // If there's a to address, add that as well - if (!to.isEmpty()) { - // Remember to clear any existing address fields, because we are creating a new transaction. - this->clearSendForm(); - ui->Address1->setText(to); - } - - // See if max button has to be checked - if (sendMax) { - ui->Max1->setChecked(true); - } - - // And switch to the send tab. - ui->tabWidget->setCurrentIndex(1); - }; - - // Double click opens up memo if one exists - QObject::connect(ui->balancesTable, &QTableView::doubleClicked, [=](auto index) { - index = index.sibling(index.row(), 0); - auto addr = AddressBook::addressFromAddressLabel(ui->balancesTable->model()->data(index).toString()); - - fnDoSendFrom(addr); - }); // Setup context menu on balances tab ui->balancesTable->setContextMenuPolicy(Qt::CustomContextMenu); @@ -800,18 +811,8 @@ void MainWindow::setupBalancesTab() { this->exportKeys(addr); }); - menu.addAction("Send from " % addr.left(40) % (addr.size() > 40 ? "..." : ""), [=]() { - fnDoSendFrom(addr); - }); if (Settings::isTAddress(addr)) { - auto defaultSapling = rpc->getDefaultSaplingAddress(); - if (!defaultSapling.isEmpty()) { - menu.addAction(tr("Shield balance to Sapling"), [=] () { - fnDoSendFrom(addr, defaultSapling, true); - }); - } - menu.addAction(tr("View on block explorer"), [=] () { Settings::openAddressInExplorer(addr); }); @@ -1092,7 +1093,7 @@ void MainWindow::setupReceiveTab() { } ui->rcvLabel->setText(label); - ui->rcvBal->setText(Settings::gethushUSDDisplayFormat(rpc->getModel()->getAllBalances().value(addr))); + ui->rcvBal->setText(rpc->getModel()->getAllBalances().value(addr).toDecimalhushUSDString()); ui->txtReceive->setPlainText(addr); ui->qrcodeDisplay->setQrcodeString(addr); if (rpc->getModel()->getUsedAddresses().value(addr, false)) { @@ -1183,7 +1184,7 @@ void MainWindow::updateTAddrCombo(bool checked) { // If the address is in the address book, add it. if (labels.contains(taddr) && !addrs.contains(taddr)) { addrs.insert(taddr); - ui->listReceiveAddresses->addItem(taddr, 0); + ui->listReceiveAddresses->addItem(taddr, CAmount::fromqint64(0)); } }); @@ -1194,7 +1195,7 @@ void MainWindow::updateTAddrCombo(bool checked) { if (!addrs.contains(addr)) { addrs.insert(addr); // Balance is zero since it has not been previously added - ui->listReceiveAddresses->addItem(addr, 0); + ui->listReceiveAddresses->addItem(addr, CAmount::fromqint64(0)); } } @@ -1211,7 +1212,7 @@ void MainWindow::updateTAddrCombo(bool checked) { // 5. Add a last, disabled item if there are remaining items if (allTaddrs.size() > addrs.size()) { auto num = QString::number(allTaddrs.size() - addrs.size()); - ui->listReceiveAddresses->addItem("-- " + num + " more --", 0); + ui->listReceiveAddresses->addItem("-- " + num + " more --", CAmount::fromqint64(0)); QStandardItemModel* model = qobject_cast(ui->listReceiveAddresses->model()); QStandardItem* item = model->findItems("--", Qt::MatchStartsWith)[0]; @@ -1230,9 +1231,6 @@ void MainWindow::updateLabels() { addZAddrsToComboList(ui->rdioZSAddr->isChecked())(true); } - // Update the Send Tab - updateFromCombo(); - // Update the autocomplete updateLabelsAutoComplete(); } diff --git a/src/mainwindow.h b/src/mainwindow.h index bdb86ef..0af7ad3 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -17,7 +17,7 @@ using json = nlohmann::json; // Struct used to hold destination info when sending a Tx. struct ToFields { QString addr; - double amount; + CAmount amount; QString memo; }; @@ -25,7 +25,7 @@ struct ToFields { struct Tx { QString fromAddr; QList toAddrs; - double fee; + CAmount fee; }; namespace Ui { @@ -47,7 +47,6 @@ public: QRegExpValidator* getAmountValidator() { return amtValidator; } QString doSendTxValidations(Tx tx); - void setDefaultPayFrom(); void replaceWormholeClient(WormholeClient* newClient); bool isWebsocketListening(); @@ -59,7 +58,6 @@ public: void updateLabels(); void updateTAddrCombo(bool checked); - void updateFromCombo(); // Disable recurring on mainnet void disableRecurring(); @@ -98,9 +96,11 @@ private: Tx createTxFromSendPage(); bool confirmTx(Tx tx, RecurringPaymentInfo* rpi); + void encryptWallet(); + void removeWalletEncryption(); + void cancelButton(); void sendButton(); - void inputComboTextChanged(int index); void addAddressSection(); void maxAmountChecked(int checked); @@ -122,7 +122,7 @@ private: void importPrivKey(); void exportAllKeys(); void exportKeys(QString addr = ""); - void backupWalletDat(); + void exportSeed(); void exportTransactions(); void doImport(QList* keys); diff --git a/src/mainwindow.ui b/src/mainwindow.ui index e0e905d..a2dc2c6 100644 --- a/src/mainwindow.ui +++ b/src/mainwindow.ui @@ -6,8 +6,8 @@ 0 0 - 968 - 616 + 1274 + 779 @@ -22,7 +22,7 @@ - 4 + 1 @@ -75,6 +75,37 @@ + + + + + + + 10 + + + + Notarized + + + + + + + + 10 + + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + @@ -148,26 +179,13 @@ - - - - Qt::Vertical - - - - 20 - 40 - - - - color:red; - Your node is still syncing, balances may not be updated + Your node is still syncing, balances may not be updated. true @@ -186,10 +204,26 @@ color: red; - Some transactions are not yet confirmed + Some transactions are not yet confirmed. Balances may change. + + + true + + + + Qt::Vertical + + + + 20 + 40 + + + + @@ -262,65 +296,64 @@ false - From + false - + - - - - - + + + Qt::Horizontal + + + + 40 + 20 + + + - - - - - Address Balance - - - - - - - - 0 - 0 - - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - true - - - - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - + + + + 75 + true + + + + Total notarized funds available: + + + + + + + + + + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + @@ -359,8 +392,8 @@ 0 0 - 920 - 301 + 1226 + 504 @@ -899,6 +932,9 @@ QAbstractItemView::SelectRows + + true + @@ -1051,7 +1087,7 @@ 0 0 - 968 + 1274 22 @@ -1063,7 +1099,7 @@ - + @@ -1093,6 +1129,9 @@ + + + @@ -1120,7 +1159,7 @@ - &Send Duke Feedback + &Send DenioD Feedback @@ -1151,9 +1190,9 @@ Ctrl+B - + - &Backup wallet.dat + &Export seed phrase @@ -1189,6 +1228,16 @@ File a bug... + + + Encrypt Wallet + + + + + Remove Wallet Encryption + + @@ -1210,7 +1259,6 @@ tabWidget - inputsCombo Address1 Amount1 Max1 @@ -1229,7 +1277,6 @@ transactionsTable balancesTable minerFeeAmt - sendAddressBalance sendToScrollArea diff --git a/src/privkey.ui b/src/privkey.ui index 57bdb16..ffdb89c 100644 --- a/src/privkey.ui +++ b/src/privkey.ui @@ -27,7 +27,7 @@ Qt::Horizontal - QDialogButtonBox::Close|QDialogButtonBox::Ok|QDialogButtonBox::Save + QDialogButtonBox::Close|QDialogButtonBox::Save diff --git a/src/recurring.cpp b/src/recurring.cpp index 1550d37..5941e52 100644 --- a/src/recurring.cpp +++ b/src/recurring.cpp @@ -3,6 +3,7 @@ #include "mainwindow.h" #include "controller.h" #include "settings.h" +#include "camount.h" #include "ui_newrecurring.h" #include "ui_recurringdialog.h" #include "ui_recurringpayments.h" @@ -69,7 +70,7 @@ QJsonObject RecurringPaymentInfo::toJson() { {"desc", desc}, {"from", fromAddr}, {"to", toAddr}, - {"amt", Settings::getDecimalString(amt)}, + {"amt", amt}, {"memo", memo}, {"currency", currency}, {"schedule", (int)schedule}, @@ -81,7 +82,8 @@ QJsonObject RecurringPaymentInfo::toJson() { } QString RecurringPaymentInfo::getAmountPretty() const { - return currency == "USD" ? Settings::getUSDFormat(amt) : Settings::gethushDisplayFormat(amt); + CAmount amount = CAmount::fromDouble(amt); + return currency == "USD" ? amount.toDecimalUSDString() : amount.toDecimalhushString(); } QString RecurringPaymentInfo::getScheduleDescription() const { @@ -135,7 +137,7 @@ RecurringPaymentInfo* Recurring::getNewRecurringFromTx(QWidget* parent, MainWind ui.lblTo->setText(tx.toAddrs[0].addr); // Default is USD - ui.lblAmt->setText(Settings::getUSDFormat(tx.toAddrs[0].amount)); + ui.lblAmt->setText(tx.toAddrs[0].amount.toDecimalUSDString()); ui.txtMemo->setPlainText(tx.toAddrs[0].memo); ui.txtMemo->setEnabled(false); @@ -147,10 +149,10 @@ RecurringPaymentInfo* Recurring::getNewRecurringFromTx(QWidget* parent, MainWind return; if (c == "USD") { - ui.lblAmt->setText(Settings::getUSDFormat(tx.toAddrs[0].amount)); + ui.lblAmt->setText(tx.toAddrs[0].amount.toDecimalUSDString()); } else { - ui.lblAmt->setText(Settings::getDecimalString(tx.toAddrs[0].amount)); + ui.lblAmt->setText(tx.toAddrs[0].amount.toDecimalString()); } }); @@ -201,13 +203,13 @@ void Recurring::updateInfoWithTx(RecurringPaymentInfo* r, Tx tx) { r->toAddr = tx.toAddrs[0].addr; r->memo = tx.toAddrs[0].memo; r->fromAddr = tx.fromAddr; - if (r->currency.isEmpty() || r->currency == "usd") { - r->currency = "usd"; - r->amt = tx.toAddrs[0].amount * Settings::getInstance()->gethushPrice(); + if (r->currency.isEmpty() || r->currency == "USD") { + r->currency = "USD"; + r->amt = tx.toAddrs[0].amount.toqint64() * Settings::getInstance()->getZECPrice(); } else { r->currency = Settings::getTokenName(); - r->amt = tx.toAddrs[0].amount; + r->amt = tx.toAddrs[0].amount.toqint64(); } // Make sure that the number of payments is properly listed in the array @@ -459,11 +461,11 @@ void Recurring::processMultiplePending(RecurringPaymentInfo rpi, MainWindow* mai } void Recurring::executeRecurringPayment(MainWindow* main, RecurringPaymentInfo rpi, QList paymentNumbers) { - // Amount is in USD or hush? - auto amt = rpi.amt; - if (rpi.currency == "usd") { + // Amount is in USD or Hush? + double amount = rpi.amt; + if (rpi.currency == "USD") { // If there is no price, then fail the payment - if (Settings::getInstance()->gethushPrice() == 0) { + if (Settings::getInstance()->getZECPrice() == 0) { for (auto paymentNumber: paymentNumbers) { updatePaymentItem(rpi.getHash(), paymentNumber, "", QObject::tr("No hush price was available to convert from USD"), @@ -473,7 +475,7 @@ void Recurring::executeRecurringPayment(MainWindow* main, RecurringPaymentInfo r } // Translate it into hush - amt = rpi.amt / Settings::getInstance()->gethushPrice(); + amount = rpi.amt / Settings::getInstance()->getZECPrice(); } // Build a Tx @@ -483,9 +485,9 @@ void Recurring::executeRecurringPayment(MainWindow* main, RecurringPaymentInfo r // If this is a multiple payment, we'll add up all the amounts if (paymentNumbers.size() > 1) - amt *= paymentNumbers.size(); + amount *= paymentNumbers.size(); - tx.toAddrs.append(ToFields { rpi.toAddr, amt, rpi.memo }); + tx.toAddrs.append(ToFields { rpi.toAddr, CAmount::fromDouble(amount), rpi.memo }); // To prevent some weird race conditions, we immediately mark the payment as paid. // If something goes wrong, we'll get the error callback below, and the status will be diff --git a/src/requestdialog.cpp b/src/requestdialog.cpp index 5a32155..d63de4d 100644 --- a/src/requestdialog.cpp +++ b/src/requestdialog.cpp @@ -73,7 +73,8 @@ void RequestDialog::showPaymentConfirmation(MainWindow* main, QString paymentURI req.txtFrom->setText(payInfo.addr); req.txtMemo->setPlainText(payInfo.memo); req.txtAmount->setText(payInfo.amt); - req.txtAmountUSD->setText(Settings::getUSDFormat(req.txtAmount->text().toDouble())); + CAmount amount = CAmount::fromDecimalString(req.txtAmount->text()); + req.txtAmountUSD->setText(amount.toDecimalUSDString()); req.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Pay")); @@ -112,9 +113,11 @@ void RequestDialog::showRequesthush(MainWindow* main) { // Amount textbox req.txtAmount->setValidator(main->getAmountValidator()); QObject::connect(req.txtAmount, &QLineEdit::textChanged, [=] (auto text) { - req.txtAmountUSD->setText(Settings::getUSDFormat(text.toDouble())); + CAmount amount = CAmount::fromDecimalString(text); + req.txtAmountUSD->setText(amount.toDecimalUSDString()); }); - req.txtAmountUSD->setText(Settings::getUSDFormat(req.txtAmount->text().toDouble())); + CAmount amount = CAmount::fromDecimalString(req.txtAmount->text()); + req.txtAmountUSD->setText(amount.toDecimalUSDString()); req.txtMemo->setAcceptButton(req.buttonBox->button(QDialogButtonBox::Ok)); req.txtMemo->setLenDisplayLabel(req.lblMemoLen); @@ -124,8 +127,9 @@ void RequestDialog::showRequesthush(MainWindow* main) { if (d.exec() == QDialog::Accepted) { // Construct a hush Payment URI with the data and pay it immediately. + CAmount amount = CAmount::fromDecimalString(req.txtAmount->text()); QString memoURI = "hush:" + req.cmbMyAddress->currentText() - + "?amt=" + Settings::getDecimalString(req.txtAmount->text().toDouble()) + + "?amt=" + amount.toDecimalString() + "&memo=" + QUrl::toPercentEncoding(req.txtMemo->toPlainText()); QString sendURI = "hush:" + AddressBook::addressFromAddressLabel(req.txtFrom->text()) diff --git a/src/scripts/desktopentry b/src/scripts/desktopentry index 4a18661..6fe326b 100644 --- a/src/scripts/desktopentry +++ b/src/scripts/desktopentry @@ -1,13 +1,13 @@ [Desktop Entry] -Name=silentdragon -Comment=Full node and wallet for hush +Name=SilentDragonLite +Comment=Lightclient UI wallet for Hush GenericName=Wallet -Exec=/usr/local/bin/silentdragon %u -Icon=silentdragon.xpm +Exec=/usr/local/bin/silentdragonlite %u +Icon=silentdragonlite.xpm Type=Application StartupNotify=true -StartupWMClass=silentdragon +StartupWMClass=silentdragonlite Categories=Utility; MimeType=x-scheme-handler/hush; -Keywords=silentdragon; +Keywords=silentdragonlite; diff --git a/src/scripts/dotranslations.sh b/src/scripts/dotranslations.sh index 70ff51c..7cefb8d 100755 --- a/src/scripts/dotranslations.sh +++ b/src/scripts/dotranslations.sh @@ -6,7 +6,7 @@ if [ -z $QT_STATIC ]; then fi rm -f res/*.qm -$QT_STATIC/bin/lrelease silentdragonlite.pro +$QT_STATIC/bin/lrelease silentdragon-lite.pro # Then update the qt base translations. First, get all languages ls res/*.qm | awk -F '[_.]' '{print $4}' | while read -r language ; do diff --git a/src/scripts/mkmacdmg.sh b/src/scripts/mkmacdmg.sh index efdfe1e..a9d8799 100755 --- a/src/scripts/mkmacdmg.sh +++ b/src/scripts/mkmacdmg.sh @@ -35,21 +35,11 @@ if [ -z $QT_PATH ]; then exit 1; fi -if [ -z $hush_DIR ]; then - echo "hush_DIR is not set. Please set it to the base directory of a compiled hushd"; - exit 1; -fi - if [ -z $APP_VERSION ]; then echo "APP_VERSION is not set. Please set it to the current release version of the app"; exit 1; fi -if [ ! -f $hush_DIR/src/hushd ]; then - echo "Could not find compiled hushd in $hush_DIR/src/."; - exit 1; -fi - if ! cat src/version.h | grep -q "$APP_VERSION"; then echo "Version mismatch in src/version.h" exit 1 @@ -60,14 +50,14 @@ export PATH=$PATH:/usr/local/bin #Clean echo -n "Cleaning..............." make distclean >/dev/null 2>&1 -rm -f artifacts/macOS-silentdragon-v$APP_VERSION.dmg +rm -f artifacts/macOS-silentdragonlite-v$APP_VERSION.dmg echo "[OK]" echo -n "Configuring............" # Build QT_STATIC=$QT_PATH src/scripts/dotranslations.sh >/dev/null -$QT_PATH/bin/qmake silentdragonlite.pro CONFIG+=release >/dev/null +$QT_PATH/bin/qmake silentdragon-lite.pro CONFIG+=release >/dev/null echo "[OK]" @@ -78,27 +68,17 @@ echo "[OK]" #Qt deploy echo -n "Deploying.............." mkdir artifacts >/dev/null 2>&1 -rm -f artifcats/silentdragon.dmg >/dev/null 2>&1 +rm -f artifcats/Silentdragonlite.dmg >/dev/null 2>&1 rm -f artifacts/rw* >/dev/null 2>&1 -cp $hush_DIR/src/hushd silentdragon.app/Contents/MacOS/ -cp $hush_DIR/src/hush-cli silentdragon.app/Contents/MacOS/ -$QT_PATH/bin/macdeployqt silentdragon.app +$QT_PATH/bin/macdeployqt Silentdragonlite.app echo "[OK]" echo -n "Building dmg..........." -mv silentdragon.app silentdragon.app -create-dmg --volname "silentdragon-v$APP_VERSION" --volicon "res/logo.icns" --window-pos 200 120 --icon "silentdragon.app" 200 190 --app-drop-link 600 185 --hide-extension "silentdragon.app" --window-size 800 400 --hdiutil-quiet --background res/dmgbg.png artifacts/macOS-silentdragon-v$APP_VERSION.dmg silentdragon.app >/dev/null 2>&1 +mv silentdragonlite.app Silentdragonlite.app +create-dmg --volname "SilentDragonLite-v$APP_VERSION" --volicon "res/logo.icns" --window-pos 200 120 --icon "SilentDragonLite.app" 200 190 --app-drop-link 600 185 --hide-extension "SilentDragonLite.app" --window-size 800 400 --hdiutil-quiet --background res/dmgbg.png artifacts/macOS-SilentDragonLite-v$APP_VERSION.dmg SilentDragonLite.app >/dev/null 2>&1 -#mkdir bin/dmgbuild >/dev/null 2>&1 -#sed "s/RELEASE_VERSION/${APP_VERSION}/g" res/appdmg.json > bin/dmgbuild/appdmg.json -#cp res/logo.icns bin/dmgbuild/ -#cp res/dmgbg.png bin/dmgbuild/ - -#cp -r silentdragon.app bin/dmgbuild/ - -#appdmg --quiet bin/dmgbuild/appdmg.json artifacts/macOS-silentdragon-v$APP_VERSION.dmg >/dev/null -if [ ! -f artifacts/macOS-silentdragon-v$APP_VERSION.dmg ]; then +if [ ! -f artifacts/macOS-SilentDragonLite-v$APP_VERSION.dmg ]; then echo "[ERROR]" exit 1 fi diff --git a/src/scripts/mkrelease.sh b/src/scripts/mkrelease.sh index 1cbe960..9820673 100755 --- a/src/scripts/mkrelease.sh +++ b/src/scripts/mkrelease.sh @@ -7,43 +7,9 @@ fi if [ -z $APP_VERSION ]; then echo "APP_VERSION is not set"; exit 1; fi if [ -z $PREV_VERSION ]; then echo "PREV_VERSION is not set"; exit 1; fi -if [ -z $hush_DIR ]; then - echo "hush_DIR is not set. Please set it to the base directory of a hush project with built hush binaries." - exit 1; -fi - -if [ ! -f $hush_DIR/artifacts/hushd ]; then - echo "Couldn't find hushd in $hush_DIR/artifacts/. Please build hushd." - exit 1; -fi - -if [ ! -f $hush_DIR/artifacts/hush-cli ]; then - echo "Couldn't find hush-cli in $hush_DIR/artifacts/. Please build hushd." - exit 1; -fi - -# Ensure that hushd is the right build -echo -n "hushd version........." -if grep -q "zqwMagicBean" $hush_DIR/artifacts/hushd && ! readelf -s $hush_DIR/artifacts/hushd | grep -q "GLIBC_2\.25"; then - echo "[OK]" -else - echo "[ERROR]" - echo "hushd doesn't seem to be a zqwMagicBean build or hushd is built with libc 2.25" - exit 1 -fi - -echo -n "hushd.exe version....." -if grep -q "zqwMagicBean" $hush_DIR/artifacts/hushd.exe; then - echo "[OK]" -else - echo "[ERROR]" - echo "hushd doesn't seem to be a zqwMagicBean build" - exit 1 -fi - echo -n "Version files.........." # Replace the version number in the .pro file so it gets picked up everywhere -sed -i "s/${PREV_VERSION}/${APP_VERSION}/g" silentdragonlite.pro > /dev/null +sed -i "s/${PREV_VERSION}/${APP_VERSION}/g" silentdragon-lite.pro > /dev/null # Also update it in the README.md sed -i "s/${PREV_VERSION}/${APP_VERSION}/g" README.md > /dev/null @@ -60,21 +26,21 @@ echo "[Building on" `lsb_release -r`"]" echo -n "Configuring............" QT_STATIC=$QT_STATIC bash src/scripts/dotranslations.sh >/dev/null -$QT_STATIC/bin/qmake silentdragonlite.pro -spec linux-clang CONFIG+=release > /dev/null +$QT_STATIC/bin/qmake silentdragon-lite.pro -spec linux-clang CONFIG+=release > /dev/null echo "[OK]" echo -n "Building..............." rm -rf bin/silentdragonlite* > /dev/null -rm -rf bin/silentdragon* > /dev/null -make clean > /dev/null +# Build the lib first +cd lib && make release && cd .. make -j$(nproc) > /dev/null echo "[OK]" # Test for Qt echo -n "Static link............" -if [[ $(ldd silentdragon | grep -i "Qt") ]]; then +if [[ $(ldd silentdragonlite | grep -i "Qt") ]]; then echo "FOUND QT; ABORT"; exit 1 fi @@ -82,27 +48,25 @@ echo "[OK]" echo -n "Packaging.............." -mkdir bin/silentdragon-v$APP_VERSION > /dev/null -strip silentdragon +mkdir bin/silentdragonlite-v$APP_VERSION > /dev/null +strip silentdragonlite -cp silentdragon bin/silentdragon-v$APP_VERSION > /dev/null -cp $hush_DIR/artifacts/hushd bin/silentdragon-v$APP_VERSION > /dev/null -cp $hush_DIR/artifacts/hush-cli bin/silentdragon-v$APP_VERSION > /dev/null -cp README.md bin/silentdragon-v$APP_VERSION > /dev/null -cp LICENSE bin/silentdragon-v$APP_VERSION > /dev/null +cp silentdragonlite bin/silentdragonlite-v$APP_VERSION > /dev/null +cp README.md bin/silentdragonlite-v$APP_VERSION > /dev/null +cp LICENSE bin/silentdragonlite-v$APP_VERSION > /dev/null -cd bin && tar czf linux-silentdragon-v$APP_VERSION.tar.gz silentdragon-v$APP_VERSION/ > /dev/null +cd bin && tar czf linux-silentdragonlite-v$APP_VERSION.tar.gz silentdragonlite-v$APP_VERSION/ > /dev/null cd .. mkdir artifacts >/dev/null 2>&1 -cp bin/linux-silentdragon-v$APP_VERSION.tar.gz ./artifacts/linux-binaries-silentdragon-v$APP_VERSION.tar.gz +cp bin/linux-silentdragonlite-v$APP_VERSION.tar.gz ./artifacts/linux-binaries-silentdragonlite-v$APP_VERSION.tar.gz echo "[OK]" -if [ -f artifacts/linux-binaries-silentdragon-v$APP_VERSION.tar.gz ] ; then +if [ -f artifacts/linux-binaries-silentdragonlite-v$APP_VERSION.tar.gz ] ; then echo -n "Package contents......." # Test if the package is built OK - if tar tf "artifacts/linux-binaries-silentdragon-v$APP_VERSION.tar.gz" | wc -l | grep -q "6"; then + if tar tf "artifacts/linux-binaries-silentdragonlite-v$APP_VERSION.tar.gz" | wc -l | grep -q "4"; then echo "[OK]" else echo "[ERROR]" @@ -114,24 +78,23 @@ else fi echo -n "Building deb..........." -debdir=bin/deb/silentdragon-v$APP_VERSION +debdir=bin/deb/silentdragonlite-v$APP_VERSION mkdir -p $debdir > /dev/null mkdir $debdir/DEBIAN mkdir -p $debdir/usr/local/bin cat src/scripts/control | sed "s/RELEASE_VERSION/$APP_VERSION/g" > $debdir/DEBIAN/control -cp silentdragon $debdir/usr/local/bin/ -cp $hush_DIR/artifacts/hushd $debdir/usr/local/bin/zqw-hushd +cp silentdragonlite $debdir/usr/local/bin/ mkdir -p $debdir/usr/share/pixmaps/ -cp res/silentdragon.xpm $debdir/usr/share/pixmaps/ +cp res/silentdragonlite.xpm $debdir/usr/share/pixmaps/ mkdir -p $debdir/usr/share/applications cp src/scripts/desktopentry $debdir/usr/share/applications/silentdragonlite.desktop dpkg-deb --build $debdir >/dev/null -cp $debdir.deb artifacts/linux-deb-silentdragon-v$APP_VERSION.deb +cp $debdir.deb artifacts/linux-deb-silentdragonlite-v$APP_VERSION.deb echo "[OK]" @@ -145,51 +108,40 @@ if [ -z $MXE_PATH ]; then exit 0; fi -if [ ! -f $hush_DIR/artifacts/hushd.exe ]; then - echo "Couldn't find hushd.exe in $hush_DIR/artifacts/. Please build hushd.exe" - exit 1; -fi - - -if [ ! -f $hush_DIR/artifacts/hush-cli.exe ]; then - echo "Couldn't find hush-cli.exe in $hush_DIR/artifacts/. Please build hushd.exe" - exit 1; -fi - export PATH=$MXE_PATH:$PATH echo -n "Configuring............" make clean > /dev/null -rm -f silentdragonlite-mingw.pro +#rm -f silentdragonlite-mingw.pro rm -rf release/ #Mingw seems to have trouble with precompiled headers, so strip that option from the .pro file -cat silentdragonlite.pro | sed "s/precompile_header/release/g" | sed "s/PRECOMPILED_HEADER.*//g" > silentdragonlite-mingw.pro +#cat silentdragon-lite.pro | sed "s/precompile_header/release/g" | sed "s/PRECOMPILED_HEADER.*//g" > silentdragonlite-mingw.pro echo "[OK]" echo -n "Building..............." -x86_64-w64-mingw32.static-qmake-qt5 silentdragonlite-mingw.pro CONFIG+=release > /dev/null +# Build the lib first +cd lib && make winrelease && cd .. +x86_64-w64-mingw32.static-qmake-qt5 silentdragonlite.pro CONFIG+=release > /dev/null make -j32 > /dev/null echo "[OK]" echo -n "Packaging.............." -mkdir release/silentdragon-v$APP_VERSION -cp release/silentdragon.exe release/silentdragon-v$APP_VERSION -cp $hush_DIR/artifacts/hushd.exe release/silentdragon-v$APP_VERSION > /dev/null -cp $hush_DIR/artifacts/hush-cli.exe release/silentdragon-v$APP_VERSION > /dev/null -cp README.md release/silentdragon-v$APP_VERSION -cp LICENSE release/silentdragon-v$APP_VERSION -cd release && zip -r Windows-binaries-silentdragon-v$APP_VERSION.zip silentdragon-v$APP_VERSION/ > /dev/null +mkdir release/silentdragonlite-v$APP_VERSION +cp release/silentdragonlite.exe release/silentdragonlite-v$APP_VERSION +cp README.md release/silentdragonlite-v$APP_VERSION +cp LICENSE release/silentdragonlite-v$APP_VERSION +cd release && zip -r Windows-binaries-silentdragonlite-v$APP_VERSION.zip silentdragonlite-v$APP_VERSION/ > /dev/null cd .. mkdir artifacts >/dev/null 2>&1 -cp release/Windows-binaries-silentdragon-v$APP_VERSION.zip ./artifacts/ +cp release/Windows-binaries-silentdragonlite-v$APP_VERSION.zip ./artifacts/ echo "[OK]" -if [ -f artifacts/Windows-binaries-silentdragon-v$APP_VERSION.zip ] ; then +if [ -f artifacts/Windows-binaries-silentdragonlite-v$APP_VERSION.zip ] ; then echo -n "Package contents......." - if unzip -l "artifacts/Windows-binaries-silentdragon-v$APP_VERSION.zip" | wc -l | grep -q "11"; then + if unzip -l "artifacts/Windows-binaries-silentdragonlite-v$APP_VERSION.zip" | wc -l | grep -q "9"; then echo "[OK]" else echo "[ERROR]" diff --git a/src/sendtab.cpp b/src/sendtab.cpp index 7f8d809..f9b3e9f 100644 --- a/src/sendtab.cpp +++ b/src/sendtab.cpp @@ -22,10 +22,6 @@ void MainWindow::setupSendTab() { // Cancel Button QObject::connect(ui->cancelSendButton, &QPushButton::clicked, this, &MainWindow::cancelButton); - // Input Combobox current text changed - QObject::connect(ui->inputsCombo, QOverload::of(&QComboBox::currentIndexChanged), - this, &MainWindow::inputComboTextChanged); - // Hook up add address button click QObject::connect(ui->addAddressButton, &QPushButton::clicked, this, &MainWindow::addAddressSection); @@ -59,18 +55,19 @@ void MainWindow::setupSendTab() { }); // Fee amount changed - // Disable custom fees if settings say no - ui->minerFeeAmt->setReadOnly(!Settings::getInstance()->getAllowCustomFees()); + ui->minerFeeAmt->setReadOnly(true); QObject::connect(ui->minerFeeAmt, &QLineEdit::textChanged, [=](auto txt) { - ui->lblMinerFeeUSD->setText(Settings::getUSDFormat(txt.toDouble())); + CAmount fee = CAmount::fromDecimalString(txt); + ui->lblMinerFeeUSD->setText(fee.toDecimalUSDString()); }); - ui->minerFeeAmt->setText(Settings::getDecimalString(Settings::getMinerFee())); + ui->minerFeeAmt->setText(Settings::getMinerFee().toDecimalString()); // Set up focus enter to set fees QObject::connect(ui->tabWidget, &QTabWidget::currentChanged, [=] (int pos) { if (pos == 1) { QString txt = ui->minerFeeAmt->text(); - ui->lblMinerFeeUSD->setText(Settings::getUSDFormat(txt.toDouble())); + QString feeUSD = CAmount::fromDecimalString(txt).toDecimalUSDString(); + ui->lblMinerFeeUSD->setText(feeUSD); } }); @@ -167,70 +164,6 @@ void MainWindow::updateLabelsAutoComplete() { } } -void MainWindow::setDefaultPayFrom() { - auto findMax = [=] (QString startsWith) { - double max_amt = 0; - int idx = -1; - - for (int i=0; i < ui->inputsCombo->count(); i++) { - auto addr = ui->inputsCombo->itemText(i); - if (addr.startsWith(startsWith)) { - auto amt = rpc->getModel()->getAllBalances().value(addr); - if (max_amt < amt) { - max_amt = amt; - idx = i; - } - } - } - - return idx; - }; - - // By default, select the z-address with the most balance from the inputs combo - auto maxZ = findMax("zs1"); - if (maxZ >= 0) { - ui->inputsCombo->setCurrentIndex(maxZ); - } else { - auto maxT = findMax("R"); - maxT = maxT >= 0 ? maxT : 0; - ui->inputsCombo->setCurrentIndex(maxT); - } -}; - -void MainWindow::updateFromCombo() { - if (!rpc) - return; - - auto lastFromAddr = ui->inputsCombo->currentText(); - - ui->inputsCombo->clear(); - auto i = rpc->getModel()->getAllBalances().constBegin(); - - // Add all the addresses into the inputs combo box - while (i != rpc->getModel()->getAllBalances().constEnd()) { - ui->inputsCombo->addItem(i.key(), i.value()); - if (i.key() == lastFromAddr) ui->inputsCombo->setCurrentText(i.key()); - - ++i; - } - - if (lastFromAddr.isEmpty()) { - setDefaultPayFrom(); - } - else { - ui->inputsCombo->setCurrentText(lastFromAddr); - } -} - -void MainWindow::inputComboTextChanged(int index) { - auto addr = ui->inputsCombo->itemText(index); - auto bal = rpc->getModel()->getAllBalances().value(addr); - auto balFmt = Settings::gethushDisplayFormat(bal); - - ui->sendAddressBalance->setText(balFmt); - ui->sendAddressBalanceUSD->setText(Settings::getUSDFormat(bal)); -} - void MainWindow::addAddressSection() { int itemNumber = ui->sendToWidgets->children().size() - 1; @@ -341,7 +274,8 @@ void MainWindow::addressChanged(int itemNumber, const QString& text) { void MainWindow::amountChanged(int item, const QString& text) { auto usd = ui->sendToWidgets->findChild(QString("AmtUSD") % QString::number(item)); - usd->setText(Settings::getUSDFormat(text.toDouble())); + CAmount amt = CAmount::fromDecimalString(text); + usd->setText(amt.toDecimalUSDString()); // If there is a recurring payment, update the info there as well if (sendTxRecurringInfo != nullptr) { @@ -386,12 +320,9 @@ void MainWindow::memoButtonClicked(int number, bool includeReplyTo) { memoDialog.memoTxt->setAcceptButton(memoDialog.buttonBox->button(QDialogButtonBox::Ok)); auto fnAddReplyTo = [=, &dialog]() { - QString replyTo = ui->inputsCombo->currentText(); - if (!Settings::isZAddress(replyTo)) { - replyTo = rpc->getDefaultSaplingAddress(); - if (replyTo.isEmpty()) - return; - } + auto replyTo = rpc->getDefaultSaplingAddress(); + if (replyTo.isEmpty()) + return; memoDialog.memoTxt->includeReplyTo(replyTo); @@ -435,7 +366,7 @@ void MainWindow::clearSendForm() { setMemoEnabled(1, false); // Reset the fee - ui->minerFeeAmt->setText(Settings::getDecimalString(Settings::getMinerFee())); + ui->minerFeeAmt->setText(Settings::getMinerFee().toDecimalString()); // Start the deletion after the first item, since we want to keep 1 send field there all there for (int i=1; i < totalItems; i++) { @@ -462,29 +393,22 @@ void MainWindow::maxAmountChecked(int checked) { if (rpc == nullptr) return; // Calculate maximum amount - double sumAllAmounts = 0.0; + CAmount sumAllAmounts; // Calculate all other amounts int totalItems = ui->sendToWidgets->children().size() - 2; // The last one is a spacer, so ignore that // Start counting the sum skipping the first one, because the MAX button is on the first one, and we don't // want to include it in the sum. for (int i=1; i < totalItems; i++) { auto amt = ui->sendToWidgets->findChild(QString("Amount") % QString::number(i+1)); - sumAllAmounts += amt->text().toDouble(); + sumAllAmounts = sumAllAmounts + CAmount::fromDecimalString(amt->text()); } - if (Settings::getInstance()->getAllowCustomFees()) { - sumAllAmounts = ui->minerFeeAmt->text().toDouble(); - } - else { - sumAllAmounts += Settings::getMinerFee(); - } - - auto addr = ui->inputsCombo->currentText(); - - auto maxamount = rpc->getModel()->getAllBalances().value(addr) - sumAllAmounts; - maxamount = (maxamount < 0) ? 0 : maxamount; + sumAllAmounts = sumAllAmounts + Settings::getMinerFee(); + + auto maxamount = rpc->getModel()->getAvailableBalance() - sumAllAmounts; + maxamount = (maxamount < 0) ? CAmount::fromqint64(0): maxamount; - ui->Amount1->setText(Settings::getDecimalString(maxamount)); + ui->Amount1->setText(maxamount.toDecimalString()); } else if (checked == Qt::Unchecked) { // Just remove the readonly part, don't change the content ui->Amount1->setReadOnly(false); @@ -495,60 +419,37 @@ void MainWindow::maxAmountChecked(int checked) { Tx MainWindow::createTxFromSendPage() { Tx tx; - bool sendChangeToSapling = Settings::getInstance()->getAutoShield(); - - // Gather the from / to addresses - tx.fromAddr = ui->inputsCombo->currentText(); - sendChangeToSapling = sendChangeToSapling && Settings::isTAddress(tx.fromAddr); - // For each addr/amt in the sendTo tab int totalItems = ui->sendToWidgets->children().size() - 2; // The last one is a spacer, so ignore that - double totalAmt = 0; + CAmount totalAmt; for (int i=0; i < totalItems; i++) { QString addr = ui->sendToWidgets->findChild(QString("Address") % QString::number(i+1))->text().trimmed(); // Remove label if it exists addr = AddressBook::addressFromAddressLabel(addr); - // If address is sprout, then we can't send change to sapling, because of turnstile. - sendChangeToSapling = sendChangeToSapling && !Settings::getInstance()->isSproutAddress(addr); - double amt = ui->sendToWidgets->findChild(QString("Amount") % QString::number(i+1))->text().trimmed().toDouble(); - totalAmt += amt; + QString amtStr = ui->sendToWidgets->findChild(QString("Amount") % QString::number(i+1))->text().trimmed(); + if (amtStr.isEmpty()) { + amtStr = "-1";; // The user didn't specify an amount + } + + bool ok; + CAmount amt; + + // Make sure it parses + amtStr.toDouble(&ok); + if (!ok) { + amt = CAmount::fromqint64(-1); + } else { + amt = CAmount::fromDecimalString(amtStr); + totalAmt = totalAmt + amt; + } + QString memo = ui->sendToWidgets->findChild(QString("MemoTxt") % QString::number(i+1))->text().trimmed(); tx.toAddrs.push_back( ToFields{addr, amt, memo,} ); } - if (Settings::getInstance()->getAllowCustomFees()) { - tx.fee = ui->minerFeeAmt->text().toDouble(); - } - else { - tx.fee = Settings::getMinerFee(); - } - - if (Settings::getInstance()->getAutoShield() && sendChangeToSapling) { - auto saplingAddr = std::find_if(rpc->getModel()->getAllZAddresses().begin(), rpc->getModel()->getAllZAddresses().end(), [=](auto i) -> bool { - // We're finding a sapling address that is not one of the To addresses, because hush doesn't allow duplicated addresses - bool isSapling = Settings::getInstance()->isSaplingAddress(i); - if (!isSapling) return false; - - // Also check all the To addresses - for (auto t : tx.toAddrs) { - if (t.addr == i) - return false; - } - - return true; - }); - - if (saplingAddr != rpc->getModel()->getAllZAddresses().end()) { - double change = rpc->getModel()->getAllBalances().value(tx.fromAddr) - totalAmt - tx.fee; - - if (Settings::getDecimalString(change) != "0") { - QString changeMemo = tr("Change from ") + tx.fromAddr; - tx.toAddrs.push_back(ToFields{ *saplingAddr, change, changeMemo}); - } - } - } + tx.fee = Settings::getMinerFee(); return tx; } @@ -588,8 +489,6 @@ bool MainWindow::confirmTx(Tx tx, RecurringPaymentInfo* rpi) { confirm.setupUi(&d); Settings::saveRestore(&d); - const QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); - // Remove all existing address/amt qlabels on the confirm dialog. int totalConfirmAddrItems = confirm.sendToAddrs->children().size(); for (int i = 0; i < totalConfirmAddrItems / 3; i++) { @@ -613,7 +512,7 @@ bool MainWindow::confirmTx(Tx tx, RecurringPaymentInfo* rpi) { // For each addr/amt/memo, construct the JSON and also build the confirm dialog box int row = 0; - double totalSpending = 0; + CAmount totalSpending; for (int i=0; i < tx.toAddrs.size(); i++) { auto toAddr = tx.toAddrs[i]; @@ -625,21 +524,20 @@ bool MainWindow::confirmTx(Tx tx, RecurringPaymentInfo* rpi) { Addr->setObjectName(QString("Addr") % QString::number(i + 1)); Addr->setWordWrap(true); Addr->setText(fnSplitAddressForWrap(toAddr.addr)); - Addr->setFont(fixedFont); confirm.gridLayout->addWidget(Addr, row, 0, 1, 1); // Amount (hush) auto Amt = new QLabel(confirm.sendToAddrs); Amt->setObjectName(QString("Amt") % QString::number(i + 1)); - Amt->setText(Settings::gethushDisplayFormat(toAddr.amount)); + Amt->setText(toAddr.amount.toDecimalhushString()); Amt->setAlignment(Qt::AlignRight | Qt::AlignTrailing | Qt::AlignVCenter); confirm.gridLayout->addWidget(Amt, row, 1, 1, 1); - totalSpending += toAddr.amount; + totalSpending = totalSpending + toAddr.amount; // Amount (USD) auto AmtUSD = new QLabel(confirm.sendToAddrs); AmtUSD->setObjectName(QString("AmtUSD") % QString::number(i + 1)); - AmtUSD->setText(Settings::getUSDFormat(toAddr.amount)); + AmtUSD->setText(toAddr.amount.toDecimalUSDString()); AmtUSD->setAlignment(Qt::AlignRight | Qt::AlignTrailing | Qt::AlignVCenter); confirm.gridLayout->addWidget(AmtUSD, row, 2, 1, 1); @@ -681,8 +579,8 @@ bool MainWindow::confirmTx(Tx tx, RecurringPaymentInfo* rpi) { minerFee->setObjectName(QStringLiteral("minerFee")); minerFee->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); confirm.gridLayout->addWidget(minerFee, row, 1, 1, 1); - minerFee->setText(Settings::gethushDisplayFormat(tx.fee)); - totalSpending += tx.fee; + minerFee->setText(tx.fee.toDecimalhushString()); + totalSpending = totalSpending + tx.fee; auto minerFeeUSD = new QLabel(confirm.sendToAddrs); QSizePolicy sizePolicy1(QSizePolicy::Minimum, QSizePolicy::Preferred); @@ -690,14 +588,7 @@ bool MainWindow::confirmTx(Tx tx, RecurringPaymentInfo* rpi) { minerFeeUSD->setObjectName(QStringLiteral("minerFeeUSD")); minerFeeUSD->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); confirm.gridLayout->addWidget(minerFeeUSD, row, 2, 1, 1); - minerFeeUSD->setText(Settings::getUSDFormat(tx.fee)); - - if (Settings::getInstance()->getAllowCustomFees() && tx.fee != Settings::getMinerFee()) { - confirm.warningLabel->setVisible(true); - } else { - // Default fee - confirm.warningLabel->setVisible(false); - } + minerFeeUSD->setText(tx.fee.toDecimalUSDString()); } // Recurring payment info, show only if there is exactly one destination address @@ -712,17 +603,7 @@ bool MainWindow::confirmTx(Tx tx, RecurringPaymentInfo* rpi) { // Syncing warning confirm.syncingWarning->setVisible(Settings::getInstance()->isSyncing()); - // No peers warning - confirm.nopeersWarning->setVisible(Settings::getInstance()->getPeers() == 0); - - // And FromAddress in the confirm dialog - confirm.sendFrom->setText(fnSplitAddressForWrap(tx.fromAddr)); - confirm.sendFrom->setFont(fixedFont); - QString tooltip = tr("Current balance : ") + - Settings::gethushUSDDisplayFormat(rpc->getModel()->getAllBalances().value(tx.fromAddr)); - tooltip += "\n" + tr("Balance after this Tx: ") + - Settings::gethushUSDDisplayFormat(rpc->getModel()->getAllBalances().value(tx.fromAddr) - totalSpending); - confirm.sendFrom->setToolTip(tooltip); + // Show the dialog and submit it if the user confirms return d.exec() == QDialog::Accepted; @@ -735,6 +616,7 @@ void MainWindow::sendButton() { Tx tx = createTxFromSendPage(); QString error = doSendTxValidations(tx); + if (!error.isEmpty()) { // Something went wrong, so show an error and exit QMessageBox msg(QMessageBox::Critical, tr("Transaction Error"), error, @@ -762,11 +644,39 @@ void MainWindow::sendButton() { // Then delete the additional fields from the sendTo tab clearSendForm(); + // Create a new Dialog to show that we are computing/sending the Tx + auto d = new QDialog(this); + auto connD = new Ui_ConnectionDialog(); + connD->setupUi(d); + QPixmap logo(":/img/res/logobig.gif"); + connD->topIcon->setBasePixmap(logo.scaled(256, 256, Qt::KeepAspectRatio, Qt::SmoothTransformation)); + + connD->status->setText(tr("Please wait...")); + connD->statusDetail->setText(tr("Computing your transaction")); + + d->show(); + // And send the Tx rpc->executeTransaction(tx, [=] (QString txid) { ui->statusBar->showMessage(Settings::txidStatusMessage + " " + txid); + connD->status->setText(tr("Done!")); + connD->statusDetail->setText(txid); + + QTimer::singleShot(1000, [=]() { + d->accept(); + d->close(); + delete connD; + delete d; + + // And switch to the balances tab + ui->tabWidget->setCurrentIndex(0); + }); + + // Force a UI update so we get the unconfirmed Tx + rpc->refresh(true); + // If this was a recurring payment, update the payment with the info if (!recurringPaymentHash.isEmpty()) { // Since this is the send button payment, this is the first payment @@ -777,6 +687,11 @@ void MainWindow::sendButton() { // Errored out [=] (QString opid, QString errStr) { ui->statusBar->showMessage(QObject::tr(" Tx ") % opid % QObject::tr(" failed"), 15 * 1000); + + d->accept(); + d->close(); + delete connD; + delete d; if (!opid.isEmpty()) errStr = QObject::tr("The transaction with id ") % opid % QObject::tr(" failed. The error was") + ":\n\n" + errStr; @@ -795,8 +710,9 @@ void MainWindow::sendButton() { } QString MainWindow::doSendTxValidations(Tx tx) { - if (!Settings::isValidAddress(tx.fromAddr)) return QString(tr("From Address is Invalid")); + // Check to see if we have enough verified funds to send the Tx. + CAmount total; for (auto toAddr : tx.toAddrs) { if (!Settings::isValidAddress(toAddr.addr)) { QString addr = (toAddr.addr.length() > 100 ? toAddr.addr.left(100) + "..." : toAddr.addr); @@ -805,13 +721,22 @@ QString MainWindow::doSendTxValidations(Tx tx) { // This technically shouldn't be possible, but issue #62 seems to have discovered a bug // somewhere, so just add a check to make sure. - if (toAddr.amount < 0) { + if (toAddr.amount.toqint64() < 0) { return QString(tr("Amount for address '%1' is invalid!").arg(toAddr.addr)); } + + total = total + toAddr.amount; + } + total = total + tx.fee; + + auto available = rpc->getModel()->getAvailableBalance(); + + if (available < total) { + return tr("Not enough available funds to send this transaction\n\nHave: %1\nNeed: %2\n\nNote: Funds need 5 confirmations before they can be spent") + .arg(available.toDecimalhushString(), total.toDecimalhushString()); } - - return QString(); + return ""; } void MainWindow::cancelButton() { diff --git a/src/settings.cpp b/src/settings.cpp index 10be877..e21eddc 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1,5 +1,6 @@ #include "mainwindow.h" #include "settings.h" +#include "camount.h" Settings* Settings::instance = nullptr; @@ -18,33 +19,24 @@ Config Settings::getSettings() { // Load from the QT Settings. QSettings s; - auto host = s.value("connection/host").toString(); - auto port = s.value("connection/port").toString(); - auto username = s.value("connection/rpcuser").toString(); - auto password = s.value("connection/rpcpassword").toString(); + auto server = s.value("connection/server").toString(); + if (server.trimmed().isEmpty()) { + server = Settings::getDefaultServer(); + } - return Config{host, port, username, password}; + return Config{server}; } -void Settings::saveSettings(const QString& host, const QString& port, const QString& username, const QString& password) { +void Settings::saveSettings(const QString& server) { QSettings s; - s.setValue("connection/host", host); - s.setValue("connection/port", port); - s.setValue("connection/rpcuser", username); - s.setValue("connection/rpcpassword", password); - + s.setValue("connection/server", server); s.sync(); // re-init to load correct settings init(); } -void Settings::setUsinghushConf(QString confLocation) { - if (!confLocation.isEmpty()) - _confLocation = confLocation; -} - bool Settings::isTestnet() { return _isTestnet; } @@ -72,7 +64,7 @@ bool Settings::isZAddress(QString addr) { if (!isValidAddress(addr)) return false; - return addr.startsWith("z"); + return addr.startsWith("zs"); } bool Settings::isTAddress(QString addr) { @@ -110,17 +102,8 @@ bool Settings::isSaplingActive() { return (isTestnet() && getBlockNumber() > 0) || (!isTestnet() && getBlockNumber() > 0); } -double Settings::gethushPrice() { - return hushPrice; -} - -bool Settings::getAutoShield() { - // Load from Qt settings - return QSettings().value("options/autoshield", false).toBool(); -} - -void Settings::setAutoShield(bool allow) { - QSettings().setValue("options/autoshield", allow); +double Settings::getZECPrice() { + return ZECPrice; } bool Settings::getCheckForUpdates() { @@ -139,15 +122,6 @@ void Settings::setAllowFetchPrices(bool allow) { QSettings().setValue("options/allowfetchprices", allow); } -bool Settings::getAllowCustomFees() { - // Load from the QT Settings. - return QSettings().value("options/customfees", false).toBool(); -} - -void Settings::setAllowCustomFees(bool allow) { - QSettings().setValue("options/customfees", allow); -} - QString Settings::get_theme_name() { // Load from the QT Settings. return QSettings().value("options/theme_name", false).toString(); @@ -157,22 +131,7 @@ void Settings::set_theme_name(QString theme_name) { QSettings().setValue("options/theme_name", theme_name); } -bool Settings::getSaveZtxs() { - // Load from the QT Settings. - return QSettings().value("options/savesenttx", true).toBool(); -} -void Settings::setSaveZtxs(bool save) { - QSettings().setValue("options/savesenttx", save); -} - -void Settings::setPeers(int peers) { - _peerConnections = peers; -} - -int Settings::getPeers() { - return _peerConnections; -} //================================= // Static Stuff //================================= @@ -193,6 +152,10 @@ void Settings::saveRestoreTableHeader(QTableView* table, QDialog* d, QString tab }); } +QString Settings::getDefaultServer() { + return "https://hush-lightwallet.de:443"; +} + void Settings::openAddressInExplorer(QString address) { QString url; if (Settings::getInstance()->isTestnet()) { @@ -216,37 +179,6 @@ void Settings::openTxInExplorer(QString txid) { - -QString Settings::getUSDFormat(double bal) { - return "$" + QLocale(QLocale::English).toString(bal * Settings::getInstance()->gethushPrice(), 'f', 2); -} - -QString Settings::getDecimalString(double amt) { - QString f = QString::number(amt, 'f', 8); - - while (f.contains(".") && (f.right(1) == "0" || f.right(1) == ".")) { - f = f.left(f.length() - 1); - } - if (f == "-0") - f = "0"; - - return f; -} - -QString Settings::gethushDisplayFormat(double bal) { - // This is idiotic. Why doesn't QString have a way to do this? - return getDecimalString(bal) % " " % Settings::getTokenName(); -} - -QString Settings::gethushUSDDisplayFormat(double bal) { - auto usdFormat = getUSDFormat(bal); - if (!usdFormat.isEmpty()) - return gethushDisplayFormat(bal) % " (" % getUSDFormat(bal) % ")"; - else - return gethushDisplayFormat(bal); -} - - const QString Settings::txidStatusMessage = QString(QObject::tr("Tx submitted (right click to copy) txid:")); QString Settings::getTokenName() { @@ -261,72 +193,12 @@ QString Settings::getDonationAddr() { if (Settings::getInstance()->isTestnet()) return "ztestsaplingXXX"; else - return "zs1aq4xnrkjlnxx0zesqye7jz3dfrf3rjh7q5z6u8l6mwyqqaam3gx3j2fkqakp33v93yavq46j83q"; + return "zs1kwp3h4rwz76zfqzmwqqextq696kndtjskg4fzc80l9ygfal4hchcsst83ua8tjwzzy9nja7v5rr"; } -bool Settings::addTohushConf(QString confLocation, QString line) { - QFile file(confLocation); - if (!file.open(QIODevice::ReadWrite | QIODevice::Append)) - return false; - - - QTextStream out(&file); - out << line << "\n"; - file.close(); - - return true; -} - -bool Settings::removeFromhushConf(QString confLocation, QString option) { - if (confLocation.isEmpty()) - return false; - - // To remove an option, we'll create a new file, and copy over everything but the option. - QFile file(confLocation); - if (!file.open(QIODevice::ReadOnly)) - return false; - - QList lines; - QTextStream in(&file); - while (!in.atEnd()) { - QString line = in.readLine(); - auto s = line.indexOf("="); - QString name = line.left(s).trimmed().toLower(); - if (name != option) { - lines.append(line); - } - } - file.close(); - - QFile newfile(confLocation); - if (!newfile.open(QIODevice::ReadWrite | QIODevice::Truncate)) - return false; - - QTextStream out(&newfile); - for (QString line : lines) { - out << line << endl; - } - newfile.close(); - - return true; -} - -double Settings::getMinerFee() { - return 0.0001; -} - -double Settings::getZboardAmount() { - return 0.0001; -} - -QString Settings::getZboardAddr() { - if (Settings::getInstance()->isTestnet()) { - return getDonationAddr(); - } - else { - return "zs10m00rvkhfm4f7n23e4sxsx275r7ptnggx39ygl0vy46j9mdll5c97gl6dxgpk0njuptg2mn9w5s"; - } +CAmount Settings::getMinerFee() { + return CAmount::fromqint64(10000); } bool Settings::isValidSaplingPrivateKey(QString pk) { @@ -349,7 +221,8 @@ bool Settings::isValidAddress(QString addr) { // Get a pretty string representation of this Payment URI QString Settings::paymentURIPretty(PaymentURI uri) { - return QString() + "Payment Request\n" + "Pay: " + uri.addr + "\nAmount: " + gethushDisplayFormat(uri.amt.toDouble()) + CAmount amount = CAmount::fromDecimalString(uri.amt); + return QString() + "Payment Request\n" + "Pay: " + uri.addr + "\nAmount: " + amount.toDecimalhushString() + "\nMemo:" + QUrl::fromPercentEncoding(uri.memo.toUtf8()); } diff --git a/src/settings.h b/src/settings.h index 12cb362..b4253d2 100644 --- a/src/settings.h +++ b/src/settings.h @@ -2,12 +2,12 @@ #define SETTINGS_H #include "precompiled.h" +#include "camount.h" + +using json = nlohmann::json; struct Config { - QString host; - QString port; - QString rpcuser; - QString rpcpassword; + QString server; }; struct ToFields; @@ -29,7 +29,7 @@ public: static Settings* getInstance(); Config getSettings(); - void saveSettings(const QString& host, const QString& port, const QString& username, const QString& password); + void saveSettings(const QString& server); bool isTestnet(); void setTestnet(bool isTestnet); @@ -54,15 +54,6 @@ public: int getBlockNumber(); void setBlockNumber(int number); - bool getSaveZtxs(); - void setSaveZtxs(bool save); - - bool getAutoShield(); - void setAutoShield(bool allow); - - bool getAllowCustomFees(); - void setAllowCustomFees(bool allow); - bool getAllowFetchPrices(); void setAllowFetchPrices(bool allow); @@ -74,15 +65,9 @@ public: bool isSaplingActive(); - void setUsinghushConf(QString confLocation); - const QString& gethushdConfLocation() { return _confLocation; } + void setZECPrice(double p) { ZECPrice = p; } + double getZECPrice(); - void sethushPrice(double p) { hushPrice = p; } - double gethushPrice(); - - void setPeers(int peers); - int getPeers(); - // Static stuff static const QString txidStatusMessage; @@ -98,27 +83,18 @@ public: static bool isZAddress(QString addr); static bool isTAddress(QString addr); - static QString getDecimalString(double amt); - static QString getUSDFormat(double bal); - - - static QString gethushDisplayFormat(double bal); - static QString gethushUSDDisplayFormat(double bal); - static QString getTokenName(); static QString getDonationAddr(); - static double getMinerFee(); - static double getZboardAmount(); - static QString getZboardAddr(); + static QString getDefaultServer(); + static CAmount getMinerFee(); static int getMaxMobileAppTxns() { return 30; } + + static int getNumberOfDecimalPlaces() {return 8;} static bool isValidAddress(QString addr); - static bool addTohushConf(QString confLocation, QString line); - static bool removeFromhushConf(QString confLocation, QString option); - static QString getChainName() { return QString("main"); } static const QString labelRegExp; @@ -134,7 +110,6 @@ private: static Settings* instance; - QString _confLocation; QString _executable; bool _isTestnet = false; bool _isSyncing = false; @@ -142,9 +117,19 @@ private: int _hushdVersion = 0; bool _useEmbedded = false; bool _headless = false; - int _peerConnections = 0; - double hushPrice = 0.0; + double ZECPrice = 0.0; }; + +inline bool isJsonResultSuccess(const json& res) { + return res.find("result") != res.end() && + QString::fromStdString(res["result"].get()) == "success"; +} + +inline bool isJsonError(const json& res) { + return res.find("error") != res.end(); +} + + #endif // SETTINGS_H diff --git a/src/settings.ui b/src/settings.ui index baf1421..8a749da 100644 --- a/src/settings.ui +++ b/src/settings.ui @@ -26,11 +26,11 @@ - 1 + 0 - hushd connection + Connection @@ -43,13 +43,6 @@ - - - - Qt::Horizontal - - - @@ -59,69 +52,17 @@ - Host + Server - + - - - - - 60 - 0 - - - - Port - - - - - - - - - - - - - - - 60 - 0 - - - - RPC Username - - - - - - - - - - - 60 - 0 - - - - RPC Password - - - - - - @@ -145,165 +86,7 @@ Options - - - - Connect to github on startup to check for updates - - - - - - - Normally, change from t-Addresses goes to another t-Address. Checking this option will send the change to your shielded sapling address instead. Check this option to increase your privacy. - - - true - - - - - - - Clear History - - - - - - - Remember shielded transactions - - - - - - - Connect to the internet to fetch hush prices - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Allow overriding the default fees when sending transactions. Enabling this option may compromise your privacy since fees are transparent. - - - true - - - - - - - Check github for updates at startup - - - - - - - Shielded transactions are saved locally and shown in the transactions tab. If you uncheck this, shielded transactions will not appear in the transactions tab. - - - true - - - - - - - Shield change from t-Addresses to your sapling address - - - - - - - - 0 - 0 - - - - Qt::Horizontal - - - - - - - Connect to the Tor network via SOCKS proxy running on 127.0.0.1:9050. Please note that you'll have to install and run the Tor service externally. - - - true - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Connect via Tor - - - - - - - Allow custom fees - - - - - - - Fetch hush / USD prices - - - - - - - - 0 - 0 - - - - Theme - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - + @@ -333,6 +116,76 @@ + + + + Fetch hush / USD prices + + + + + + + Check github for updates at startup + + + + + + + Connect to github on startup to check for updates + + + + + + + + 0 + 0 + + + + Theme + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + 0 + 0 + + + + Qt::Horizontal + + + + + + + Connect to the internet to fetch hush prices + + + @@ -341,37 +194,6 @@ - - - Reindex - - - - - - - Rescan the blockchain for any missing wallet transactions and to correct your wallet balance. This may take several hours. You need to restart silentdragon for this to take effect - - - true - - - - - - - Rescan - - - - - - - Qt::Horizontal - - - - Qt::Vertical @@ -385,33 +207,26 @@ - - - + + + Qt::Horizontal - - + + - Rebuild the entire blockchain from the genesis block, by rescanning all the block files. This may take several hours to days, depending on your hardware. You need to restart silentdragon for this to take effect + Rescan the blockchain for any missing wallet transactions and to correct your wallet balance. This may take several hours. You need to restart hushWallet for this to take effect true - - - - Qt::Horizontal - - - - - + + - + Rescan diff --git a/src/txtablemodel.cpp b/src/txtablemodel.cpp index 7676f2c..b25f2d7 100644 --- a/src/txtablemodel.cpp +++ b/src/txtablemodel.cpp @@ -69,10 +69,20 @@ bool TxTableModel::exportToCsv(QString fileName) const { return headers.size(); } +QString TxTableModel::concatMultipleMemos(const TransactionItem& dat) const { + // Concat all the memos + QString memo; + for (auto item : dat.items) { + if (!item.memo.trimmed().isEmpty()) { + memo += item.address + ": \"" + item.memo + "\"\n"; + } + } - QVariant TxTableModel::data(const QModelIndex &index, int role) const - { - // Align numeric columns (confirmations, amount) right + return memo; +}; + +QVariant TxTableModel::data(const QModelIndex &index, int role) const { + // Align numeric columns (confirmations, amount) right if (role == Qt::TextAlignmentRole && (index.column() == Column::Confirmations || index.column() == Column::Amount)) return QVariant(Qt::AlignRight | Qt::AlignVCenter); @@ -105,11 +115,11 @@ bool TxTableModel::exportToCsv(QString fileName) const { case Column::Confirmations: return QString::number(dat.confirmations); case Column::Amount: { // Sum up all the amounts - double total = 0; + CAmount total; for (int i=0; i < dat.items.length(); i++) { - total += dat.items[i].amount; + total = total + dat.items[i].amount; } - return Settings::gethushDisplayFormat(total); + return total.toDecimalhushString(); } } } @@ -127,7 +137,7 @@ bool TxTableModel::exportToCsv(QString fileName) const { (memo.isEmpty() ? "" : " tx memo: \"" + memo + "\""); } } else { - return "Multiple"; + return concatMultipleMemos(dat); } } case Column::Address: { @@ -141,23 +151,23 @@ bool TxTableModel::exportToCsv(QString fileName) const { case Column::Confirmations: return QString("%1 Network Confirmations").arg(QString::number(dat.confirmations)); case Column::Amount: { // Sum up all the amounts - double total = 0; + CAmount total; for (int i=0; i < dat.items.length(); i++) { - total += dat.items[i].amount; + total = total + dat.items[i].amount; } - return Settings::getInstance()->getUSDFormat(total); + return total.toDecimalUSDString(); } } } - if (role == Qt::DecorationRole && index.column() == 0) { + if (role == Qt::DecorationRole && index.column() == 0) { bool hasMemo = false; for (int i=0; i < dat.items.length(); i++) { if (!dat.items[i].memo.isEmpty()) { hasMemo = true; } } - + // If the memo is a Payment URI, then show a payment request icon if (dat.items.length() == 1 && dat.items[0].memo.startsWith("hush:")) { QIcon icon(":/icons/res/paymentreq.gif"); @@ -202,20 +212,8 @@ QString TxTableModel::getTxId(int row) const { QString TxTableModel::getMemo(int row) const { auto dat = modeldata->at(row); - bool hasMemo = false; - for (int i=0; i < dat.items.length(); i++) { - if (!dat.items[i].memo.isEmpty()) { - hasMemo = true; - } - } - - if (dat.items.length() == 1) { - return dat.items[0].memo; - } else if (hasMemo) { - return "(Multiple)"; - } else { - return ""; - } + + return concatMultipleMemos(dat); } qint64 TxTableModel::getConfirmations(int row) const { @@ -237,9 +235,9 @@ QString TxTableModel::getType(int row) const { QString TxTableModel::getAmt(int row) const { auto dat = modeldata->at(row); - double total = 0; + CAmount total; for (int i=0; i < dat.items.length(); i++) { - total += dat.items[i].amount; + total = total + dat.items[i].amount; } - return Settings::getDecimalString(total); + return total.toDecimalString(); } diff --git a/src/txtablemodel.h b/src/txtablemodel.h index 8e60ea7..b07b914 100644 --- a/src/txtablemodel.h +++ b/src/txtablemodel.h @@ -38,6 +38,8 @@ public: QVariant headerData(int section, Qt::Orientation orientation, int role) const; private: + QString concatMultipleMemos(const TransactionItem&) const; + QList* modeldata = nullptr; QList headers; diff --git a/src/version.h b/src/version.h index d40071e..58be58c 100644 --- a/src/version.h +++ b/src/version.h @@ -1 +1 @@ -#define APP_VERSION "0.7.9" +#define APP_VERSION "1.0" diff --git a/src/viewalladdresses.cpp b/src/viewalladdresses.cpp index 0a7d06d..bd2ce3e 100644 --- a/src/viewalladdresses.cpp +++ b/src/viewalladdresses.cpp @@ -1,4 +1,5 @@ #include "viewalladdresses.h" +#include "camount.h" #include "settings.h" ViewAllAddressesModel::ViewAllAddressesModel(QTableView *parent, QList taddrs, Controller* rpc) @@ -22,7 +23,7 @@ QVariant ViewAllAddressesModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { switch(index.column()) { case 0: return address; - case 1: return rpc->getModel()->getAllBalances().value(address, 0.0); + case 1: return rpc->getModel()->getAllBalances().value(address, CAmount::fromqint64(0)).toDecimalString(); } } return QVariant(); diff --git a/src/websockets.cpp b/src/websockets.cpp index 28afdc6..cd9d5ad 100644 --- a/src/websockets.cpp +++ b/src/websockets.cpp @@ -320,7 +320,7 @@ void AppDataServer::updateUIWithNewQRCode(MainWindow* mainwindow) { if (ipv4Addr.isEmpty()) return; - QString uri = "ws://" + ipv4Addr + ":8237"; + QString uri = "ws://" + ipv4Addr + ":8777"; // Get a new secret unsigned char* secretBin = new unsigned char[crypto_secretbox_KEYBYTES]; @@ -658,9 +658,9 @@ void AppDataServer::processSendTx(QJsonObject sendTx, MainWindow* mainwindow, st tx.fee = Settings::getMinerFee(); // Find a from address that has at least the sending amout - double amt = sendTx["amount"].toString().toDouble(); + CAmount amt = CAmount::fromDecimalString(sendTx["amount"].toString()); auto allBalances = mainwindow->getRPC()->getModel()->getAllBalances(); - QList> bals; + QList> bals; for (auto i : allBalances.keys()) { // Filter out sprout addresses if (Settings::getInstance()->isSproutAddress(i)) @@ -669,7 +669,7 @@ void AppDataServer::processSendTx(QJsonObject sendTx, MainWindow* mainwindow, st if (allBalances.value(i) < amt) continue; - bals.append(QPair(i, allBalances.value(i))); + bals.append(QPair(i, allBalances.value(i))); } if (bals.isEmpty()) { @@ -677,7 +677,7 @@ void AppDataServer::processSendTx(QJsonObject sendTx, MainWindow* mainwindow, st return; } - std::sort(bals.begin(), bals.end(), [=](const QPaira, const QPair b) -> bool { + std::sort(bals.begin(), bals.end(), [=](const QPaira, const QPair b) -> bool { // Sort z addresses first return a.first > b.first; }); @@ -736,8 +736,8 @@ void AppDataServer::processGetInfo(QJsonObject jobj, MainWindow* mainWindow, std } // Max spendable safely from a z address and from any address - double maxZSpendable = 0; - double maxSpendable = 0; + CAmount maxZSpendable; + CAmount maxSpendable; for (auto a : mainWindow->getRPC()->getModel()->getAllBalances().keys()) { if (Settings::getInstance()->isSaplingAddress(a)) { if (mainWindow->getRPC()->getModel()->getAllBalances().value(a) > maxZSpendable) { @@ -751,16 +751,16 @@ void AppDataServer::processGetInfo(QJsonObject jobj, MainWindow* mainWindow, std setConnectedName(connectedName); - auto r = QJsonDocument(QJsonObject{ + auto r = QJsonDocument(QJsonObject { {"version", 1.0}, {"command", "getInfo"}, {"saplingAddress", mainWindow->getRPC()->getDefaultSaplingAddress()}, {"tAddress", mainWindow->getRPC()->getDefaultTAddress()}, - {"balance", AppDataModel::getInstance()->getTotalBalance()}, - {"maxspendable", maxSpendable}, - {"maxzspendable", maxZSpendable}, + {"balance", AppDataModel::getInstance()->getTotalBalance().toDecimalDouble()}, + {"maxspendable", maxSpendable.toDecimalDouble()}, + {"maxzspendable", maxZSpendable.toDecimalDouble()}, {"tokenName", Settings::getTokenName()}, - {"hushprice", Settings::getInstance()->gethushPrice()}, + {"zecprice", Settings::getInstance()->getZECPrice()}, {"serverversion", QString(APP_VERSION)} }).toJson(); pClient->sendTextMessage(encryptOutgoing(r)); diff --git a/src/websockets.h b/src/websockets.h index 4758f1c..6483f42 100644 --- a/src/websockets.h +++ b/src/websockets.h @@ -3,6 +3,7 @@ #include "precompiled.h" +#include "camount.h" #include "mainwindow.h" #include "ui_mobileappconnector.h" @@ -151,11 +152,11 @@ public: return instance; } - double getTBalance() { return balTransparent; } - double getZBalance() { return balShielded; } - double getTotalBalance() { return balTotal; } + CAmount getTBalance() { return balTransparent; } + CAmount getZBalance() { return balShielded; } + CAmount getTotalBalance() { return balTotal; } - void setBalances(double transparent, double shielded) { + void setBalances(CAmount transparent, CAmount shielded) { balTransparent = transparent; balShielded = shielded; balTotal = balTransparent + balShielded; @@ -164,9 +165,9 @@ public: private: AppDataModel() = default; // Private, for singleton - double balTransparent; - double balShielded; - double balTotal; + CAmount balTransparent; + CAmount balShielded; + CAmount balTotal; QString saplingAddress;