Browse Source

switch back to json lohman - qtjson in new branch for more testing

pull/174/head
DenioD 4 years ago
parent
commit
460974f594
  1. 1
      silentdragon-lite.pro
  2. 18928
      src/3rdparty/json/json.hpp
  3. 9
      src/DataStore/ChatDataStore.cpp
  4. 1
      src/DataStore/ChatDataStore.h
  5. 11
      src/DataStore/ContactDataStore.cpp
  6. 1
      src/DataStore/ContactDataStore.h
  7. 2
      src/DataStore/SietchDataStore.h
  8. 1
      src/FileSystem/FileSystem.h
  9. 23
      src/Model/ChatItem.cpp
  10. 3
      src/Model/ChatItem.h
  11. 14
      src/Model/ContactItem.cpp
  12. 3
      src/Model/ContactItem.h
  13. 1
      src/Model/ContactRequest.h
  14. 4
      src/addressbook.cpp
  15. 9
      src/chatmodel.cpp
  16. 45
      src/connection.cpp
  17. 21
      src/connection.h
  18. 539
      src/controller.cpp
  19. 34
      src/controller.h
  20. 22
      src/firsttimewizard.cpp
  21. 40
      src/liteinterface.cpp
  22. 42
      src/liteinterface.h
  23. 34
      src/mainwindow.cpp
  24. 2
      src/mainwindow.h
  25. 1
      src/precompiled.h
  26. 2
      src/sendtab.cpp
  27. 11
      src/settings.h
  28. 8
      src/websockets.cpp

1
silentdragon-lite.pro

@ -50,6 +50,7 @@ SOURCES += \
src/3rdparty/qrcode/BitBuffer.cpp \ src/3rdparty/qrcode/BitBuffer.cpp \
src/3rdparty/qrcode/QrCode.cpp \ src/3rdparty/qrcode/QrCode.cpp \
src/3rdparty/qrcode/QrSegment.cpp \ src/3rdparty/qrcode/QrSegment.cpp \
src/3rdparty/json/json.hpp \
src/settings.cpp \ src/settings.cpp \
src/sendtab.cpp \ src/sendtab.cpp \
src/txtablemodel.cpp \ src/txtablemodel.cpp \

18928
src/3rdparty/json/json.hpp

File diff suppressed because it is too large

9
src/DataStore/ChatDataStore.cpp

@ -59,16 +59,15 @@ void ChatDataStore::setPassword(QString password)
QString ChatDataStore::dump() QString ChatDataStore::dump()
{ {
QJsonObject chats; json chats;
chats["count"] = (qint64)this->data.size(); chats["count"] = this->data.size();
QJsonArray j; json j = {};
for (auto &c: this->data) for (auto &c: this->data)
{ {
j.push_back(c.second.toJson()); j.push_back(c.second.toJson());
} }
chats["chatitems"] = j; chats["chatitems"] = j;
QJsonDocument jd_chats = QJsonDocument(chats); return QString::fromStdString(chats.dump());
return QLatin1String(jd_chats.toJson(QJsonDocument::Compact));
} }
std::map<QString, ChatItem> ChatDataStore::getAllRawChatItems() std::map<QString, ChatItem> ChatDataStore::getAllRawChatItems()

1
src/DataStore/ChatDataStore.h

@ -1,6 +1,7 @@
#ifndef CHATDATASTORE_H #ifndef CHATDATASTORE_H
#define CHATDATASTORE_H #define CHATDATASTORE_H
#include "../chatmodel.h" #include "../chatmodel.h"
using json = nlohmann::json;
class ChatDataStore class ChatDataStore
{ {

11
src/DataStore/ContactDataStore.cpp

@ -33,9 +33,9 @@ ContactItem ContactDataStore::getData(QString key)
QString ContactDataStore::dump() QString ContactDataStore::dump()
{ {
QJsonObject contacts; json contacts;
contacts["count"] = (qint64)this->data.size(); contacts["count"] = this->data.size();
QJsonArray j = {}; json j = {};
for (auto &c: this->data) for (auto &c: this->data)
{ {
qDebug() << c.second.toQTString(); qDebug() << c.second.toQTString();
@ -43,10 +43,7 @@ QString ContactDataStore::dump()
j.push_back(c.second.toJson()); j.push_back(c.second.toJson());
} }
contacts["contacts"] = j; contacts["contacts"] = j;
QJsonDocument jd_contacts = QJsonDocument(contacts); return QString::fromStdString(contacts.dump(4));
return QLatin1String(jd_contacts.toJson(QJsonDocument::Compact));
// return QString::fromStdString(contacts.dump(4));
} }
ContactDataStore* ContactDataStore::instance = nullptr; ContactDataStore* ContactDataStore::instance = nullptr;

1
src/DataStore/ContactDataStore.h

@ -2,6 +2,7 @@
#define CONTACTDATASTORE_H #define CONTACTDATASTORE_H
#include "../Model/ContactItem.h" #include "../Model/ContactItem.h"
#include <string> #include <string>
using json = nlohmann::json;
class ContactDataStore class ContactDataStore
{ {

2
src/DataStore/SietchDataStore.h

@ -1,6 +1,8 @@
#ifndef SIETCHDATASTORE_H #ifndef SIETCHDATASTORE_H
#define SIETCHDATASTORE_H #define SIETCHDATASTORE_H
using json = nlohmann::json;
class SietchDataStore class SietchDataStore
{ {
private: private:

1
src/FileSystem/FileSystem.h

@ -8,6 +8,7 @@
#include "../Model/ContactItem.h" #include "../Model/ContactItem.h"
#include "../Crypto/FileEncryption.h" #include "../Crypto/FileEncryption.h"
#include <fstream> #include <fstream>
using json = nlohmann::json;
class FileSystem class FileSystem
{ {

23
src/Model/ChatItem.cpp

@ -219,17 +219,18 @@ QString ChatItem::toChatLine()
return line; return line;
} }
QJsonValue ChatItem::toJson()
{ json ChatItem::toJson()
QJsonObject j; {
j["_timestamp"] = (qint64)_timestamp; json j;
j["_address"] = _address; j["_timestamp"] = _timestamp;
j["_contact"] = _contact; j["_address"] = _address.toStdString();
j["_memo"] = _memo; j["_contact"] = _contact.toStdString();
j["_requestZaddr"] = _requestZaddr; j["_memo"] = _memo.toStdString();
j["_type"] = _type; j["_requestZaddr"] = _requestZaddr.toStdString();
j["_cid"] = _cid; j["_type"] = _type.toStdString();
j["_txid"] = _txid; j["_cid"] = _cid.toStdString();
j["_txid"] = _txid.toStdString();
j["_confirmations"] = _confirmations; j["_confirmations"] = _confirmations;
j["_outgoing"] = _outgoing; j["_outgoing"] = _outgoing;
return j; return j;

3
src/Model/ChatItem.h

@ -5,6 +5,7 @@
#define CHATITEM_H #define CHATITEM_H
#include <QString> #include <QString>
using json = nlohmann::json;
class ChatItem class ChatItem
{ {
@ -52,7 +53,7 @@ class ChatItem
void notarized(); void notarized();
void contact(bool iscontact); void contact(bool iscontact);
QString toChatLine(); QString toChatLine();
QJsonValue toJson(); json toJson();
~ChatItem(); ~ChatItem();
}; };

14
src/Model/ContactItem.cpp

@ -86,13 +86,13 @@ QString ContactItem::toQTString()
return _name + "|" + _partnerAddress + "|" + _myAddress + "|" + _cid + "|" + _avatar; return _name + "|" + _partnerAddress + "|" + _myAddress + "|" + _cid + "|" + _avatar;
} }
QJsonValue ContactItem::toJson() json ContactItem::toJson()
{ {
QJsonObject j; json j;
j["_myAddress"] = _myAddress; j["_myAddress"] = _myAddress.toStdString();
j["_partnerAddress"] = _partnerAddress; j["_partnerAddress"] = _partnerAddress.toStdString();
j["_name"] = _name; j["_name"] = _name.toStdString();
j["_cid"] = _cid; j["_cid"] = _cid.toStdString();
j["_avatar"] = _avatar; j["_avatar"] = _avatar.toStdString();
return j; return j;
} }

3
src/Model/ContactItem.h

@ -6,6 +6,7 @@
#include <vector> #include <vector>
#include <QString> #include <QString>
#include "mainwindow.h" #include "mainwindow.h"
using json = nlohmann::json;
class ContactItem class ContactItem
{ {
@ -33,7 +34,7 @@ public:
void setcid(QString cid); void setcid(QString cid);
void setAvatar(QString avatar); void setAvatar(QString avatar);
QString toQTString(); QString toQTString();
QJsonValue toJson(); json toJson();
}; };
#endif #endif

1
src/Model/ContactRequest.h

@ -5,6 +5,7 @@
#define CONTACTREQUEST_H #define CONTACTREQUEST_H
#include <QString> #include <QString>
using json = nlohmann::json;
class ContactRequest class ContactRequest
{ {

4
src/addressbook.cpp

@ -153,8 +153,8 @@ void AddressBook::open(MainWindow* parent, QLineEdit* target)
bool sapling = true; bool sapling = true;
try try
{ {
rpc->createNewZaddr(sapling, [=] (QJsonValue reply) { rpc->createNewZaddr(sapling, [=] (json reply) {
QString myAddr = reply.toArray()[0].toString(); QString myAddr = QString::fromStdString(reply.get<json::array_t>()[0]);
QString message = QString("New Chat Address for your partner: ") + myAddr; QString message = QString("New Chat Address for your partner: ") + myAddr;
QString cid = QUuid::createUuid().toString(QUuid::WithoutBraces); QString cid = QUuid::createUuid().toString(QUuid::WithoutBraces);

9
src/chatmodel.cpp

@ -433,8 +433,6 @@ Tx MainWindow::createTxFromChatPage() {
QString myAddr = c.getMyAddress(); QString myAddr = c.getMyAddress();
QString type = "Memo"; QString type = "Memo";
QString addr = c.getPartnerAddress(); QString addr = c.getPartnerAddress();
/////////User input for chatmemos /////////User input for chatmemos
QString memoplain = ui->memoTxtChat->toPlainText().trimmed(); QString memoplain = ui->memoTxtChat->toPlainText().trimmed();
@ -516,8 +514,7 @@ Tx MainWindow::createTxFromChatPage() {
/////Ciphertext Memo /////Ciphertext Memo
QString memo = QByteArray(reinterpret_cast<const char*>(ciphertext), CIPHERTEXT_LEN).toHex(); QString memo = QByteArray(reinterpret_cast<const char*>(ciphertext), CIPHERTEXT_LEN).toHex();
tx.toAddrs.push_back(ToFields{addr, amt, hmemo}); tx.toAddrs.push_back(ToFields{addr, amt, hmemo});
tx.toAddrs.push_back(ToFields{addr, amt, memo}); tx.toAddrs.push_back(ToFields{addr, amt, memo});
@ -724,8 +721,8 @@ void::MainWindow::addContact()
{ {
bool sapling = true; bool sapling = true;
rpc->createNewZaddr(sapling, [=] (QJsonValue reply) { rpc->createNewZaddr(sapling, [=] (json reply) {
QString myAddr = reply.toArray()[0].toString(); QString myAddr = QString::fromStdString(reply.get<json::array_t>()[0]);
rpc->refreshAddresses(); rpc->refreshAddresses();
request.myzaddr->setText(myAddr); request.myzaddr->setText(myAddr);
ui->listReceiveAddresses->insertItem(0, myAddr); ui->listReceiveAddresses->insertItem(0, myAddr);

45
src/connection.cpp

@ -8,6 +8,8 @@
#include "../lib/silentdragonlitelib.h" #include "../lib/silentdragonlitelib.h"
#include "precompiled.h" #include "precompiled.h"
using json = nlohmann::json;
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
auto dirwalletconnection = QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)).filePath("silentdragonlite/silentdragonlite-wallet.dat"); auto dirwalletconnection = QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)).filePath("silentdragonlite/silentdragonlite-wallet.dat");
#endif #endif
@ -99,7 +101,7 @@ void ConnectionLoader::doAutoConnect()
auto me = this; auto me = this;
// After the lib is initialized, try to do get info // After the lib is initialized, try to do get info
connection->doRPC("info", "", [=](QJsonValue reply) { connection->doRPC("info", "", [=](auto reply) {
// If success, set the connection // If success, set the connection
main->logger->write("Connection is online."); main->logger->write("Connection is online.");
connection->setInfo(reply); connection->setInfo(reply);
@ -111,7 +113,7 @@ void ConnectionLoader::doAutoConnect()
// Do a sync at startup // Do a sync at startup
syncTimer = new QTimer(main); syncTimer = new QTimer(main);
main->logger->write("Beginning sync"); main->logger->write("Beginning sync");
connection->doRPCWithDefaultErrorHandling("sync", "", [=](QJsonValue) { connection->doRPCWithDefaultErrorHandling("sync", "", [=](auto) {
isSyncing->storeRelaxed(false); isSyncing->storeRelaxed(false);
// Cancel the timer // Cancel the timer
syncTimer->deleteLater(); syncTimer->deleteLater();
@ -126,12 +128,12 @@ void ConnectionLoader::doAutoConnect()
// Get the sync status // Get the sync status
try { try {
connection->doRPC("syncstatus", "", [=](QJsonValue reply) { connection->doRPC("syncstatus", "", [=](json reply) {
if (isSyncing != nullptr && reply.find("synced_blocks") != reply.end())
if (isSyncing != nullptr && reply.toObject()["synced_blocks"].toInt())
{ {
qint64 synced = reply["synced_blocks"].toInt(); qint64 synced = reply["synced_blocks"].get<json::number_unsigned_t>();
qint64 total = reply["total_blocks"].toInt(); qint64 total = reply["total_blocks"].get<json::number_unsigned_t>();
me->showInformation( me->showInformation(
"Synced " + QString::number(synced) + " / " + QString::number(total) "Synced " + QString::number(synced) + " / " + QString::number(total)
); );
@ -238,26 +240,21 @@ void Executor::run()
{ {
char* resp = litelib_execute(this->cmd.toStdString().c_str(), this->args.toStdString().c_str()); char* resp = litelib_execute(this->cmd.toStdString().c_str(), this->args.toStdString().c_str());
QString reply = litelib_process_response(resp); QString reply = litelib_process_response(resp);
QJsonDocument parsed = QJsonDocument::fromJson(reply.toUtf8()); auto parsed = json::parse(
reply.toStdString().c_str(),
if (parsed.isEmpty() || parsed.isNull()) nullptr,
false
);
if (parsed.is_discarded() || parsed.is_null())
emit handleError(reply); emit handleError(reply);
else else
{
QJsonValue retval;
if (parsed.isObject())
retval = QJsonValue(parsed.object());
else if (parsed.isArray())
retval = QJsonValue(parsed.array());
emit responseReady(retval); emit responseReady(parsed);
}
} }
void Callback::processRPCCallback(QJsonValue resp) void Callback::processRPCCallback(json resp)
{ {
this->cb(resp); this->cb(resp);
// Destroy self // Destroy self
@ -276,10 +273,10 @@ Connection::Connection(MainWindow* m, std::shared_ptr<ConnectionConfig> conf)
this->config = conf; this->config = conf;
this->main = m; this->main = m;
// Register the JSON type as a type that can be passed between signals and slots. // Register the JSON type as a type that can be passed between signals and slots.
qRegisterMetaType<QJsonValue>("QJsonValue"); qRegisterMetaType<json>("json");
} }
void Connection::doRPC(const QString cmd, const QString args, const std::function<void(QJsonValue)>& cb, const std::function<void(QString)>& errCb) void Connection::doRPC(const QString cmd, const QString args, const std::function<void(json)>& cb, const std::function<void(QString)>& errCb)
{ {
if (shutdownInProgress) if (shutdownInProgress)
// Ignoring RPC because shutdown in progress // Ignoring RPC because shutdown in progress
@ -298,14 +295,14 @@ void Connection::doRPC(const QString cmd, const QString args, const std::functio
QThreadPool::globalInstance()->start(runner); QThreadPool::globalInstance()->start(runner);
} }
void Connection::doRPCWithDefaultErrorHandling(const QString cmd, const QString args, const std::function<void(QJsonValue)>& cb) void Connection::doRPCWithDefaultErrorHandling(const QString cmd, const QString args, const std::function<void(json)>& cb)
{ {
doRPC(cmd, args, cb, [=] (QString err) { doRPC(cmd, args, cb, [=] (QString err) {
this->showTxError(err); this->showTxError(err);
}); });
} }
void Connection::doRPCIgnoreError(const QString cmd, const QString args, const std::function<void(QJsonValue)>& cb) void Connection::doRPCIgnoreError(const QString cmd, const QString args, const std::function<void(json)>& cb)
{ {
doRPC(cmd, args, cb, [=] (auto) { doRPC(cmd, args, cb, [=] (auto) {
// Ignored error handling // Ignored error handling

21
src/connection.h

@ -5,6 +5,7 @@
#include "ui_connection.h" #include "ui_connection.h"
#include "precompiled.h" #include "precompiled.h"
using json = nlohmann::json;
class Controller; class Controller;
@ -54,15 +55,15 @@ private:
class Callback: public QObject { class Callback: public QObject {
Q_OBJECT Q_OBJECT
public: public:
Callback(const std::function<void(QJsonValue)> cb, const std::function<void(QString)> errCb) { this->cb = cb; this->errCb = errCb;} Callback(const std::function<void(json)> cb, const std::function<void(QString)> errCb) { this->cb = cb; this->errCb = errCb;}
~Callback() = default; ~Callback() = default;
public slots: public slots:
void processRPCCallback(QJsonValue resp); void processRPCCallback(json resp);
void processError(QString error); void processError(QString error);
private: private:
std::function<void(QJsonValue)> cb; std::function<void(json)> cb;
std::function<void(QString)> errCb; std::function<void(QString)> errCb;
}; };
@ -89,7 +90,7 @@ public:
virtual void run(); virtual void run();
signals: signals:
void responseReady(QJsonValue); void responseReady(json);
void handleError(QString); void handleError(QString);
private: private:
@ -114,19 +115,19 @@ public:
void shutdown(); void shutdown();
void doRPC(const QString cmd, const QString args, const std::function<void(QJsonValue)>& cb, void doRPC(const QString cmd, const QString args, const std::function<void(json)>& cb,
const std::function<void(QString)>& errCb); const std::function<void(QString)>& errCb);
void doRPCWithDefaultErrorHandling(const QString cmd, const QString args, const std::function<void(QJsonValue)>& cb); void doRPCWithDefaultErrorHandling(const QString cmd, const QString args, const std::function<void(json)>& cb);
void doRPCIgnoreError(const QString cmd, const QString args, const std::function<void(QJsonValue)>& cb) ; void doRPCIgnoreError(const QString cmd, const QString args, const std::function<void(json)>& cb) ;
void showTxError(const QString& error); void showTxError(const QString& error);
QJsonValue getInfo() { return serverInfo; } json getInfo() { return serverInfo; }
void setInfo(const QJsonValue& info) { serverInfo = info; } void setInfo(const json& info) { serverInfo = info; }
private: private:
bool shutdownInProgress = false; bool shutdownInProgress = false;
QJsonValue serverInfo; json serverInfo;
}; };
#endif #endif

539
src/controller.cpp

@ -15,6 +15,8 @@ ChatModel *chatModel = new ChatModel();
Chat *chat = new Chat(); Chat *chat = new Chat();
ContactModel *contactModel = new ContactModel(); ContactModel *contactModel = new ContactModel();
using json = nlohmann::json;
Controller::Controller(MainWindow* main) Controller::Controller(MainWindow* main)
{ {
@ -92,8 +94,8 @@ void Controller::setConnection(Connection* c)
// Using DataStore singelton, to store the data outside of lambda, bing bada boom :D // Using DataStore singelton, to store the data outside of lambda, bing bada boom :D
for(uint8_t i = 0; i < 6; i++) for(uint8_t i = 0; i < 6; i++)
{ {
zrpc->createNewSietchZaddr( [=] (QJsonValue reply) { zrpc->createNewSietchZaddr( [=] (json reply) {
QString zdust = reply.toArray()[0].toString(); QString zdust = QString::fromStdString(reply.get<json::array_t>()[0]);
DataStore::getSietchDataStore()->setData("Sietch" + QString(i), zdust.toUtf8()); DataStore::getSietchDataStore()->setData("Sietch" + QString(i), zdust.toUtf8());
}); });
} }
@ -123,44 +125,32 @@ std::string Controller::encryptDecrypt(std::string toEncrypt)
} }
// Build the RPC JSON Parameters for this tx // Build the RPC JSON Parameters for this tx
void Controller::fillTxJsonParams(QJsonArray& allRecepients, Tx tx) void Controller::fillTxJsonParams(json& allRecepients, Tx tx)
{ {
Q_ASSERT(allRecepients.isEmpty()); Q_ASSERT(allRecepients.is_array());
// Construct the JSON params // Construct the JSON params
QJsonObject rec; json rec = json::object();
//creating the JSON dust parameters in a std::vector to iterate over there during tx //creating the JSON dust parameters in a std::vector to iterate over there during tx
QVector<QJsonObject> dust; std::vector<json> dust(6);
dust.resize(6); dust.resize(6, json::object());
// Create Sietch zdust addr again to not use it twice. // Create Sietch zdust addr again to not use it twice.
// Using DataStore singelton, to store the data outside of lambda, bing bada boom :D // Using DataStore singelton, to store the data outside of lambda, bing bada boom :D
for(uint8_t i = 0; i < 6; i++) for(uint8_t i = 0; i < 6; i++)
{ {
zrpc->createNewSietchZaddr( [=] (QJsonValue reply) { zrpc->createNewSietchZaddr( [=] (json reply) {
QString zdust = reply.toArray()[0].toString(); QString zdust = QString::fromStdString(reply.get<json::array_t>()[0]);
DataStore::getSietchDataStore()->setData(QString("Sietch") + QString(i), zdust.toUtf8()); DataStore::getSietchDataStore()->setData(QString("Sietch") + QString(i), zdust.toUtf8());
} ); } );
} }
// Set sietch zdust addr to json. // Set sietch zdust addr to json.
// Using DataStore singelton, to store the data into the dusts, bing bada boom :D // Using DataStore singelton, to store the data into the dust.
int i = 0;
for(auto &it : dust)
{
it["address"] = DataStore::getSietchDataStore()->getData(QString("Sietch" + QString(i++)));
}
/*
for(uint8_t i = 0; i < 6; i++) for(uint8_t i = 0; i < 6; i++)
{ {
dust.at(i).toObject()["address"] = QJsonValue(DataStore::getSietchDataStore()->getData(QString("Sietch" + QString(i)))); dust.at(i)["address"] = DataStore::getSietchDataStore()->getData(QString("Sietch" + QString(i))).toStdString();
qDebug() << "MIODRAG ADDRESS FILL IN" << dust.at(i).toObject()["address"] << dust.at(i).toObject()["memo"] << dust.at(i).toObject()["amount"];
} }
*/
DataStore::getSietchDataStore()->clear(); // clears the datastore DataStore::getSietchDataStore()->clear(); // clears the datastore
@ -178,49 +168,18 @@ void Controller::fillTxJsonParams(QJsonArray& allRecepients, Tx tx)
QChar nextChar = possibleCharacters.at(index); QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar); randomString.append(nextChar);
} }
for(uint8_t i = 0; i < 6; i++)
for(auto &it : dust)
{
int length = randomString.length();
int randomSize = rand() % 120 +10;
char *randomHash = NULL;
randomHash = new char[length+1];
strncpy(randomHash, randomString.toLocal8Bit(), length +1);
#define MESSAGE ((const unsigned char *) randomHash)
#define MESSAGE_LEN length
#define MESSAGE_LEN1 length + randomSize
unsigned char hash[crypto_secretstream_xchacha20poly1305_ABYTES];
crypto_generichash(hash, sizeof hash,
MESSAGE, MESSAGE_LEN1,
NULL, 0);
std::string decryptedMemo(reinterpret_cast<char*>(hash),MESSAGE_LEN1);
std::string encrypt = this->encryptDecrypt(decryptedMemo);
QString randomHashafter1 = QByteArray(reinterpret_cast<const char*>(encrypt.c_str()),encrypt.size()).toHex();
it["memo"] = randomHashafter1;
//qDebug() << "MIODRAG MEMO FILL IN" << dust.at(i)["address"] << dust.at(i)["memo"] << dust.at(i)["amount"];
}
/*
for(uint8_t i = 0; i < 6; i++)
{ {
int length = randomString.length(); int length = randomString.length();
int randomSize = rand() % 120 +10; int randomSize = rand() % 120 +10;
char *randomHash = NULL; char *randomHash = NULL;
randomHash = new char[length+1]; randomHash = new char[length+1];
strncpy(randomHash, randomString.toLocal8Bit(), length +1); strncpy(randomHash, randomString.toLocal8Bit(), length +1);
#define MESSAGE ((const unsigned char *) randomHash) #define MESSAGE ((const unsigned char *) randomHash)
#define MESSAGE_LEN length #define MESSAGE_LEN length
#define MESSAGE_LEN1 length + randomSize #define MESSAGE_LEN1 length + randomSize
unsigned char hash[crypto_secretstream_xchacha20poly1305_ABYTES]; unsigned char hash[crypto_secretstream_xchacha20poly1305_ABYTES];
crypto_generichash(hash, sizeof hash, crypto_generichash(hash, sizeof hash,
@ -230,48 +189,38 @@ void Controller::fillTxJsonParams(QJsonArray& allRecepients, Tx tx)
std::string decryptedMemo(reinterpret_cast<char*>(hash),MESSAGE_LEN1); std::string decryptedMemo(reinterpret_cast<char*>(hash),MESSAGE_LEN1);
std::string encrypt = this->encryptDecrypt(decryptedMemo); std::string encrypt = this->encryptDecrypt(decryptedMemo);
QString randomHashafter1 = QByteArray(reinterpret_cast<const char*>(encrypt.c_str()),encrypt.size()).toHex(); QString randomHashafter1 = QByteArray(reinterpret_cast<const char*>(encrypt.c_str()),encrypt.size()).toHex();
dust.at(i)["memo"] = randomHashafter1; dust.at(i)["memo"] = randomHashafter1.toStdString();
qDebug() << "MIODRAG MEMO FILL IN" << dust.at(i)["address"] << dust.at(i)["memo"] << dust.at(i)["amount"];
} }
*/
for(auto &it: dust) for(auto &it: dust)
{ {
it["amount"] = 0; it["amount"] = 0;
} }
/*
for(uint8_t i = 0; i < 6; i++)
{
dust.at(i)["amount"] = 0;
qDebug() << "MIODRAG AMOUNT FILL IN" << dust.at(i)["address"] << dust.at(i)["memo"] << dust.at(i)["amount"];
}
*/
// For each addr/amt/memo, construct the JSON and also build the confirm dialog box // For each addr/amt/memo, construct the JSON and also build the confirm dialog box
for (int i=0; i < tx.toAddrs.size(); i++) for (int i=0; i < tx.toAddrs.size(); i++)
{ {
auto toAddr = tx.toAddrs[i]; auto toAddr = tx.toAddrs[i];
rec["address"] = toAddr.addr; rec["address"] = toAddr.addr.toStdString();
rec["amount"] = toAddr.amount.toqint64(); rec["amount"] = toAddr.amount.toqint64();
if (Settings::isZAddress(toAddr.addr) && !toAddr.memo.trimmed().isEmpty()) if (Settings::isZAddress(toAddr.addr) && !toAddr.memo.trimmed().isEmpty())
rec["memo"] = toAddr.memo; rec["memo"] = toAddr.memo.toStdString();
allRecepients.push_back(rec) ; allRecepients.push_back(rec);
} }
allRecepients << dust.at(0) allRecepients.insert(std::begin(allRecepients), {
<< dust.at(1) dust.at(0),
<< dust.at(2) dust.at(1),
<< dust.at(3) dust.at(2),
<< dust.at(4) dust.at(3),
<< dust.at(5); dust.at(4),
dust.at(5)
}) ;
qDebug()<<"ADDR DUST";
} }
void Controller::noConnection() void Controller::noConnection()
@ -312,17 +261,17 @@ void Controller::refresh(bool force)
getInfoThenRefresh(force); getInfoThenRefresh(force);
} }
void Controller::processInfo(const QJsonValue& info) void Controller::processInfo(const json& info)
{ {
// Testnet? // Testnet?
QString chainName; QString chainName;
if (!info["chain_name"].isNull()) if (!info["chain_name"].is_null())
{ {
chainName = info["chain_name"].toString(); chainName = QString::fromStdString(info["chain_name"].get<json::string_t>());
Settings::getInstance()->setTestnet(chainName == "test"); Settings::getInstance()->setTestnet(chainName == "test");
} }
QString version = info["version"].toString(); QString version = QString::fromStdString(info["version"].get<json::string_t>());
Settings::getInstance()->sethushdVersion(version); Settings::getInstance()->sethushdVersion(version);
// Recurring pamynets are testnet only // Recurring pamynets are testnet only
@ -337,15 +286,15 @@ void Controller::getInfoThenRefresh(bool force)
static bool prevCallSucceeded = false; static bool prevCallSucceeded = false;
zrpc->fetchInfo([=] (const QJsonValue& reply) { zrpc->fetchInfo([=] (const json& reply) {
prevCallSucceeded = true; prevCallSucceeded = true;
int curBlock = reply["latest_block_height"].toInt(); int curBlock = reply["latest_block_height"].get<json::number_integer_t>();
bool doUpdate = force || (model->getLatestBlock() != curBlock); bool doUpdate = force || (model->getLatestBlock() != curBlock);
int difficulty = reply["difficulty"].toInt(); int difficulty = reply["difficulty"].get<json::number_integer_t>();
int blocks_until_halving= 340000 - curBlock; int blocks_until_halving= 340000 - curBlock;
int halving_days = (blocks_until_halving * 150) / (60 * 60 * 24) ; int halving_days = (blocks_until_halving * 150) / (60 * 60 * 24) ;
int longestchain = reply["longestchain"].toInt(); int longestchain = reply["longestchain"].get<json::number_integer_t>();
int notarized = reply["notarized"].toInt(); int notarized = reply["notarized"].get<json::number_integer_t>();
model->setLatestBlock(curBlock); model->setLatestBlock(curBlock);
if ( if (
@ -391,16 +340,16 @@ void Controller::getInfoThenRefresh(bool force)
); );
} }
ui->Version->setText(reply["version"].toString()); ui->Version->setText(QString::fromStdString(reply["version"].get<json::string_t>()));
ui->Vendor->setText(reply["vendor"].toString()); ui->Vendor->setText(QString::fromStdString(reply["vendor"].get<json::string_t>()));
main->logger->write( main->logger->write(
QString("Refresh. curblock ") % QString::number(curBlock) % ", update=" % (doUpdate ? "true" : "false") QString("Refresh. curblock ") % QString::number(curBlock) % ", update=" % (doUpdate ? "true" : "false")
); );
// Connected, so display checkmark. // Connected, so display checkmark.
auto tooltip = Settings::getInstance()->getSettings().server + "\n" + auto tooltip = Settings::getInstance()->getSettings().server + "\n" +
QLatin1String(QJsonDocument(zrpc->getConnection()->getInfo().toObject()).toJson(QJsonDocument::Compact)); QString::fromStdString(zrpc->getConnection()->getInfo().dump());
QIcon i(":/icons/res/connected.gif"); QIcon i(":/icons/res/connected.gif");
QString chainName = Settings::getInstance()->isTestnet() ? "test" : "main"; QString chainName = Settings::getInstance()->isTestnet() ? "test" : "main";
main->statusLabel->setText(chainName + "(" + QString::number(curBlock) + ")"); main->statusLabel->setText(chainName + "(" + QString::number(curBlock) + ")");
@ -602,16 +551,16 @@ void Controller::getInfoThenRefresh(bool force)
Recurring::getInstance()->processPending(main); Recurring::getInstance()->processPending(main);
// Check if the wallet is locked/encrypted // Check if the wallet is locked/encrypted
zrpc->fetchWalletEncryptionStatus([=] (const QJsonValue& reply) { zrpc->fetchWalletEncryptionStatus([=] (const json& reply) {
bool isEncrypted = reply["encrypted"].toBool(); bool isEncrypted = reply["encrypted"].get<json::boolean_t>();
bool isLocked = reply["locked"].toBool(); bool isLocked = reply["locked"].get<json::boolean_t>();
model->setEncryptionStatus(isEncrypted, isLocked); model->setEncryptionStatus(isEncrypted, isLocked);
}); });
// Get the total supply and render it with thousand decimal // Get the total supply and render it with thousand decimal
zrpc->fetchSupply([=] (const QJsonValue& reply) { zrpc->fetchSupply([=] (const json& reply) {
int supply = reply["supply"].toInt(); int supply = reply["supply"].get<json::number_integer_t>();
int zfunds = reply["zfunds"].toInt(); int zfunds = reply["zfunds"].get<json::number_integer_t>();
int total = reply["total"].toInt(); int total = reply["total"].get<json::number_integer_t>();;
if ( if (
Settings::getInstance()->get_currency_name() == "EUR" || Settings::getInstance()->get_currency_name() == "EUR" ||
Settings::getInstance()->get_currency_name() == "CHF" || Settings::getInstance()->get_currency_name() == "CHF" ||
@ -685,19 +634,19 @@ void Controller::refreshAddresses()
auto newzaddresses = new QList<QString>(); auto newzaddresses = new QList<QString>();
auto newtaddresses = new QList<QString>(); auto newtaddresses = new QList<QString>();
zrpc->fetchAddresses([=] (QJsonValue reply) { zrpc->fetchAddresses([=] (json reply) {
auto zaddrs = reply["z_addresses"].toArray(); auto zaddrs = reply["z_addresses"].get<json::array_t>();
for (const auto& it : zaddrs) for (auto& it : zaddrs)
{ {
auto addr = it.toString(); auto addr = QString::fromStdString(it.get<json::string_t>());
newzaddresses->push_back(addr); newzaddresses->push_back(addr);
} }
model->replaceZaddresses(newzaddresses); model->replaceZaddresses(newzaddresses);
auto taddrs = reply["t_addresses"].toArray(); auto taddrs = reply["t_addresses"].get<json::array_t>();
for (const auto& it : taddrs) for (auto& it : taddrs)
{ {
auto addr = it.toString(); auto addr = QString::fromStdString(it.get<json::string_t>());
if (Settings::isTAddress(addr)) if (Settings::isTAddress(addr))
newtaddresses->push_back(addr); newtaddresses->push_back(addr);
} }
@ -723,17 +672,17 @@ void Controller::updateUI(bool anyUnconfirmed)
}; };
// Function to process reply of the listunspent and z_listunspent API calls, used below. // Function to process reply of the listunspent and z_listunspent API calls, used below.
void Controller::processUnspent(const QJsonValue& reply, QMap<QString, CAmount>* balancesMap, QList<UnspentOutput>* unspentOutputs) { void Controller::processUnspent(const json& reply, QMap<QString, CAmount>* balancesMap, QList<UnspentOutput>* unspentOutputs) {
auto processFn = [=](const QJsonArray& array) { auto processFn = [=](const json& array) {
for (const auto& it : array) for (auto& it : array)
{ {
QString qsAddr = it["address"].toString(); QString qsAddr = QString::fromStdString(it["address"]);
int block = it["created_in_block"].toInt(); int block = it["created_in_block"].get<json::number_unsigned_t>();
QString txid = it["created_in_txid"].toString(); QString txid = QString::fromStdString(it["created_in_txid"]);
CAmount amount = CAmount::fromqint64(it["value"].toDouble()); CAmount amount = CAmount::fromqint64(it["value"].get<json::number_unsigned_t>());
bool spendable = it["unconfirmed_spent"].isNull() && it["spent"].isNull(); // TODO: Wait for 1 confirmations bool spendable = it["unconfirmed_spent"].is_null() && it["spent"].is_null(); // TODO: Wait for 1 confirmations
bool pending = !it["unconfirmed_spent"].isNull(); bool pending = !it["unconfirmed_spent"].is_null();;
unspentOutputs->push_back( unspentOutputs->push_back(
UnspentOutput{ qsAddr, txid, amount, block, spendable, pending } UnspentOutput{ qsAddr, txid, amount, block, spendable, pending }
@ -741,15 +690,15 @@ void Controller::processUnspent(const QJsonValue& reply, QMap<QString, CAmount>*
if (spendable) if (spendable)
{ {
(*balancesMap)[qsAddr] = (*balancesMap)[qsAddr] + (*balancesMap)[qsAddr] = (*balancesMap)[qsAddr] +
CAmount::fromqint64(it["value"].toDouble()); CAmount::fromqint64(it["value"].get<json::number_unsigned_t>());
} }
} }
}; };
processFn(reply["unspent_notes"].toArray()); processFn(reply["unspent_notes"].get<json::array_t>());
processFn(reply["utxos"].toArray()); processFn(reply["utxos"].get<json::array_t>());
processFn(reply["pending_notes"].toArray()); processFn(reply["pending_notes"].get<json::array_t>());
processFn(reply["pending_utxos"].toArray()); processFn(reply["pending_utxos"].get<json::array_t>());
}; };
void Controller::updateUIBalances() void Controller::updateUIBalances()
@ -905,10 +854,10 @@ void Controller::refreshBalances()
return noConnection(); return noConnection();
// 1. Get the Balances // 1. Get the Balances
zrpc->fetchBalance([=] (QJsonValue reply) { zrpc->fetchBalance([=] (json reply) {
CAmount balT = CAmount::fromqint64(reply["tbalance"].toDouble()); CAmount balT = CAmount::fromqint64(reply["tbalance"].get<json::number_unsigned_t>());
CAmount balZ = CAmount::fromqint64(reply["zbalance"].toDouble()); CAmount balZ = CAmount::fromqint64(reply["zbalance"].get<json::number_unsigned_t>());
CAmount balVerified = CAmount::fromqint64(reply["verified_zbalance"].toDouble()); CAmount balVerified = CAmount::fromqint64(reply["verified_zbalance"].get<json::number_unsigned_t>());
model->setBalT(balT); model->setBalT(balT);
model->setBalZ(balZ); model->setBalZ(balZ);
@ -929,7 +878,7 @@ void Controller::refreshBalances()
auto newBalances = new QMap<QString, CAmount>(); auto newBalances = new QMap<QString, CAmount>();
// Call the Transparent and Z unspent APIs serially and then, once they're done, update the UI // Call the Transparent and Z unspent APIs serially and then, once they're done, update the UI
zrpc->fetchUnspent([=] (QJsonValue reply) { zrpc->fetchUnspent([=] (json reply) {
processUnspent(reply, newBalances, newUnspentOutputs); processUnspent(reply, newBalances, newUnspentOutputs);
// Swap out the balances and UTXOs // Swap out the balances and UTXOs
@ -955,37 +904,39 @@ void Controller::refreshTransactions() {
if (!zrpc->haveConnection()) if (!zrpc->haveConnection())
return noConnection(); return noConnection();
zrpc->fetchTransactions([=] (QJsonValue reply) { zrpc->fetchTransactions([=] (json reply) {
QList<TransactionItem> txdata; QList<TransactionItem> txdata;
for (const auto& it : reply.toArray()) for (auto& it : reply.get<json::array_t>()) {
{ {
QString address; QString address;
CAmount total_amount; CAmount total_amount;
QList<TransactionItemDetail> items; QList<TransactionItemDetail> items;
long confirmations; long confirmations;
if (it.toObject()["unconfirmed"].isBool() && it.toObject()["unconfirmed"].toBool()) if (it.find("unconfirmed") != it.end() && it["unconfirmed"].get<json::boolean_t>()) {
confirmations = 0; confirmations = 0;
else }else{
confirmations = model->getLatestBlock() - it.toObject()["block_height"].toInt() + 1; confirmations = model->getLatestBlock() - it["block_height"].get<json::number_integer_t>() + 1;
}
auto txid = it.toObject()["txid"].toString(); auto txid = QString::fromStdString(it["txid"]);
auto datetime = it.toObject()["datetime"].toInt(); auto datetime = it["datetime"].get<json::number_integer_t>();
// First, check if there's outgoing metadata // First, check if there's outgoing metadata
if (!it.toObject()["outgoing_metadata"].isNull()) { if (!it["outgoing_metadata"].is_null()) {
for (auto o: it.toObject()["outgoing_metadata"].toArray()) for (auto o: it["outgoing_metadata"].get<json::array_t>())
{ {
// if (chatModel->getCidByTx(txid) == QString("0xdeadbeef")){ // if (chatModel->getCidByTx(txid) == QString("0xdeadbeef")){
QString address; QString address;
address = o.toObject()["address"].toString(); address = QString::fromStdString(o["address"]);
// Sent items are -ve // Sent items are -ve
CAmount amount = CAmount::fromqint64(-1* o.toObject()["value"].toDouble()); CAmount amount = CAmount::fromqint64(-1* o["value"].get<json::number_unsigned_t>());
// Check for Memos // Check for Memos
@ -1004,8 +955,8 @@ void Controller::refreshTransactions() {
QString cid; QString cid;
QString headerbytes; QString headerbytes;
QString publickey; QString publickey;
if (!o.toObject()["memo"].isNull()) { if (!o["memo"].is_null()) {
memo = o.toObject()["memo"].toString(); memo = QString::fromStdString(o["memo"].get<json::string_t>());
if (memo.startsWith("{")) { if (memo.startsWith("{")) {
try try
@ -1196,16 +1147,16 @@ void Controller::refreshTransactions() {
{ {
{ // Incoming Transaction { // Incoming Transaction
address = (it.toObject()["address"].isNull() ? "" : it.toObject()["address"].toString()); address = (it["address"].is_null() ? "" : QString::fromStdString(it["address"]));
model->markAddressUsed(address); model->markAddressUsed(address);
QString memo; QString memo;
if (!it.toObject()["memo"].isNull()) if (!it["memo"].is_null()) {
memo = it.toObject()["memo"].toString(); memo = QString::fromStdString(it["memo"]);
items.push_back(TransactionItemDetail{ items.push_back(TransactionItemDetail{
address, address,
CAmount::fromqint64(it.toObject()["amount"].toDouble()), CAmount::fromqint64(it["amount"].get<json::number_integer_t>()),
memo memo
}); });
@ -1216,39 +1167,35 @@ void Controller::refreshTransactions() {
txdata.push_back(tx); txdata.push_back(tx);
} }
address = (it.toObject()["address"].isNull() ? "" : it.toObject()["address"].toString());
model->markAddressUsed(address); QString type;
QString publickey;
QString headerbytes;
QString cid;
QString requestZaddr;
QString contactname;
bool isContact;
QString memo; if (!it["memo"].is_null()) {
if (!it.toObject()["memo"].isNull())
memo = it.toObject()["memo"].toString();
QString type;
QString publickey;
QString headerbytes;
QString cid;
QString requestZaddr;
QString contactname;
bool isContact;
if (!it.toObject()["memo"].isNull()) {
if (memo.startsWith("{")) {
try
{
QJsonDocument headermemo = QJsonDocument::fromJson(memo.toUtf8());
cid = headermemo["cid"].toString(); if (memo.startsWith("{")) {
type = headermemo["t"].toString(); try
requestZaddr = headermemo["z"].toString(); {
headerbytes = headermemo["e"].toString(); QJsonDocument headermemo = QJsonDocument::fromJson(memo.toUtf8());
publickey = headermemo["p"].toString();
chatModel->addCid(txid, cid); cid = headermemo["cid"].toString();
chatModel->addrequestZaddr(txid, requestZaddr); type = headermemo["t"].toString();
chatModel->addHeader(txid, headerbytes); requestZaddr = headermemo["z"].toString();
headerbytes = headermemo["e"].toString();
if (publickey.length() > 10){ publickey = headermemo["p"].toString();
main->addPubkey(requestZaddr, publickey);
} chatModel->addCid(txid, cid);
chatModel->addrequestZaddr(txid, requestZaddr);
chatModel->addHeader(txid, headerbytes);
if (publickey.length() > 10){
main->addPubkey(requestZaddr, publickey);
}
} }
catch (...) catch (...)
@ -1315,7 +1262,7 @@ void Controller::refreshTransactions() {
isNotarized = false; isNotarized = false;
} }
int position = it.toObject()["position"].toInt(); int position = it["position"].get<json::number_integer_t>();
int ciphercheck = memo.length() - crypto_secretstream_xchacha20poly1305_ABYTES; int ciphercheck = memo.length() - crypto_secretstream_xchacha20poly1305_ABYTES;
@ -1453,6 +1400,8 @@ void Controller::refreshTransactions() {
DataStore::getChatDataStore()->setData(ChatIDGenerator::getInstance()->generateID(item), item); DataStore::getChatDataStore()->setData(ChatIDGenerator::getInstance()->generateID(item), item);
} }
} }
}
}
} }
} }
@ -1523,7 +1472,7 @@ void Controller::unlockIfEncrypted(std::function<void(void)> cb, std::function<v
return; return;
} }
zrpc->unlockWallet(password, [=](QJsonValue reply) { zrpc->unlockWallet(password, [=](json reply) {
if (isJsonResultSuccess(reply)) if (isJsonResultSuccess(reply))
{ {
cb(); cb();
@ -1536,7 +1485,7 @@ void Controller::unlockIfEncrypted(std::function<void(void)> cb, std::function<v
QMessageBox::critical( QMessageBox::critical(
main, main,
main->tr("Wallet Decryption Failed"), main->tr("Wallet Decryption Failed"),
reply["error"].toString(), QString::fromStdString(reply["error"].get<json::string_t>()),
QMessageBox::Ok QMessageBox::Ok
); );
error(); error();
@ -1586,18 +1535,18 @@ void Controller::executeTransaction(Tx tx,
{ {
unlockIfEncrypted([=] () { unlockIfEncrypted([=] () {
// First, create the json params // First, create the json params
QJsonArray params; json params = json::array();
fillTxJsonParams(params, tx); fillTxJsonParams(params, tx);
// std::cout << std::setw(2) << params << std::endl; std::cout << std::setw(2) << params << std::endl;
zrpc->sendTransaction(QLatin1String(QJsonDocument(params).toJson(QJsonDocument::Compact)), [=](const QJsonValue& reply) { zrpc->sendTransaction(QString::fromStdString(params.dump()), [=](const json& reply) {
if (reply["txid"].isUndefined()) if (reply.find("txid") == reply.end())
{ {
error("", "Couldn't understand Response: " + QLatin1String(QJsonDocument(reply.toObject()).toJson(QJsonDocument::Compact))); error("", "Couldn't understand Response: " + QString::fromStdString(reply.dump()));
} }
else else
{ {
QString txid = reply["txid"].toString(); QString txid = QString::fromStdString(reply["txid"].get<json::string_t>());
submitted(txid); submitted(txid);
} }
}, },
@ -1718,14 +1667,9 @@ void Controller::refreshZECPrice()
{ {
if (reply->error() != QNetworkReply::NoError) if (reply->error() != QNetworkReply::NoError)
{ {
QByteArray raw_reply = reply->readAll(); auto parsed = json::parse(reply->readAll(), nullptr, false);
QString qs_raw_reply = QString::fromUtf8(raw_reply); if (!parsed.is_discarded() && !parsed["error"]["message"].is_null())
QByteArray unescaped_raw_reply = qs_raw_reply.toUtf8(); qDebug() << QString::fromStdString(parsed["error"]["message"]);
QJsonDocument qjd_reply = QJsonDocument::fromJson(unescaped_raw_reply);
QJsonObject parsed = qjd_reply.object();
if (!parsed.isEmpty() && !parsed["error"].toObject()["message"].isNull())
qDebug() << parsed["error"].toObject()["message"].toString();
else else
qDebug() << reply->errorString(); qDebug() << reply->errorString();
@ -1767,11 +1711,8 @@ void Controller::refreshZECPrice()
qDebug() << "No network errors"; qDebug() << "No network errors";
auto all = reply->readAll(); auto all = reply->readAll();
QString qs_raw_reply = QString::fromUtf8(all); auto parsed = json::parse(all, nullptr, false);
QByteArray unescaped_raw_reply = qs_raw_reply.toUtf8(); if (parsed.is_discarded())
QJsonDocument qjd_reply = QJsonDocument::fromJson(unescaped_raw_reply);
QJsonObject parsed = qjd_reply.object();
if (parsed.isEmpty())
{ {
Settings::getInstance()->setZECPrice(0); Settings::getInstance()->setZECPrice(0);
Settings::getInstance()->setEURPrice(0); Settings::getInstance()->setEURPrice(0);
@ -1809,206 +1750,206 @@ void Controller::refreshZECPrice()
return; return;
} }
qDebug() << "Parsed JSON"; qDebug() << "Parsed JSON";
const QJsonObject& item = parsed; const json& item = parsed.get<json::object_t>();
const QJsonObject& hush = item["hush"].toObject(); const json& hush = item["hush"].get<json::object_t>();
if (hush["usd"].toDouble() >= 0) if (hush["usd"] >= 0)
{ {
qDebug() << "Found hush key in price json"; qDebug() << "Found hush key in price json";
qDebug() << "HUSH = $" << QString::number(hush["usd"].toDouble()); qDebug() << "HUSH = $" << QString::number((double)hush["usd"]);
Settings::getInstance()->setZECPrice( hush["usd"].toDouble() ); Settings::getInstance()->setZECPrice( hush["usd"] );
} }
if (hush["eur"].toDouble() >= 0) if (hush["eur"] >= 0)
{ {
qDebug() << "HUSH = €" << QString::number(hush["eur"].toDouble()); qDebug() << "HUSH = €" << QString::number((double)hush["eur"]);
Settings::getInstance()->setEURPrice(hush["eur"].toDouble()); Settings::getInstance()->setEURPrice(hush["eur"]);
} }
if (hush["btc"].toDouble() >= 0) if (hush["btc"] >= 0)
{ {
qDebug() << "HUSH = BTC" << QString::number(hush["btc"].toDouble()); qDebug() << "HUSH = BTC" << QString::number((double)hush["btc"]);
Settings::getInstance()->setBTCPrice( hush["btc"].toDouble()); Settings::getInstance()->setBTCPrice( hush["btc"]);
} }
if (hush["cny"].toDouble() >= 0) if (hush["cny"] >= 0)
{ {
qDebug() << "HUSH = CNY" << QString::number(hush["cny"].toDouble()); qDebug() << "HUSH = CNY" << QString::number((double)hush["cny"]);
Settings::getInstance()->setCNYPrice( hush["cny"].toDouble()); Settings::getInstance()->setCNYPrice( hush["cny"]);
} }
if (hush["rub"].toDouble() >= 0) if (hush["rub"] >= 0)
{ {
qDebug() << "HUSH = RUB" << QString::number(hush["rub"].toDouble()); qDebug() << "HUSH = RUB" << QString::number((double)hush["rub"]);
Settings::getInstance()->setRUBPrice( hush["rub"].toDouble()); Settings::getInstance()->setRUBPrice( hush["rub"]);
} }
if (hush["cad"].toDouble() >= 0) if (hush["cad"] >= 0)
{ {
qDebug() << "HUSH = CAD" << QString::number(hush["cad"].toDouble()); qDebug() << "HUSH = CAD" << QString::number((double)hush["cad"]);
Settings::getInstance()->setCADPrice( hush["cad"].toDouble()); Settings::getInstance()->setCADPrice( hush["cad"]);
} }
if (hush["sgd"].toDouble() >= 0) if (hush["sgd"] >= 0)
{ {
qDebug() << "HUSH = SGD" << QString::number(hush["sgd"].toDouble()); qDebug() << "HUSH = SGD" << QString::number((double)hush["sgd"]);
Settings::getInstance()->setSGDPrice( hush["sgd"].toDouble()); Settings::getInstance()->setSGDPrice( hush["sgd"]);
} }
if (hush["chf"].toDouble() >= 0) if (hush["chf"] >= 0)
{ {
qDebug() << "HUSH = CHF" << QString::number(hush["chf"].toDouble()); qDebug() << "HUSH = CHF" << QString::number((double)hush["chf"]);
Settings::getInstance()->setCHFPrice( hush["chf"].toDouble()); Settings::getInstance()->setCHFPrice( hush["chf"]);
} }
if (hush["inr"].toDouble() >= 0) if (hush["inr"] >= 0)
{ {
qDebug() << "HUSH = INR" << QString::number(hush["inr"].toDouble()); qDebug() << "HUSH = INR" << QString::number((double)hush["inr"]);
Settings::getInstance()->setINRPrice( hush["inr"].toDouble()); Settings::getInstance()->setINRPrice( hush["inr"]);
} }
if (hush["gbp"].toDouble() >= 0) if (hush["gbp"] >= 0)
{ {
qDebug() << "HUSH = GBP" << QString::number(hush["gbp"].toDouble()); qDebug() << "HUSH = GBP" << QString::number((double)hush["gbp"]);
Settings::getInstance()->setGBPPrice( hush["gbp"].toDouble()); Settings::getInstance()->setGBPPrice( hush["gbp"]);
} }
if (hush["aud"].toDouble() >= 0) if (hush["aud"] >= 0)
{ {
qDebug() << "HUSH = AUD" << QString::number(hush["aud"].toDouble()); qDebug() << "HUSH = AUD" << QString::number((double)hush["aud"]);
Settings::getInstance()->setAUDPrice( hush["aud"].toDouble()); Settings::getInstance()->setAUDPrice( hush["aud"]);
} }
if (hush["btc_24h_vol"].toDouble() >= 0) if (hush["btc_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = usd_24h_vol" << QString::number(hush["usd_24h_vol"].toDouble()); qDebug() << "HUSH = usd_24h_vol" << QString::number((double)hush["usd_24h_vol"]);
Settings::getInstance()->setUSDVolume( hush["usd_24h_vol"].toDouble()); Settings::getInstance()->setUSDVolume( hush["usd_24h_vol"]);
} }
if (hush["btc_24h_vol"].toDouble() >= 0) if (hush["btc_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = euro_24h_vol" << QString::number(hush["eur_24h_vol"].toDouble()); qDebug() << "HUSH = euro_24h_vol" << QString::number((double)hush["eur_24h_vol"]);
Settings::getInstance()->setEURVolume( hush["eur_24h_vol"].toDouble()); Settings::getInstance()->setEURVolume( hush["eur_24h_vol"]);
} }
if (hush["btc_24h_vol"].toDouble() >= 0) if (hush["btc_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = btc_24h_vol" << QString::number(hush["btc_24h_vol"].toDouble()); qDebug() << "HUSH = btc_24h_vol" << QString::number((double)hush["btc_24h_vol"]);
Settings::getInstance()->setBTCVolume( hush["btc_24h_vol"].toDouble()); Settings::getInstance()->setBTCVolume( hush["btc_24h_vol"]);
} }
if (hush["cny_24h_vol"].toDouble() >= 0) if (hush["cny_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = cny_24h_vol" << QString::number(hush["cny_24h_vol"].toDouble()); qDebug() << "HUSH = cny_24h_vol" << QString::number((double)hush["cny_24h_vol"]);
Settings::getInstance()->setCNYVolume( hush["cny_24h_vol"].toDouble()); Settings::getInstance()->setCNYVolume( hush["cny_24h_vol"]);
} }
if (hush["rub_24h_vol"].toDouble() >= 0) if (hush["rub_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = rub_24h_vol" << QString::number(hush["rub_24h_vol"].toDouble()); qDebug() << "HUSH = rub_24h_vol" << QString::number((double)hush["rub_24h_vol"]);
Settings::getInstance()->setRUBVolume( hush["rub_24h_vol"].toDouble()); Settings::getInstance()->setRUBVolume( hush["rub_24h_vol"]);
} }
if (hush["cad_24h_vol"].toDouble() >= 0) if (hush["cad_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = cad_24h_vol" << QString::number(hush["cad_24h_vol"].toDouble()); qDebug() << "HUSH = cad_24h_vol" << QString::number((double)hush["cad_24h_vol"]);
Settings::getInstance()->setCADVolume( hush["cad_24h_vol"].toDouble()); Settings::getInstance()->setCADVolume( hush["cad_24h_vol"]);
} }
if (hush["sgd_24h_vol"].toDouble() >= 0) if (hush["sgd_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = sgd_24h_vol" << QString::number(hush["sgd_24h_vol"].toDouble()); qDebug() << "HUSH = sgd_24h_vol" << QString::number((double)hush["sgd_24h_vol"]);
Settings::getInstance()->setSGDVolume( hush["sgd_24h_vol"].toDouble()); Settings::getInstance()->setSGDVolume( hush["sgd_24h_vol"]);
} }
if (hush["chf_24h_vol"].toDouble() >= 0) if (hush["chf_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = chf_24h_vol" << QString::number(hush["chf_24h_vol"].toDouble()); qDebug() << "HUSH = chf_24h_vol" << QString::number((double)hush["chf_24h_vol"]);
Settings::getInstance()->setCHFVolume( hush["chf_24h_vol"].toDouble()); Settings::getInstance()->setCHFVolume( hush["chf_24h_vol"]);
} }
if (hush["inr_24h_vol"].toDouble() >= 0) if (hush["inr_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = inr_24h_vol" << QString::number(hush["inr_24h_vol"].toDouble()); qDebug() << "HUSH = inr_24h_vol" << QString::number((double)hush["inr_24h_vol"]);
Settings::getInstance()->setINRVolume( hush["inr_24h_vol"].toDouble()); Settings::getInstance()->setINRVolume( hush["inr_24h_vol"]);
} }
if (hush["gbp_24h_vol"].toDouble() >= 0) if (hush["gbp_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = gbp_24h_vol" << QString::number(hush["gbp_24h_vol"].toDouble()); qDebug() << "HUSH = gbp_24h_vol" << QString::number((double)hush["gbp_24h_vol"]);
Settings::getInstance()->setGBPVolume( hush["gbp_24h_vol"].toDouble()); Settings::getInstance()->setGBPVolume( hush["gbp_24h_vol"]);
} }
if (hush["aud_24h_vol"].toDouble() >= 0) if (hush["aud_24h_vol"] >= 0)
{ {
qDebug() << "HUSH = aud_24h_vol" << QString::number(hush["aud_24h_vol"].toDouble()); qDebug() << "HUSH = aud_24h_vol" << QString::number((double)hush["aud_24h_vol"]);
Settings::getInstance()->setAUDVolume( hush["aud_24h_vol"].toDouble()); Settings::getInstance()->setAUDVolume( hush["aud_24h_vol"]);
} }
if (hush["usd_market_cap"].toDouble() >= 0) if (hush["usd_market_cap"] >= 0)
{ {
qDebug() << "HUSH = usd_market_cap" << QString::number(hush["usd_market_cap"].toDouble()); qDebug() << "HUSH = usd_market_cap" << QString::number((double)hush["usd_market_cap"]);
Settings::getInstance()->setUSDCAP( hush["usd_market_cap"].toDouble()); Settings::getInstance()->setUSDCAP( hush["usd_market_cap"]);
} }
if (hush["eur_market_cap"].toDouble() >= 0) if (hush["eur_market_cap"] >= 0)
{ {
qDebug() << "HUSH = eur_market_cap" << QString::number(hush["eur_market_cap"].toDouble()); qDebug() << "HUSH = eur_market_cap" << QString::number((double)hush["eur_market_cap"]);
Settings::getInstance()->setEURCAP( hush["eur_market_cap"].toDouble()); Settings::getInstance()->setEURCAP( hush["eur_market_cap"]);
} }
if (hush["btc_market_cap"].toDouble() >= 0) if (hush["btc_market_cap"] >= 0)
{ {
qDebug() << "HUSH = btc_market_cap" << QString::number(hush["btc_market_cap"].toDouble()); qDebug() << "HUSH = btc_market_cap" << QString::number((double)hush["btc_market_cap"]);
Settings::getInstance()->setBTCCAP( hush["btc_market_cap"].toDouble()); Settings::getInstance()->setBTCCAP( hush["btc_market_cap"]);
} }
if (hush["cny_market_cap"].toDouble() >= 0) if (hush["cny_market_cap"] >= 0)
{ {
qDebug() << "HUSH = cny_market_cap" << QString::number(hush["cny_market_cap"].toDouble()); qDebug() << "HUSH = cny_market_cap" << QString::number((double)hush["cny_market_cap"]);
Settings::getInstance()->setCNYCAP( hush["cny_market_cap"].toDouble()); Settings::getInstance()->setCNYCAP( hush["cny_market_cap"]);
} }
if (hush["rub_market_cap"].toDouble() >= 0) if (hush["rub_market_cap"] >= 0)
{ {
qDebug() << "HUSH = rub_market_cap" << QString::number(hush["rub_market_cap"].toDouble()); qDebug() << "HUSH = rub_market_cap" << QString::number((double)hush["rub_market_cap"]);
Settings::getInstance()->setRUBCAP( hush["rub_market_cap"].toDouble()); Settings::getInstance()->setRUBCAP( hush["rub_market_cap"]);
} }
if (hush["cad_market_cap"].toDouble() >= 0) if (hush["cad_market_cap"] >= 0)
{ {
qDebug() << "HUSH = cad_market_cap" << QString::number(hush["cad_market_cap"].toDouble()); qDebug() << "HUSH = cad_market_cap" << QString::number((double)hush["cad_market_cap"]);
Settings::getInstance()->setCADCAP( hush["cad_market_cap"].toDouble()); Settings::getInstance()->setCADCAP( hush["cad_market_cap"]);
} }
if (hush["sgd_market_cap"].toDouble() >= 0) if (hush["sgd_market_cap"] >= 0)
{ {
qDebug() << "HUSH = sgd_market_cap" << QString::number(hush["sgd_market_cap"].toDouble()); qDebug() << "HUSH = sgd_market_cap" << QString::number((double)hush["sgd_market_cap"]);
Settings::getInstance()->setSGDCAP( hush["sgd_market_cap"].toDouble()); Settings::getInstance()->setSGDCAP( hush["sgd_market_cap"]);
} }
if (hush["chf_market_cap"].toDouble() >= 0) if (hush["chf_market_cap"] >= 0)
{ {
qDebug() << "HUSH = chf_market_cap" << QString::number(hush["chf_market_cap"].toDouble()); qDebug() << "HUSH = chf_market_cap" << QString::number((double)hush["chf_market_cap"]);
Settings::getInstance()->setCHFCAP( hush["chf_market_cap"].toDouble()); Settings::getInstance()->setCHFCAP( hush["chf_market_cap"]);
} }
if (hush["inr_market_cap"].toDouble() >= 0) if (hush["inr_market_cap"] >= 0)
{ {
qDebug() << "HUSH = inr_market_cap" << QString::number(hush["inr_market_cap"].toDouble()); qDebug() << "HUSH = inr_market_cap" << QString::number((double)hush["inr_market_cap"]);
Settings::getInstance()->setINRCAP( hush["inr_market_cap"].toDouble()); Settings::getInstance()->setINRCAP( hush["inr_market_cap"]);
} }
if (hush["gbp_market_cap"].toDouble() >= 0) if (hush["gbp_market_cap"] >= 0)
{ {
qDebug() << "HUSH = gbp_market_cap" << QString::number(hush["gbp_market_cap"].toDouble()); qDebug() << "HUSH = gbp_market_cap" << QString::number((double)hush["gbp_market_cap"]);
Settings::getInstance()->setGBPCAP( hush["gbp_market_cap"].toDouble()); Settings::getInstance()->setGBPCAP( hush["gbp_market_cap"]);
} }
if (hush["aud_market_cap"].toDouble() >= 0) if (hush["aud_market_cap"] >= 0)
{ {
qDebug() << "HUSH = aud_market_cap" << QString::number(hush["aud_market_cap"].toDouble()); qDebug() << "HUSH = aud_market_cap" << QString::number((double)hush["aud_market_cap"]);
Settings::getInstance()->setAUDCAP( hush["aud_market_cap"].toDouble()); Settings::getInstance()->setAUDCAP( hush["aud_market_cap"]);
} }
return; return;
@ -2088,7 +2029,7 @@ void Controller::shutdownhushd()
} }
bool finished = false; bool finished = false;
zrpc->saveWallet([&] (QJsonValue) { zrpc->saveWallet([&] (json) {
if (!finished) if (!finished)
d.accept(); d.accept();
finished = true; finished = true;

34
src/controller.h

@ -20,6 +20,8 @@
#include "Model/ContactItem.h" #include "Model/ContactItem.h"
#include "contactmodel.h" #include "contactmodel.h"
using json = nlohmann::json;
struct WatchedTx { struct WatchedTx {
QString opid; QString opid;
Tx tx; Tx tx;
@ -90,7 +92,7 @@ public:
const std::function<void(QString txid)> submitted, const std::function<void(QString txid)> submitted,
const std::function<void(QString txid, QString errStr)> error); const std::function<void(QString txid, QString errStr)> error);
void fillTxJsonParams(QJsonArray &params, Tx tx); void fillTxJsonParams(json& params, Tx tx);
const TxTableModel* getTransactionsModel() { return transactionsTableModel; } const TxTableModel* getTransactionsModel() { return transactionsTableModel; }
@ -98,58 +100,58 @@ public:
void noConnection(); void noConnection();
bool isEmbedded() { return ehushd != nullptr; } bool isEmbedded() { return ehushd != nullptr; }
void encryptWallet(QString password, const std::function<void(QJsonValue)>& cb) { void encryptWallet(QString password, const std::function<void(json)>& cb) {
zrpc->encryptWallet(password, cb); zrpc->encryptWallet(password, cb);
} }
void removeWalletEncryption(QString password, const std::function<void(QJsonValue)>& cb) { void removeWalletEncryption(QString password, const std::function<void(json)>& cb) {
zrpc->removeWalletEncryption(password, cb); } zrpc->removeWalletEncryption(password, cb); }
void saveWallet(const std::function<void(QJsonValue)>& cb) { zrpc->saveWallet(cb); } void saveWallet(const std::function<void(json)>& cb) { zrpc->saveWallet(cb); }
void clearWallet(const std::function<void(QJsonValue)>& cb) { zrpc->clearWallet(cb); } void clearWallet(const std::function<void(json)>& cb) { zrpc->clearWallet(cb); }
void createNewZaddr(bool sapling, const std::function<void(QJsonValue)>& cb) { void createNewZaddr(bool sapling, const std::function<void(json)>& cb) {
unlockIfEncrypted([=] () { unlockIfEncrypted([=] () {
zrpc->createNewZaddr(sapling, cb); zrpc->createNewZaddr(sapling, cb);
}, [=](){}); }, [=](){});
} }
void createNewTaddr(const std::function<void(QJsonValue)>& cb) { void createNewTaddr(const std::function<void(json)>& cb) {
unlockIfEncrypted([=] () { unlockIfEncrypted([=] () {
zrpc->createNewTaddr(cb); zrpc->createNewTaddr(cb);
}, [=](){}); }, [=](){});
} }
void createNewSietchZaddr(const std::function<void(QJsonValue)>& cb) { void createNewSietchZaddr(const std::function<void(json)>& cb) {
unlockIfEncrypted([=] () { unlockIfEncrypted([=] () {
zrpc->createNewSietchZaddr(cb); zrpc->createNewSietchZaddr(cb);
}, [=](){}); }, [=](){});
} }
void fetchPrivKey(QString addr, const std::function<void(QJsonValue)>& cb) { void fetchPrivKey(QString addr, const std::function<void(json)>& cb) {
unlockIfEncrypted([=] () { unlockIfEncrypted([=] () {
zrpc->fetchPrivKey(addr, cb); zrpc->fetchPrivKey(addr, cb);
}, },
[=]() { [=]() {
cb(QJsonObject({ {"error", "Failed to unlock wallet"} }) ); cb({ {"error", "Failed to unlock wallet"} });
}); });
} }
void fetchAllPrivKeys(const std::function<void(QJsonValue)> cb) { void fetchAllPrivKeys(const std::function<void(json)> cb) {
unlockIfEncrypted([=] () { unlockIfEncrypted([=] () {
zrpc->fetchAllPrivKeys(cb); zrpc->fetchAllPrivKeys(cb);
}, },
[=]() { [=]() {
cb(QJsonObject({ {"error", "Failed to unlock wallet"} })); cb({ {"error", "Failed to unlock wallet"} });
}); });
} }
void fetchSeed(const std::function<void(QJsonValue)> cb) { void fetchSeed(const std::function<void(json)> cb) {
unlockIfEncrypted([=] () { unlockIfEncrypted([=] () {
zrpc->fetchSeed(cb); zrpc->fetchSeed(cb);
}, },
[=]() { [=]() {
cb(QJsonObject({ {"error", "Failed to unlock wallet"} })); cb({ {"error", "Failed to unlock wallet"} });
}); });
} }
@ -162,12 +164,12 @@ public:
private: private:
void processInfo(const QJsonValue&); void processInfo(const json&);
void refreshBalances(); void refreshBalances();
void refreshTransactions(); void refreshTransactions();
void processUnspent (const QJsonValue& reply, QMap<QString, CAmount>* newBalances, QList<UnspentOutput>* newUnspentOutputs); void processUnspent (const json& reply, QMap<QString, CAmount>* newBalances, QList<UnspentOutput>* newUnspentOutputs);
void updateUI (bool anyUnconfirmed); void updateUI (bool anyUnconfirmed);
void updateUIBalances (); void updateUIBalances ();

22
src/firsttimewizard.cpp

@ -196,14 +196,11 @@ void NewSeedPage::initializePage() {
char* resp = litelib_initialize_new(parent->server.toStdString().c_str()); char* resp = litelib_initialize_new(parent->server.toStdString().c_str());
QString reply = litelib_process_response(resp); QString reply = litelib_process_response(resp);
QByteArray ba_reply = reply.toUtf8(); auto parsed = json::parse(reply.toStdString().c_str(), nullptr, false);
QJsonDocument jd_reply = QJsonDocument::fromJson(ba_reply); if (parsed.is_discarded() || parsed.is_null() || parsed.find("seed") == parsed.end()) {
QJsonObject parsed = jd_reply.object();
if (parsed.isEmpty() || parsed["seed"].isNull()) {
form.txtSeed->setPlainText(tr("Error creating a wallet") + "\n" + reply); form.txtSeed->setPlainText(tr("Error creating a wallet") + "\n" + reply);
} else { } else {
QString seed = parsed["seed"].toString(); QString seed = QString::fromStdString(parsed["seed"].get<json::string_t>());
form.txtSeed->setPlainText(seed); form.txtSeed->setPlainText(seed);
} }
@ -216,11 +213,9 @@ bool NewSeedPage::validatePage() {
char* resp = litelib_execute("save", ""); char* resp = litelib_execute("save", "");
QString reply = litelib_process_response(resp); QString reply = litelib_process_response(resp);
QByteArray ba_reply = reply.toUtf8(); auto parsed = json::parse(reply.toStdString().c_str(), nullptr, false);
QJsonDocument jd_reply = QJsonDocument::fromJson(ba_reply); if (parsed.is_discarded() || parsed.is_null() || parsed.find("result") == parsed.end()) {
QJsonObject parsed = jd_reply.object();
if (parsed.isEmpty() || parsed["result"].isNull()) {
QMessageBox::warning(this, tr("Failed to save wallet"), QMessageBox::warning(this, tr("Failed to save wallet"),
tr("Couldn't save the wallet") + "\n" + reply, tr("Couldn't save the wallet") + "\n" + reply,
QMessageBox::Ok); QMessageBox::Ok);
@ -289,11 +284,8 @@ qint64 number = number_str.toUInt();
char* resp = litelib_execute("save", ""); char* resp = litelib_execute("save", "");
QString reply = litelib_process_response(resp); QString reply = litelib_process_response(resp);
QByteArray ba_reply = reply.toUtf8(); auto parsed = json::parse(reply.toStdString().c_str(), nullptr, false);
QJsonDocument jd_reply = QJsonDocument::fromJson(ba_reply); if (parsed.is_discarded() || parsed.is_null() || parsed.find("result") == parsed.end()) {
QJsonObject parsed = jd_reply.object();
if (parsed.isEmpty() || parsed["result"].isNull()) {
QMessageBox::warning(this, tr("Failed to save wallet"), QMessageBox::warning(this, tr("Failed to save wallet"),
tr("Couldn't save the wallet") + "\n" + reply, tr("Couldn't save the wallet") + "\n" + reply,
QMessageBox::Ok); QMessageBox::Ok);

40
src/liteinterface.cpp

@ -20,7 +20,7 @@ bool LiteInterface::haveConnection() {
return conn != nullptr; return conn != nullptr;
} }
void LiteInterface::fetchAddresses(const std::function<void(QJsonValue)>& cb) { void LiteInterface::fetchAddresses(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
@ -28,21 +28,21 @@ void LiteInterface::fetchAddresses(const std::function<void(QJsonValue)>& cb) {
} }
void LiteInterface::fetchUnspent(const std::function<void(QJsonValue)>& cb) { void LiteInterface::fetchUnspent(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("notes", "", cb); conn->doRPCWithDefaultErrorHandling("notes", "", cb);
} }
void LiteInterface::createNewZaddr(bool, const std::function<void(QJsonValue)>& cb) { void LiteInterface::createNewZaddr(bool, const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("new", "zs", cb); conn->doRPCWithDefaultErrorHandling("new", "zs", cb);
} }
void LiteInterface::createNewSietchZaddr(const std::function<void(QJsonValue)>& cb) { void LiteInterface::createNewSietchZaddr(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
@ -50,70 +50,70 @@ void LiteInterface::createNewSietchZaddr(const std::function<void(QJsonValue)>&
} }
void LiteInterface::createNewTaddr(const std::function<void(QJsonValue)>& cb) { void LiteInterface::createNewTaddr(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("new", "R", cb); conn->doRPCWithDefaultErrorHandling("new", "R", cb);
} }
void LiteInterface::fetchPrivKey(QString addr, const std::function<void(QJsonValue)>& cb) { void LiteInterface::fetchPrivKey(QString addr, const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("export", addr, cb); conn->doRPCWithDefaultErrorHandling("export", addr, cb);
} }
void LiteInterface::fetchSeed(const std::function<void(QJsonValue)>& cb) { void LiteInterface::fetchSeed(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("seed", "", cb); conn->doRPCWithDefaultErrorHandling("seed", "", cb);
} }
void LiteInterface::fetchBalance(const std::function<void(QJsonValue)>& cb) { void LiteInterface::fetchBalance(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("balance", "", cb); conn->doRPCWithDefaultErrorHandling("balance", "", cb);
} }
void LiteInterface::fetchTransactions(const std::function<void(QJsonValue)>& cb) { void LiteInterface::fetchTransactions(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("list", "", cb); conn->doRPCWithDefaultErrorHandling("list", "", cb);
} }
void LiteInterface::saveWallet(const std::function<void(QJsonValue)>& cb) { void LiteInterface::saveWallet(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("save", "", cb); conn->doRPCWithDefaultErrorHandling("save", "", cb);
} }
void LiteInterface::clearWallet(const std::function<void(QJsonValue)>& cb) { void LiteInterface::clearWallet(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("clear", "", cb); conn->doRPCWithDefaultErrorHandling("clear", "", cb);
} }
void LiteInterface::unlockWallet(QString password, const std::function<void(QJsonValue)>& cb) { void LiteInterface::unlockWallet(QString password, const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("unlock", password, cb); conn->doRPCWithDefaultErrorHandling("unlock", password, cb);
} }
void LiteInterface::fetchWalletEncryptionStatus(const std::function<void(QJsonValue)>& cb) { void LiteInterface::fetchWalletEncryptionStatus(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
conn->doRPCWithDefaultErrorHandling("encryptionstatus", "", cb); conn->doRPCWithDefaultErrorHandling("encryptionstatus", "", cb);
} }
void LiteInterface::encryptWallet(QString password, const std::function<void(QJsonValue)>& cb) { void LiteInterface::encryptWallet(QString password, const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
@ -121,7 +121,7 @@ void LiteInterface::encryptWallet(QString password, const std::function<void(QJs
} }
void LiteInterface::removeWalletEncryption(QString password, const std::function<void(QJsonValue)>& cb) { void LiteInterface::removeWalletEncryption(QString password, const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
@ -129,7 +129,7 @@ void LiteInterface::removeWalletEncryption(QString password, const std::function
} }
void LiteInterface::sendTransaction(QString params, const std::function<void(QJsonValue)>& cb, void LiteInterface::sendTransaction(QString params, const std::function<void(json)>& cb,
const std::function<void(QString)>& err) { const std::function<void(QString)>& err) {
if (conn == nullptr) if (conn == nullptr)
return; return;
@ -137,7 +137,7 @@ void LiteInterface::sendTransaction(QString params, const std::function<void(QJs
conn->doRPC("send", params, cb, err); conn->doRPC("send", params, cb, err);
} }
void LiteInterface::fetchInfo(const std::function<void(QJsonValue)>& cb, void LiteInterface::fetchInfo(const std::function<void(json)>& cb,
const std::function<void(QString)>& err) { const std::function<void(QString)>& err) {
if (conn == nullptr) if (conn == nullptr)
return; return;
@ -145,7 +145,7 @@ void LiteInterface::fetchInfo(const std::function<void(QJsonValue)>& cb,
conn->doRPC("info", "", cb, err); conn->doRPC("info", "", cb, err);
} }
void LiteInterface::fetchSupply(const std::function<void(QJsonValue)>& cb) { void LiteInterface::fetchSupply(const std::function<void(json)>& cb) {
if (conn == nullptr) if (conn == nullptr)
return; return;
@ -153,7 +153,7 @@ void LiteInterface::fetchSupply(const std::function<void(QJsonValue)>& cb) {
} }
void LiteInterface::fetchLatestBlock(const std::function<void(QJsonValue)>& cb, void LiteInterface::fetchLatestBlock(const std::function<void(json)>& cb,
const std::function<void(QString)>& err) { const std::function<void(QString)>& err) {
if (conn == nullptr) if (conn == nullptr)
return; return;
@ -166,7 +166,7 @@ void LiteInterface::fetchLatestBlock(const std::function<void(QJsonValue)>& cb,
* combine the result, and call the callback with a single list containing both the t-addr and z-addr * combine the result, and call the callback with a single list containing both the t-addr and z-addr
* private keys * private keys
*/ */
void LiteInterface::fetchAllPrivKeys(const std::function<void(QJsonValue)> cb) { void LiteInterface::fetchAllPrivKeys(const std::function<void(json)> cb) {
if (conn == nullptr) { if (conn == nullptr) {
// No connection, just return // No connection, just return
return; return;

42
src/liteinterface.h

@ -6,6 +6,8 @@
#include "camount.h" #include "camount.h"
#include "connection.h" #include "connection.h"
using json = nlohmann::json;
// Since each transaction can contain multiple outputs, we separate them out individually // Since each transaction can contain multiple outputs, we separate them out individually
// into a struct with address, amount, memo // into a struct with address, amount, memo
struct TransactionItemDetail { struct TransactionItemDetail {
@ -36,43 +38,43 @@ public:
void setConnection(Connection* c); void setConnection(Connection* c);
Connection* getConnection() { return conn; } Connection* getConnection() { return conn; }
void fetchUnspent (const std::function<void(QJsonValue)>& cb); void fetchUnspent (const std::function<void(json)>& cb);
void fetchTransactions (const std::function<void(QJsonValue)>& cb); void fetchTransactions (const std::function<void(json)>& cb);
void fetchAddresses (const std::function<void(QJsonValue)>& cb); void fetchAddresses (const std::function<void(json)>& cb);
void fetchInfo(const std::function<void(QJsonValue)>& cb, void fetchInfo(const std::function<void(json)>& cb,
const std::function<void(QString)>& err); const std::function<void(QString)>& err);
void fetchLatestBlock(const std::function<void(QJsonValue)>& cb, void fetchLatestBlock(const std::function<void(json)>& cb,
const std::function<void(QString)>& err); const std::function<void(QString)>& err);
void fetchBalance(const std::function<void(QJsonValue)>& cb); void fetchBalance(const std::function<void(json)>& cb);
void createNewZaddr(bool sapling, const std::function<void(QJsonValue)>& cb); void createNewZaddr(bool sapling, const std::function<void(json)>& cb);
void createNewTaddr(const std::function<void(QJsonValue)>& cb); void createNewTaddr(const std::function<void(json)>& cb);
void createNewSietchZaddr(const std::function<void(QJsonValue)>& cb); void createNewSietchZaddr(const std::function<void(json)>& cb);
void fetchPrivKey(QString addr, const std::function<void(QJsonValue)>& cb); void fetchPrivKey(QString addr, const std::function<void(json)>& cb);
void fetchAllPrivKeys(const std::function<void(QJsonValue)>); void fetchAllPrivKeys(const std::function<void(json)>);
void fetchSeed(const std::function<void(QJsonValue)>&); void fetchSeed(const std::function<void(json)>&);
void saveWallet(const std::function<void(QJsonValue)>& cb); void saveWallet(const std::function<void(json)>& cb);
void clearWallet(const std::function<void(QJsonValue)>& cb); void clearWallet(const std::function<void(json)>& cb);
void fetchWalletEncryptionStatus(const std::function<void(QJsonValue)>& cb); void fetchWalletEncryptionStatus(const std::function<void(json)>& cb);
void fetchSupply(const std::function<void(QJsonValue)>& cb); void fetchSupply(const std::function<void(json)>& cb);
void encryptWallet(QString password, const std::function<void(QJsonValue)>& cb); void encryptWallet(QString password, const std::function<void(json)>& cb);
void unlockWallet(QString password, const std::function<void(QJsonValue)>& cb); void unlockWallet(QString password, const std::function<void(json)>& cb);
void removeWalletEncryption(QString password, const std::function<void(QJsonValue)>& cb); void removeWalletEncryption(QString password, const std::function<void(json)>& cb);
//void importZPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb); //void importZPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb);
//void importTPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb); //void importTPrivKey(QString addr, bool rescan, const std::function<void(json)>& cb);
void sendTransaction(QString params, const std::function<void(QJsonValue)>& cb, const std::function<void(QString)>& err); void sendTransaction(QString params, const std::function<void(json)>& cb, const std::function<void(QString)>& err);
private: private:
Connection* conn = nullptr; Connection* conn = nullptr;

34
src/mainwindow.cpp

@ -41,6 +41,8 @@
#include <QGuiApplication> #include <QGuiApplication>
#include <QKeyEvent> #include <QKeyEvent>
using json = nlohmann::json;
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
auto dirwallet = QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)).filePath("silentdragonlite/silentdragonlite-wallet.dat"); auto dirwallet = QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)).filePath("silentdragonlite/silentdragonlite-wallet.dat");
@ -181,14 +183,14 @@ MainWindow::MainWindow(QWidget *parent) :
Settings::saveRestore(&dialog); Settings::saveRestore(&dialog);
rpc->fetchSeed([&](QJsonValue reply) { rpc->fetchSeed([=](json reply) {
if (isJsonError(reply)) { if (isJsonError(reply)) {
return; return;
} }
restoreSeed.seed->setReadOnly(true); restoreSeed.seed->setReadOnly(true);
restoreSeed.seed->setLineWrapMode(QPlainTextEdit::LineWrapMode::NoWrap); restoreSeed.seed->setLineWrapMode(QPlainTextEdit::LineWrapMode::NoWrap);
QString seedJson = QLatin1String(QJsonDocument(reply.toObject()).toJson(QJsonDocument::Compact)); QString seedJson = QString::fromStdString(reply.get<json::string_t>());
int startPos = seedJson.indexOf("seed") +7; int startPos = seedJson.indexOf("seed") +7;
int endPos = seedJson.indexOf("}") -1; int endPos = seedJson.indexOf("}") -1;
int length = endPos - startPos; int length = endPos - startPos;
@ -1104,7 +1106,7 @@ void MainWindow::exportSeed() {
rpc->fetchSeed([=](QJsonValue reply) { rpc->fetchSeed([=](json reply) {
if (isJsonError(reply)) { if (isJsonError(reply)) {
return; return;
} }
@ -1122,7 +1124,7 @@ void MainWindow::exportSeed() {
pui.privKeyTxt->setReadOnly(true); pui.privKeyTxt->setReadOnly(true);
pui.privKeyTxt->setLineWrapMode(QPlainTextEdit::LineWrapMode::NoWrap); pui.privKeyTxt->setLineWrapMode(QPlainTextEdit::LineWrapMode::NoWrap);
pui.privKeyTxt->setPlainText(QLatin1String(QJsonDocument(reply.toObject()).toJson(QJsonDocument::Compact))); pui.privKeyTxt->setPlainText(QString::fromStdString(reply.dump()));
pui.helpLbl->setText(tr("This is your wallet seed. Please back it up carefully and safely.")); pui.helpLbl->setText(tr("This is your wallet seed. Please back it up carefully and safely."));
@ -1176,14 +1178,14 @@ void MainWindow::exportKeys(QString addr) {
bool allKeys = addr.isEmpty() ? true : false; bool allKeys = addr.isEmpty() ? true : false;
auto fnUpdateUIWithKeys = [=](QJsonValue reply) { auto fnUpdateUIWithKeys = [=](json reply) {
if (isJsonError(reply)) { if (isJsonError(reply)) {
return; return;
} }
if (reply.isNull() || !reply.isArray()) { if (reply.is_discarded() || !reply.is_array()) {
QMessageBox::critical(this, tr("Error getting private keys"), QMessageBox::critical(this, tr("Error getting private keys"),
tr("Error loading private keys: ") + QLatin1String(QJsonDocument(reply.toObject()).toJson(QJsonDocument::Compact)), tr("Error loading private keys: ") + QString::fromStdString(reply.dump()),
QMessageBox::Ok); QMessageBox::Ok);
return; return;
} }
@ -1222,8 +1224,8 @@ void MainWindow::exportKeys(QString addr) {
}); });
QString allKeysTxt; QString allKeysTxt;
for (auto i : reply.toArray()) { for (auto i : reply.get<json::array_t>()) {
allKeysTxt = allKeysTxt % i.toObject()["private_key"].toString() % " # addr=" % i.toObject()["address"].toString() % "\n"; allKeysTxt = allKeysTxt % QString::fromStdString(i["private_key"]) % " # addr=" % QString::fromStdString(i["address"]) % "\n";
} }
pui.privKeyTxt->setPlainText(allKeysTxt); pui.privKeyTxt->setPlainText(allKeysTxt);
@ -1330,7 +1332,7 @@ void MainWindow::setupTransactionsTab() {
// Set up context menu on transactions tab // Set up context menu on transactions tab
auto theme = Settings::getInstance()->get_theme_name(); auto theme = Settings::getInstance()->get_theme_name();
if (theme == "Dark" || theme == "Midnight") { if (theme == "Dark" || theme == "Midnight") {
ui->listChat->setStyleSheet("background-image: url(:/icons/res/sdlogo.png) ;background-attachment: fixed ;background-position: center center ;background-repeat: no-repeat;background-size: cover"); ui->listChat->setStyleSheet("background-image: url(:/icons/res/SDLogo.png) ;background-attachment: fixed ;background-position: center center ;background-repeat: no-repeat;background-size: cover");
} }
if (theme == "Default") {ui->listChat->setStyleSheet("background-image: url(:/icons/res/sdlogo2.png) ;background-attachment: fixed ;background-position: center center ;background-repeat: no-repeat;background-size: cover");} if (theme == "Default") {ui->listChat->setStyleSheet("background-image: url(:/icons/res/sdlogo2.png) ;background-attachment: fixed ;background-position: center center ;background-repeat: no-repeat;background-size: cover");}
@ -2304,8 +2306,8 @@ void MainWindow::updateContacts()
} }
void MainWindow::addNewZaddr(bool sapling) { void MainWindow::addNewZaddr(bool sapling) {
rpc->createNewZaddr(sapling, [=] (QJsonValue reply) { rpc->createNewZaddr(sapling, [=] (json reply) {
QString addr = reply.toArray()[0].toString(); QString addr = QString::fromStdString(reply.get<json::array_t>()[0]);
// Make sure the RPC class reloads the z-addrs for future use // Make sure the RPC class reloads the z-addrs for future use
rpc->refreshAddresses(); rpc->refreshAddresses();
@ -2355,8 +2357,8 @@ std::function<void(bool)> MainWindow::addZAddrsToComboList(bool sapling) {
void MainWindow::setupReceiveTab() { void MainWindow::setupReceiveTab() {
auto addNewTAddr = [=] () { auto addNewTAddr = [=] () {
rpc->createNewTaddr([=] (QJsonValue reply) { rpc->createNewTaddr([=] (json reply) {
QString addr = reply.toArray()[0].toString(); QString addr = QString::fromStdString(reply.get<json::array_t>()[0]);
// Make sure the RPC class reloads the t-addrs for future use // Make sure the RPC class reloads the t-addrs for future use
rpc->refreshAddresses(); rpc->refreshAddresses();
@ -2731,8 +2733,8 @@ void MainWindow::on_givemeZaddr_clicked()
{ {
bool sapling = true; bool sapling = true;
rpc->createNewZaddr(sapling, [=] (QJsonValue reply) { rpc->createNewZaddr(sapling, [=] (json reply) {
QString hushchataddr = reply.toArray()[0].toString(); QString hushchataddr = QString::fromStdString(reply.get<json::array_t>()[0]);
QClipboard *zaddr_Clipboard = QApplication::clipboard(); QClipboard *zaddr_Clipboard = QApplication::clipboard();
zaddr_Clipboard ->setText(hushchataddr); zaddr_Clipboard ->setText(hushchataddr);
QMessageBox::information(this, "Your new HushChat address was copied to your clipboard!",hushchataddr); QMessageBox::information(this, "Your new HushChat address was copied to your clipboard!",hushchataddr);

2
src/mainwindow.h

@ -7,6 +7,8 @@
#include "recurring.h" #include "recurring.h"
#include "firsttimewizard.h" #include "firsttimewizard.h"
using json = nlohmann::json;
// Forward declare to break circular dependency. // Forward declare to break circular dependency.
class Controller; class Controller;
class Settings; class Settings;

1
src/precompiled.h

@ -74,6 +74,7 @@
#include <QPainterPath> #include <QPainterPath>
#include "3rdparty/qrcode/QrCode.hpp" #include "3rdparty/qrcode/QrCode.hpp"
#include "3rdparty/json/json.hpp"
#define SODIUM_STATIC #define SODIUM_STATIC
#include "3rdparty/sodium.h" #include "3rdparty/sodium.h"

2
src/sendtab.cpp

@ -8,6 +8,8 @@
#include "controller.h" #include "controller.h"
#include "recurring.h" #include "recurring.h"
using json = nlohmann::json;
void MainWindow::setupSendTab() { void MainWindow::setupSendTab() {
// Create the validator for send to/amount fields // Create the validator for send to/amount fields

11
src/settings.h

@ -4,6 +4,8 @@
#include "precompiled.h" #include "precompiled.h"
#include "camount.h" #include "camount.h"
using json = nlohmann::json;
struct Config { struct Config {
QString server; QString server;
}; };
@ -221,12 +223,13 @@ private:
}; };
inline bool isJsonResultSuccess(const QJsonValue& res) { inline bool isJsonResultSuccess(const json& res) {
return res.toObject()["result"].toString() == "success"; return res.find("result") != res.end() &&
QString::fromStdString(res["result"].get<json::string_t>()) == "success";
} }
inline bool isJsonError(const QJsonValue& res) { inline bool isJsonError(const json& res) {
return !res.toObject()["error"].isNull(); return res.find("error") != res.end();
} }

8
src/websockets.cpp

@ -735,9 +735,9 @@ void AppDataServer::processSendTx(QJsonObject sendTx, MainWindow* mainwindow, st
return; return;
} }
QJsonArray params; json params = json::array();
mainwindow->getRPC()->fillTxJsonParams(params, tx); mainwindow->getRPC()->fillTxJsonParams(params, tx);
//std::cout << std::setw(2) << params << std::endl; std::cout << std::setw(2) << params << std::endl;
// And send the Tx // And send the Tx
mainwindow->getRPC()->executeTransaction(tx, mainwindow->getRPC()->executeTransaction(tx,
@ -835,9 +835,9 @@ void AppDataServer::processSendManyTx(QJsonObject sendmanyTx, MainWindow* mainwi
return; return;
} }
QJsonArray params; json params = json::array();
mainwindow->getRPC()->fillTxJsonParams(params, tx); mainwindow->getRPC()->fillTxJsonParams(params, tx);
//std::cout << std::setw(2) << params << std::endl; std::cout << std::setw(2) << params << std::endl;
// And send the Tx // And send the Tx
mainwindow->getRPC()->executeTransaction(tx, mainwindow->getRPC()->executeTransaction(tx,

Loading…
Cancel
Save