/src/core/moneychanger.cpp
C++ | 8161 lines | 3371 code | 1077 blank | 3713 comment | 608 complexity | cce05d675dee3ab5a9537a61bc3a4fb3 MD5 | raw file
Possible License(s): LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- /*
- * MoneyChanger
- * moneychanger.cpp
- *
- * File organized as follows:
- *
- * /-- Constructor (Lengthy)--/
- * /-- Destructor --/
- *
- * /-- Systray Functions --/
- *
- * /-- Menu Dialog Functions --/
- *
- */
- #ifndef __STABLE_HPP__
- #include <core/stable.hpp>
- #endif
- #include <core/moneychanger.hpp>
- #include <core/handlers/DBHandler.hpp>
- #include <core/handlers/contacthandler.hpp>
- #include <core/handlers/modeltradearchive.hpp>
- #include <gui/widgets/compose.hpp>
- #include <gui/widgets/overridecursor.hpp>
- #include <gui/widgets/editdetails.hpp>
- #include <gui/widgets/requestdlg.hpp>
- #include <gui/widgets/dlgchooser.hpp>
- #include <gui/widgets/senddlg.hpp>
- #include <gui/widgets/proposeplandlg.hpp>
- #include <gui/widgets/createinsurancecompany.hpp>
- #include <gui/widgets/wizardconfirmsmartcontract.hpp>
- #include <gui/widgets/wizardrunsmartcontract.hpp>
- #include <gui/widgets/wizardpartyacct.hpp>
- #include <gui/widgets/settings.hpp>
- #include <gui/ui/dlgimport.hpp>
- #include <gui/ui/dlglog.hpp>
- #include <gui/ui/dlgmenu.hpp>
- #include <gui/ui/dlgmarkets.hpp>
- #include <gui/ui/dlgtradearchive.hpp>
- #include <gui/ui/dlgencrypt.hpp>
- #include <gui/ui/dlgdecrypt.hpp>
- #include <gui/ui/dlginbailment.hpp>
- #include <gui/ui/dlgpairnode.hpp>
- #include <gui/ui/dlgpassphrasemanager.hpp>
- #include <gui/ui/messages.hpp>
- #include <gui/ui/payments.hpp>
- #include <gui/ui/agreements.hpp>
- #include <gui/ui/activity.hpp>
- #include <gui/ui/getstringdialog.hpp>
- #include <opentxs/opentxs.hpp>
- #include <QMenu>
- #include <QApplication>
- #include <QFile>
- #include <QDateTime>
- #include <QDebug>
- #include <QMessageBox>
- #include <QSystemTrayIcon>
- #include <QTimer>
- #include <QRegExp>
- #include <QFlags>
- #include <chrono>
- #include <functional>
- #include <sstream>
- #include <utility>
- #include <memory>
- template class opentxs::Pimpl<opentxs::network::zeromq::PairEventCallback>;
- template class std::shared_ptr<const opentxs::OTPayment>;
- bool Moneychanger::is_base64(QString string)
- {
- QRegExp rx("[^a-zA-Z0-9+/=]");
- if ( rx.indexIn(string) == -1
- && (string.length()%4) == 0
- && string.length()>=4) {
- return true;
- }
- return false;
- }
- /**
- * Constructor & Destructor
- **/
- // Ownership passes to caller.
- //static
- Moneychanger * Moneychanger::Instantiate(const opentxs::api::client::Manager& manager, QWidget *parent/*=0*/)
- {
- return new Moneychanger(manager, parent);
- }
- static Moneychanger * It(bool bShuttingDown = false,
- QScopedPointer<Moneychanger> * pMoneychangerMain = nullptr);
- // NOT owned by caller.
- //static
- Moneychanger * Moneychanger::It(bool bShuttingDown/*=false*/, QScopedPointer<Moneychanger> * pMoneychangerMain/*=nullptr*/)
- {
- // See main.cpp
- static QScopedPointer<Moneychanger> & pMoneychanger = *pMoneychangerMain;
- if (bShuttingDown)
- {
- // bShuttingDown is only passed in the very last time this is called,
- // (at application shutdown.)
- //
- // (If we don't delete it at this time, then it won't get deleted until
- // the static objects are deleted, which causes a crash since apparently
- // that's too late to be deleting the widgets.)
- //
- pMoneychanger->disconnect();
- delete pMoneychanger.take();
- return nullptr;
- }
- // -------------------------------------
- if (pMoneychanger.isNull())
- return nullptr;
- return pMoneychanger.data();
- }
- Moneychanger::Moneychanger(const opentxs::api::client::Manager& manager, QWidget *parent)
- : QWidget(parent),
- ot_(manager),
- notify_bailment_callback_(opentxs::network::zeromq::ListenCallback::Factory(
- [this](const opentxs::network::zeromq::Message& message) -> void {
- this->process_notify_bailment(message);
- })),
- notify_bailment_(ot_.ZMQ().Context().SubscribeSocket(notify_bailment_callback_)),
- pair_event_callback_(opentxs::network::zeromq::PairEventCallback::Factory(
- [this](const opentxs::proto::PairEvent& event) -> void {
- this->process_pair_event(event);
- })),
- pair_events_(ot_.ZMQ().Context().PairEventListener(pair_event_callback_, ot_.Instance())),
- widget_update_callback_(opentxs::network::zeromq::ListenCallback::Factory(
- [this](const opentxs::network::zeromq::Message& message) -> void {
- this->process_widget_update(message);
- })),
- widget_update_(ot_.ZMQ().Context().SubscribeSocket(widget_update_callback_)),
- // m_list(*(new MTNameLookupQT)),
- mc_overall_init(false)
- {
- /**
- ** Init variables *
- **/
- refresh_count_.store(0);
- notify_bailment_->Start(ot_.Endpoints().PendingBailment());
- widget_update_->Start(ot_.Endpoints().WidgetUpdate());
- ot_.Schedule(
- std::chrono::seconds(5),
- [&]()->void
- {
- const auto count =
- ot_.Sync().RefreshCount();
- const auto existing = refresh_count_.load();
- if (existing < count) {
- refresh_count_.store(count);
- accept_cheques();
- //emit needToPopulateRecordlist();
- }
- }
- );
- ot_.Schedule(
- std::chrono::seconds(20),
- [this]()->void{ ot_.Sync().Refresh(); },
- (std::chrono::seconds(std::time(nullptr))));
- //SQLite database
- // This can be moved very easily into a different class
- // Which I will inevitably end up doing.
- /** Default Nym **/
- qDebug() << "Setting up Nym table";
- if (0 == DBHandler::getInstance()->querySize("SELECT `nym` FROM `default_nym` WHERE `default_id`='1' LIMIT 0,1"))
- {
- qDebug() << "Default Nym wasn't set in the database. Inserting blank record...";
- DBHandler::getInstance()->runQuery("INSERT INTO `default_nym` (`default_id`,`nym`) VALUES('1','')"); // Blank Row
- }
- else
- {
- if (DBHandler::getInstance()->isNext("SELECT `nym` FROM `default_nym` WHERE `default_id`='1' LIMIT 0,1"))
- {
- default_nym_id = DBHandler::getInstance()->queryString("SELECT `nym` FROM `default_nym` WHERE `default_id`='1' LIMIT 0,1", 0, 0);
- }
- // -------------------------------------------------
- // if (default_nym_id.isEmpty() && (ot_.Exec().GetNymCount() > 0))
- // {
- // default_nym_id = QString::fromStdString(ot_.Exec().GetNym_ID(0));
- // }
- // // -------------------------------------------------
- // //Ask OT what the display name of this nym is and store it for quick retrieval later on(mostly for "Default Nym" displaying purposes)
- // if (!default_nym_id.isEmpty())
- // {
- // default_nym_name = QString::fromStdString(ot_.Exec().GetNym_Name(default_nym_id.toStdString()));
- // }
- // else
- // qDebug() << "Error loading DEFAULT NYM from SQL";
- }
- /** Default Server **/
- //Query for the default server (So we know for setting later on -- Auto select server associations on later dialogs)
- if (DBHandler::getInstance()->querySize("SELECT `server` FROM `default_server` WHERE `default_id`='1' LIMIT 0,1") == 0)
- {
- qDebug() << "Default Server wasn't set in the database. Inserting blank record...";
- DBHandler::getInstance()->runQuery("INSERT INTO `default_server` (`default_id`, `server`) VALUES('1','')"); // Blank Row
- }
- else
- {
- if (DBHandler::getInstance()->runQuery("SELECT `server` FROM `default_server` WHERE `default_id`='1' LIMIT 0,1"))
- {
- default_notary_id = DBHandler::getInstance()->queryString("SELECT `server` FROM `default_server` WHERE `default_id`='1' LIMIT 0,1", 0, 0);
- }
- // -------------------------------------------------
- // if (default_notary_id.isEmpty() && (ot_.Exec().GetServerCount() > 0))
- // {
- // default_notary_id = QString::fromStdString(ot_.Exec().GetServer_ID(0));
- // }
- // // -------------------------------------------------
- // //Ask OT what the display name of this server is and store it for a quick retrieval later on(mostly for "Default Server" displaying purposes)
- // if (!default_notary_id.isEmpty())
- // {
- // default_server_name = QString::fromStdString(ot_.Exec().GetServer_Name(default_notary_id.toStdString()));
- // }
- // else
- // qDebug() << "Error loading DEFAULT SERVER from SQL";
- }
- /** Default Asset Type **/
- //Query for the default asset (So we know for setting later on -- Auto select asset associations on later dialogs)
- if (DBHandler::getInstance()->querySize("SELECT `asset` FROM `default_asset` WHERE `default_id`='1' LIMIT 0,1") == 0)
- {
- qDebug() << "Default Asset Type wasn't set in the database. Inserting blank record...";
- DBHandler::getInstance()->runQuery("INSERT INTO `default_asset` (`default_id`,`asset`) VALUES('1','')"); // Blank Row
- }
- else
- {
- if (DBHandler::getInstance()->runQuery("SELECT `asset` FROM `default_asset` WHERE `default_id`='1' LIMIT 0,1"))
- {
- default_asset_id = DBHandler::getInstance()->queryString("SELECT `asset` FROM `default_asset` WHERE `default_id`='1' LIMIT 0,1", 0, 0);
- }
- // -------------------------------------------------
- // if (default_asset_id.isEmpty() && (ot_.Exec().GetAssetTypeCount() > 0))
- // {
- // default_asset_id = QString::fromStdString(ot_.Exec().GetAssetType_ID(0));
- // }
- // // -------------------------------------------------
- // //Ask OT what the display name of this asset type is and store it for a quick retrieval later on(mostly for "Default Asset" displaying purposes)
- // if (!default_asset_id.isEmpty())
- // {
- // default_asset_name = QString::fromStdString(ot_.Exec().GetAssetType_Name(default_asset_id.toStdString()));
- // }
- // else
- // qDebug() << "Error loading DEFAULT ASSET from SQL";
- }
- /** Default Account **/
- //Query for the default account (So we know for setting later on -- Auto select account associations on later dialogs)
- if (DBHandler::getInstance()->querySize("SELECT `account` FROM `default_account` WHERE `default_id`='1' LIMIT 0,1") == 0)
- {
- qDebug() << "Default Account wasn't set in the database. Inserting blank record...";
- DBHandler::getInstance()->runQuery("INSERT INTO `default_account` (`default_id`,`account`) VALUES('1','')"); // Blank Row
- }
- else
- {
- if (DBHandler::getInstance()->runQuery("SELECT `account` FROM `default_account` WHERE `default_id`='1' LIMIT 0,1"))
- {
- default_account_id = DBHandler::getInstance()->queryString("SELECT `account` FROM `default_account` WHERE `default_id`='1' LIMIT 0,1", 0, 0);
- }
- // -------------------------------------------------
- // if (default_account_id.isEmpty() && (ot_.Exec().GetAccountCount() > 0))
- // {
- // default_account_id = QString::fromStdString(ot_.Exec().GetAccountWallet_ID(0));
- // }
- // // -------------------------------------------------
- // //Ask OT what the display name of this account is and store it for a quick retrieval later on(mostly for "Default Account" displaying purposes)
- // if (!default_account_id.isEmpty())
- // {
- // default_account_name = QString::fromStdString(ot_.Exec().GetAccountWallet_Name(default_account_id.toStdString()));
- // }
- // else
- // qDebug() << "Error loading DEFAULT ACCOUNT from SQL";
- }
- // ----------------------------------------------------------------------------
- //Ask OT for "cash account" information (might be just "Account" balance)
- //Ask OT the purse information
- /* *** *** ***
- * Init Memory Trackers (there may be other int below than just memory trackers but generally there will be mostly memory trackers below)
- * Allows the program to boot with a low footprint -- keeps start times low no matter the program complexity;
- * Memory will expand as the operator opens dialogs;
- * Also prevents HTTP requests from overloading or spamming the operators device by only allowing one window of that request;
- * *** *** ***/
- //Init MC System Tray Icon
- mc_systrayIcon = new QSystemTrayIcon(this);
- mc_systrayIcon->setIcon(QIcon(":/icons/moneychanger"));
- //Init Icon resources (Loading resources/access Harddrive first; then send to GPU; This specific order will in theory prevent bottle necking between HDD/GPU)
- mc_systrayIcon_shutdown = QIcon(":/icons/quit");
- mc_systrayIcon_overview = QIcon(":/icons/overview");
- mc_systrayIcon_nym = QIcon(":/icons/icons/identity_BW2.png");
- mc_systrayIcon_server = QIcon(":/icons/server");
- mc_systrayIcon_goldaccount = QIcon(":/icons/icons/safe_box.png");
- mc_systrayIcon_purse = QIcon(":/icons/icons/assets.png");
- // mc_systrayIcon_sendfunds = QIcon(":/icons/icons/fistful_of_cash_72.png");
- mc_systrayIcon_sendfunds = QIcon(":/icons/icons/money_fist4_small.png");
- // mc_systrayIcon_sendfunds = QIcon(":/icons/sendfunds");
- mc_systrayIcon_requestfunds = QIcon(":/icons/requestpayment");
- mc_systrayIcon_proposeplan = QIcon(":/icons/icons/timer.png");
- // mc_systrayIcon_contacts = QIcon(":/icons/addressbook");
- mc_systrayIcon_contacts = QIcon(":/icons/icons/rolodex_card2");
- mc_systrayIcon_composemessage = QIcon(":/icons/icons/pencil.png");
- // mc_systrayIcon_composemessage = QIcon(":/icons/icons/compose.png");
- mc_systrayIcon_markets = QIcon(":/icons/markets");
- mc_systrayIcon_trade_archive = QIcon(":/icons/overview");
- mc_systrayIcon_active_agreements = QIcon(":/icons/agreements");
- mc_systrayIcon_pending = QIcon(":/icons/icons/pending.png");
- // ---------------------------------------------------------------
- mc_systrayIcon_bitcoin = QIcon(":/icons/icons/bitcoin.png");
- mc_systrayIcon_crypto = QIcon(":/icons/icons/lock.png");
- //Submenu
- mc_systrayIcon_crypto_encrypt = QIcon(":/icons/icons/lock.png");
- mc_systrayIcon_crypto_decrypt = QIcon(":/icons/icons/padlock_open.png");
- mc_systrayIcon_crypto_sign = QIcon(":/icons/icons/signature-small.png");
- mc_systrayIcon_crypto_verify = QIcon(":/icons/icons/check-mark-small.png");
- // ---------------------------------------------------------------
- mc_systrayIcon_advanced = QIcon(":/icons/advanced");
- //Submenu
- mc_systrayIcon_advanced_import = QIcon(":/icons/icons/request.png");
- mc_systrayIcon_advanced_smartcontracts = QIcon(":/icons/icons/smart_contract_64.png");
- mc_systrayIcon_advanced_corporations = QIcon(":/icons/icons/buildings.png");
- mc_systrayIcon_advanced_transport = QIcon(":/icons/icons/p2p.png");
- mc_systrayIcon_advanced_log = QIcon(":/icons/icons/p2p.png");
- mc_systrayIcon_settings = QIcon(":/icons/settings");
- // ----------------------------------------------
- QString qstrExpertMode = MTContactHandler::getInstance()->
- GetValueByID("expertmode", "parameter1", "settings", "setting");
- bExpertMode_ = (0 == qstrExpertMode.compare("on"));
- // -------------------------------------------------
- QString qstrHideNav = MTContactHandler::getInstance()->
- GetValueByID("hidenav", "parameter1", "settings", "setting");
- bHideNav_ = (0 == qstrHideNav.compare("on"));
- // -------------------------------------------------
- // setupRecordList();
- mc_overall_init = true;
- }
- void Moneychanger::accept_cheques() const
- {
- const auto nyms = ot_.OTAPI().LocalNymList();
- for (const auto& nym : nyms) {
- ot_.Sync().DepositCheques(nym);
- }
- }
- void Moneychanger::process_notify_bailment(
- const opentxs::network::zeromq::Message& multipartMessage)
- {
- OT_ASSERT(1 == multipartMessage.Body().size());
- std::string message(*multipartMessage.Body().begin());
- auto request =
- opentxs::proto::TextToProto<opentxs::proto::PeerRequest>(message);
- if (false == opentxs::proto::Validate(request, false)) {
- std::cout << __FUNCTION__ << ": Invalid peer request" << std::endl;
- return;
- }
- if (opentxs::proto::PEERREQUEST_PENDINGBAILMENT != request.type()) {
- std::cout << __FUNCTION__ << ": Not a notify bailment request"
- << std::endl;
- return;
- }
- QString txid = QString::fromStdString(request.pendingbailment().txid());
- QString msg = QString(tr("Received notice of pending deposit from "
- "blockchain: ")) + txid;
- emit appendToLog(msg);
- std::cout << __FUNCTION__ << ": Received notice of pending bailment: "
- << request.pendingbailment().txid().c_str() << std::endl;
- }
- void Moneychanger::process_pair_event(const opentxs::proto::PairEvent& event)
- {
- std::cout << __FUNCTION__ << ": Received pair event" << std::endl;
- switch (event.type()) {
- case opentxs::proto::PAIREVENT_RENAME: {
- std::cout << __FUNCTION__ << ": Issuer " << event.issuer()
- << " is ready to be renamed." << std::endl;
- } break;
- case opentxs::proto::PAIREVENT_STORESECRET: {
- QString msg(tr("Your seed backup has been stored on your Stash "
- "Node Pro. You may now remove the backup USB device "
- "and store it in a safe location."));
- emit appendToLog(msg);
- std::cout << __FUNCTION__ << ": Issuer " << event.issuer()
- << " has stored a seed backup for us." << std::endl;
- } break;
- case opentxs::proto::PAIREVENT_ERROR:
- default: {
- std::cout << __FUNCTION__ << ": Unknown or invalid event type"
- << std::endl;
- }
- }
- }
- void Moneychanger::process_widget_update(
- const opentxs::network::zeromq::Message& multipartMessage)
- {
- OT_ASSERT(1 == multipartMessage.Body().size());
- std::string message(*multipartMessage.Body().begin());
- const std::string str_msg = std::string(message);
- const QString qstrMsg = QString::fromStdString(str_msg);
- emit opentxsWidgetUpdated(qstrMsg);
- }
- // RETRIEVE NYM INTERMEDIARY FILES
- // Returns:
- // True if I have enough numbers, or if there was success getting more
- // transaction numbers.
- // False if I didn't have enough numbers, tried to get more, and failed
- // somehow.
- //
- bool Moneychanger::retrieve_nym(
- const std::string& strNotaryID,
- const std::string& strMyNymID) const
- {
- auto context = ot_.Wallet().mutable_ServerContext(
- opentxs::Identifier::Factory(strMyNymID), opentxs::Identifier::Factory(strNotaryID));
- opentxs::Utility MsgUtil(context.It(), ot_);
- if (0 >= context.It().UpdateRequestNumber()) {
- return false;
- }
- bool msgWasSent = false;
- std::int32_t nGetAndProcessNymbox = MsgUtil.getAndProcessNymbox_4(
- strNotaryID, strMyNymID, msgWasSent, true);
- if (0 > nGetAndProcessNymbox) {
- return false;
- }
- return true;
- }
- void Moneychanger::onNeedToCheckNym(QString myNymId, QString hisNymId, QString notaryId)
- {
- if (hisNymId.isEmpty())
- {
- qDebug() << __FUNCTION__ << ": ERROR: no hisNymId passed in! (Returning.)";
- return;
- }
- // ---------------------------
- if (myNymId.isEmpty())
- myNymId = getDefaultNymID();
- if (myNymId.isEmpty())
- {
- //Count nyms
- const int32_t nym_count = ot_.Exec().GetNymCount();
- if (nym_count > 0)
- myNymId = QString::fromStdString(ot_.Exec().GetNym_ID(0));
- }
- if (myNymId.isEmpty())
- {
- qDebug() << __FUNCTION__ << ": no myNymId passed in, and unable to figure out one on my own! (Returning.)";
- return;
- }
- // ---------------------------
- // If a notary was passed in, let's make sure we have its contract!
- //
- if (!notaryId.isEmpty())
- {
- const std::string str_notary_contract = ot_.Exec().GetServer_Contract(notaryId.toStdString());
- if (str_notary_contract.empty())
- {
- notaryId = QString("");
- qDebug() << __FUNCTION__ << ": We don't have the server contract for the specified notary ID. "
- "(I guess we'll try the default, it may yet work.) TODO: Download it from the DHT.";
- }
- }
- // ---------------------------
- mapIDName mapServers;
- bool bGotServersForNym = false;
- // Hmm, no notary ID was passed. Perhaps one wasn't available.
- // In that case we'll see if there are any known notaries for hisNymId.
- // If so, we'll use them all.
- // Otherwise, we'll try to use the default notary instead.
- // Otherwise we'll give up :P
- //
- if (notaryId.isEmpty())
- bGotServersForNym = MTContactHandler::getInstance()->GetServers(mapServers, hisNymId);
- else
- mapServers.insert(notaryId, "Server Name Unused Here");
- if (mapServers.size() < 1)
- {
- notaryId = getDefaultNotaryID();
- if (!notaryId.isEmpty())
- mapServers.insert(notaryId, "Server Name Unused Here");
- }
- // Oh well. We tried.
- if (mapServers.size() < 1)
- {
- qDebug() << __FUNCTION__ << ": no notaryId passed in, and unable to figure out one on my own! (Returning.)";
- return;
- }
- // --------------------------------
- const std::string my_nym_id = myNymId.toStdString();
- const std::string his_nym_id = hisNymId.toStdString();
- for (mapIDName::iterator it_servers = mapServers.begin(); it_servers != mapServers.end(); ++it_servers)
- {
- QString qstrNotaryID = it_servers.key();
- // QString qstrNotaryName = it_servers.value();
- if (qstrNotaryID.isEmpty()) // Weird, should never happen.
- {
- qDebug() << __FUNCTION__ << ": Unexpectedly empty NotaryID, should not happen. (Returning.)";
- return;
- }
- const std::string notary_id = qstrNotaryID.toStdString();
- // ---------------------------------------------
- // Need to verify that I'M registered at this server, before I try to
- // download some guy's credentials from a "server he's known to use."
- // I may not even be registered there, in which case the check_nym call would fail.
- //
- // And how do I know if I even have the server contract at all?
- //
- const std::string str_server_contract = ot_.Exec().GetServer_Contract(notary_id);
- if (str_server_contract.empty())
- {
- qDebug() << __FUNCTION__ << ": We don't have the server contract for this notary ID. (Skipping.) TODO: Download it from the DHT.";
- continue;
- }
- // ---------------------------------------------
- const bool isReg = ot_.Exec().IsNym_RegisteredAtServer(my_nym_id, notary_id);
- if (!isReg)
- {
- std::string response;
- {
- MTSpinner theSpinner;
- response = opentxs::String::Factory(ot_.Sync().RegisterNym(opentxs::Identifier::Factory(my_nym_id), opentxs::Identifier::Factory(notary_id), true))->Get();
- if (response.empty() && !ot_.Exec().CheckConnection(notary_id))
- {
- QString qstrErrorMsg;
- qstrErrorMsg = QString("%1: %2. %3.").
- arg(tr("Failed trying to contact notary")).
- arg(qstrNotaryID).arg(tr("Perhaps it is down, or there might be a network problem"));
- emit appendToLog(qstrErrorMsg);
- continue;
- }
- }
- if (!opentxs::VerifyMessageSuccess(ot_, response)) {
- Moneychanger::It()->HasUsageCredits(notary_id, my_nym_id);
- continue;
- }
- else
- MTContactHandler::getInstance()->NotifyOfNymServerPair(myNymId, qstrNotaryID);
- }
- // ------------------------------
- {
- std::string response;
- {
- MTSpinner theSpinner;
- const auto notaryID = opentxs::Identifier::Factory(notary_id);
- const auto myNymID = opentxs::Identifier::Factory(my_nym_id);
- const auto hisNymID = opentxs::Identifier::Factory(his_nym_id);
- auto action = ot_.ServerAction().DownloadNym(myNymID, notaryID, hisNymID);
- response = action->Run();
- }
- if (response.empty() && !ot_.Exec().CheckConnection(notary_id))
- {
- QString qstrErrorMsg;
- qstrErrorMsg = QString("%1: %2. %3.").
- arg(tr("Failed trying to contact notary")).
- arg(qstrNotaryID).arg(tr("Perhaps it is down, or there might be a network problem"));
- emit appendToLog(qstrErrorMsg);
- continue;
- }
- int32_t nReturnVal = opentxs::VerifyMessageSuccess(ot_, response);
- if (1 == nReturnVal)
- {
- emit nymWasJustChecked(hisNymId);
- break;
- }
- }
- } // for (servers)
- }
- //QString getBitmessageAddressFromClaims(const QString & claimant_nym_id);
- //QString getDisplayNameFromClaims(const QString & claimant_nym_id);
- // Someone did this: OT_ME::check_nym(id); emit nymWasJustChecked(id);
- //
- void Moneychanger::onCheckNym(QString nymId)
- {
- // ----------------------------------------------
- auto strNymId = opentxs::String::Factory(nymId.toStdString());
- auto id_nym = opentxs::Identifier::Factory(strNymId);
- // ----------------------------------------------
- // Get the Nym. Make sure we have the latest copy, since his credentials were apparently
- // just downloaded and overwritten.
- //
- std::shared_ptr<const opentxs::Nym> pCurrentNym =
- ot_.Wallet().Nym(id_nym);
- if (false == bool(pCurrentNym))
- {
- qDebug() << "onCheckNym: Loading the nym failed. (Which should NOT happen since we supposedly JUST downloaded that Nym's credentials...)";
- return;
- }
- // // ------------------------------------------------
- // // Clear the claims and verifications we already have in the database. (If any.)
- // //
- // MTContactHandler::getInstance()->clearClaimsForNym(nymId);
- // // ----------------------------------------------
- // // Import the claims.
- // const std::string str_checked_nym_id(strNymId.Get());
- // const auto data =
- // ot_.Exec().GetContactData(nymId.toStdString());
- // auto claims =
- // opentxs::proto::DataToProto<opentxs::proto::ContactData>
- // (opentxs::Data::Factory(data.c_str(), static_cast<uint32_t>(data.length())));
- // for (const auto& section: claims.section()) {
- // for (const auto& claim: section.item()) {
- // // ---------------------------------------
- // const uint32_t claim_section = section.name();
- // const uint32_t claim_type = claim.type();
- // const QString claim_value = QString::fromStdString(claim.value());
- // // Add the claim to the database if not there already.
- // const bool upserted =
- // MTContactHandler::getInstance()->upsertClaim(
- // *pCurrentNym,
- // claim_section,
- // claim);
- // if (!upserted) {
- // qDebug() << "onCheckNym: the call to upsertClaim just failed. "
- // << "(Returning.)";
- // return;
- // }
- // bool claim_att_active = false;
- // bool claim_att_primary = false;
- // for (const auto& attribute : claim.attribute()) {
- // if (opentxs::proto::CITEMATTR_ACTIVE == attribute) {
- // claim_att_active = true;
- // }
- // if (opentxs::proto::CITEMATTR_PRIMARY == attribute) {
- // claim_att_primary = true;
- // }
- // }
- // if (claim_att_active && claim_att_primary) {
- // if (claim_section == opentxs::proto::CONTACTSECTION_IDENTIFIER) {
- // MTContactHandler::getInstance()->NotifyOfNymNamePair(
- // nymId,
- // claim_value);
- // }
- // if ((claim_section == opentxs::proto::CONTACTSECTION_COMMUNICATION) &&
- // (claim_type == opentxs::proto::CITEMTYPE_BITMESSAGE)) {
- // // NOTE: May not need to do anything here. We already
- // // imported the claims, and we can already search the
- // // claims for Bitmessage address and NymID, which we
- // // are already doing.
- // }
- // }
- // }
- // }
- // // -------------------------------------------------------
- // // Import the verifications.
- // //
- // const auto ver_data =
- // ot_.Exec().GetVerificationSet(nymId.toStdString());
- // auto the_set =
- // opentxs::proto::DataToProto<opentxs::proto::VerificationSet>
- // (opentxs::Data::Factory(ver_data.c_str(), ver_data.length()));
- // // Internal verifications:
- // // Here I'm looping through pCurrentNym's verifications of other people's claims.
- // for (auto& claimant: the_set.internal().identity()) {
- // // Here we're looping through those other people. (Claimants.)
- // const std::string& str_claimant_id = claimant.nym();
- // for (auto& verification : claimant.verification()) {
- // const bool success =
- // MTContactHandler::getInstance()->upsertClaimVerification(
- // str_claimant_id,
- // str_checked_nym_id,
- // verification,
- // true); //bIsInternal=true
- // if (!success) {
- // qDebug() << "onCheckNym: the call to "
- // << "upsertInternalClaimVerification just failed. "
- // << "(Returning.)";
- // return;
- // }
- // }
- // }
- // // External verifications:
- // // Here I'm looping through other people's verifications of pCurrentNym's claims.
- // for (auto& verifier: the_set.external().identity()) {
- // const std::string& str_verifier_id = verifier.nym();
- // for (auto& verification : verifier.verification()) {
- // const bool success =
- // MTContactHandler::getInstance()->upsertClaimVerification(
- // str_checked_nym_id,
- // str_verifier_id,
- // verification,
- // false); //bIsInternal=true by default.
- // if (!success) {
- // qDebug() << "onCheckNym: the call to "
- // << "upsertExternalClaimVerification just failed. "
- // << "(Returning.)";
- // return;
- // }
- // }
- // }
- // // -------------------------------------------------------
- // // Import the repudiations.
- // // -------------------------------------------------------
- // // emit signal that claims / verifications were updated.
- // //
- emit claimsUpdatedForNym(nymId);
- }
- static void blah()
- {
- //resume
- //todo
- // OT_API.hpp
- //EXPORT VerificationSet GetVerificationSet(const Nym& fromNym) const;
- // EXPORT bool SetVerifications(Nym& onNym,
- // const proto::VerificationSet&) const;
- // Nym.hpp
- // std::shared_ptr<proto::VerificationSet> VerificationSet() const;
- // bool SetVerificationSet(const proto::VerificationSet& data);
- //
- // proto::Verification Sign(
- // const std::string& claim,
- // const bool polarity,
- // const int64_t start = 0,
- // const int64_t end = 0,
- // const OTPasswordData* pPWData = nullptr) const;
- // bool Verify(const proto::Verification& item) const;
- // VerificationSet has 2 groups, internal and external.
- // Internal is for your signatures on other people's claims.
- // External is for other people's signatures on your claims.
- // When you find that in the external, you copy it to your own credential.
- // So external is for re-publishing other people's verifications of your claims.
- // If we've repudiated any claims, you can add their IDs to the repudiated field in the verification set.
- }
- Moneychanger::~Moneychanger()
- {
- }
- //opentxs::OTRecordList & Moneychanger::GetRecordlist()
- //{
- // return m_list;
- //}
- //void Moneychanger::setupRecordList()
- //{
- // int nServerCount = ot_.Exec().GetServerCount();
- // int nAssetCount = ot_.Exec().GetAssetTypeCount();
- // int nNymCount = ot_.Exec().GetNymCount();
- // // ----------------------------------------------------
- // GetRecordlist().ClearServers();
- // GetRecordlist().ClearAssets();
- // GetRecordlist().ClearNyms();
- // GetRecordlist().ClearAccounts();
- // // ----------------------------------------------------
- // for (int ii = 0; ii < nServerCount; ++ii)
- // {
- // std::string NotaryID = ot_.Exec().GetServer_ID(ii);
- // GetRecordlist().AddNotaryID(NotaryID);
- // }
- // // ----------------------------------------------------
- // for (int ii = 0; ii < nAssetCount; ++ii)
- // {
- // std::string InstrumentDefinitionID = ot_.Exec().GetAssetType_ID(ii);
- // GetRecordlist().AddInstrumentDefinitionID(InstrumentDefinitionID);
- // }
- // // ----------------------------------------------------
- // for (int ii = 0; ii < nNymCount; ++ii)
- // {
- // std::string nymId = ot_.Exec().GetNym_ID(ii);
- // GetRecordlist().AddNymID(nymId);
- // }
- // // ----------------------------------------------------
- // for (const auto& [accountID, alias] : ot_.DB().AccountList())
- // {
- // GetRecordlist().AddAccountID(accountID);
- // }
- // // ----------------------------------------------------
- // GetRecordlist().AcceptChequesAutomatically (true);
- // GetRecordlist().AcceptReceiptsAutomatically (true);
- // GetRecordlist().AcceptTransfersAutomatically(false);
- // GetRecordlist().IgnoreMail(!expertMode());
- //}
- // Calls OTRecordList::Populate(), and then additionally adds records from Bitmessage, etc.
- //
- //void Moneychanger::populateRecords(bool bCurrentlyModifying/*=false*/)
- //{
- // GetRecordlist().Populate(); // Refreshes the OT data from local storage. < << <<==============***
- // ---------------------------------------------------------------------
- // QList<QString> listCheckOnlyOnce; // So we don't call checkMail more than once for the same connect string.
- // // ---------------------------------------------------------------------
- // // Let's see if, additionally, there are any Bitmessage records (etc)
- // // for the Nyms that we care about. (If we didn't add a Nym ID to GetRecordlist()'s
- // // list of Nyms, then we don't care about any Bitmessages for that Nym.)
- // //
- // bool bNeedsReSorting = false;
- // const opentxs::list_of_strings & the_nyms = GetRecordlist().GetNyms();
- // for (opentxs::list_of_strings::const_iterator it = the_nyms.begin(); it != the_nyms.end(); ++it)
- // {
- // const std::string str_nym_id = *it;
- // // -----------------------------
- // mapIDName mapMethods;
- // QString filterByNym = QString::fromStdString(str_nym_id);
- // bool bGotMethods = !filterByNym.isEmpty() ? MTContactHandler::getInstance()->GetMsgMethodsByNym(mapMethods, filterByNym, false, QString("")) : false;
- // if (bGotMethods)
- // {
- // // Loop through mapMethods and for each methodID, call GetAddressesByNym.
- // // Then for each address, grab the inbox and outbox from MTComms, and add
- // // the messages to GetRecordlist().
- // //
- // for (mapIDName::iterator ii = mapMethods.begin(); ii != mapMethods.end(); ++ii)
- // {
- // QString qstrID = ii.key();
- // int nFilterByMethodID = 0;
- // QStringList stringlist = qstrID.split("|");
- // if (stringlist.size() >= 2) // Should always be 2...
- // {
- //// QString qstrType = stringlist.at(0);
- // QString qstrMethodID = stringlist.at(1);
- // nFilterByMethodID = qstrMethodID.isEmpty() ? 0 : qstrMethodID.toInt();
- // // --------------------------------------
- // if (nFilterByMethodID > 0)
- // {
- // QString qstrMethodType = MTContactHandler::getInstance()->GetMethodType (nFilterByMethodID);
- // QString qstrTypeDisplay = MTContactHandler::getInstance()->GetMethodTypeDisplay(nFilterByMethodID);
- // QString qstrConnectStr = MTContactHandler::getInstance()->GetMethodConnectStr (nFilterByMethodID);
- // if (!qstrConnectStr.isEmpty())
- // {
- // NetworkModule * pModule = MTComms::find(qstrConnectStr.toStdString());
- // if ((nullptr == pModule) && MTComms::add(qstrMethodType.toStdString(), qstrConnectStr.toStdString()))
- // pModule = MTComms::find(qstrConnectStr.toStdString());
- // if (nullptr == pModule)
- // // todo probably need a messagebox here.
- // qDebug() << QString("PopulateRecords: Unable to add a %1 interface with connection string: %2").arg(qstrMethodType).arg(qstrConnectStr);
- // if ((nullptr != pModule) && pModule->accessible())
- // {
- // if ((-1) == listCheckOnlyOnce.indexOf(qstrConnectStr)) // Not on the list yet.
- // {
- // pModule->checkMail();
- // listCheckOnlyOnce.insert(0, qstrConnectStr);
- // }
- // // ------------------------------
- // mapIDName mapAddresses;
- // if (MTContactHandler::getInstance()->GetAddressesByNym(mapAddresses, filterByNym, nFilterByMethodID))
- // {
- // for (mapIDName::iterator jj = mapAddresses.begin(); jj != mapAddresses.end(); ++jj)
- // {
- // QString qstrAddress = jj.key();
- // if (!qstrAddress.isEmpty())
- // {
- // // --------------------------------------------------------------------------------------------
- // // INBOX
- // //
- // std::vector< _SharedPtr<NetworkMail> > theInbox = pModule->getInbox(qstrAddress.toStdString());
- // for (std::vector< _SharedPtr<NetworkMail> >::size_type nIndex = 0; nIndex < theInbox.size(); ++nIndex)
- // {
- // _SharedPtr<NetworkMail> & theMsg = theInbox[nIndex];
- // std::string strSubject = theMsg->getSubject();
- // std::string strContents = theMsg->getMessage();
- // // ----------------------------------------------------
- // QString qstrFinal;
- // if (!strSubject.empty())
- // qstrFinal = QString("%1: %2\n%3").
- // arg(tr("Subject")).
- // arg(QString::fromStdString(strSubject)).
- // arg(QString::fromStdString(strContents));
- // else
- // qstrFinal = QString::fromStdString(strContents);
- // // ----------------------------------------------------
- // bNeedsReSorting = true;
- // if (!theMsg->getMessageID().empty())
- // GetRecordlist().AddSpecialMsg(theMsg->getMessageID(),
- // false, //bIsOutgoing=false
- // static_cast<int32_t>(nFilterByMethodID),
- // qstrFinal.toStdString(),
- // theMsg->getTo(),
- // theMsg->getFrom(),
- // qstrMethodType.toStdString(),
- // qstrTypeDisplay.toStdString(),
- // str_nym_id,
- // static_cast<time64_t>(theMsg->getReceivedTime()));
- // } // for (inbox)
- // // --------------------------------------------------------------------------------------------
- // // OUTBOX
- // //
- // std::vector< _SharedPtr<NetworkMail> > theOutbox = pModule->getOutbox(qstrAddress.toStdString());
- // for (std::vector< _SharedPtr<NetworkMail> >::size_type nIndex = 0; nIndex < theOutbox.size(); ++nIndex)
- // {
- // _SharedPtr<NetworkMail> & theMsg = theOutbox[nIndex];
- // std::string strSubject = theMsg->getSubject();
- // std::string strContents = theMsg->getMessage();
- // // ----------------------------------------------------
- // QString qstrFinal;
- // if (!strSubject.empty())
- // qstrFinal = QString("%1: %2\n%3").
- // arg(tr("Subject")).
- // arg(QString::fromStdString(strSubject)).
- // arg(QString::fromStdString(strContents));
- // else
- // qstrFinal = QString::fromStdString(strContents);
- // // ----------------------------------------------------
- // bNeedsReSorting = true;
- //// qDebug() << QString("Adding OUTGOING theMsg->getMessageID(): %1 \n filterByNym: %2 \n qstrAddress: %3 \n nIndex: %4")
- //// .arg(QString::fromStdString(theMsg->getMessageID()))
- //// .arg(filterByNym)
- //// .arg(qstrAddress)
- //// .arg(nIndex)
- //// ;
- // if (!theMsg->getMessageID().empty())
- // GetRecordlist().AddSpecialMsg(theMsg->getMessageID(),
- // true, //bIsOutgoing=true
- // static_cast<int32_t>(nFilterByMethodID),
- // qstrFinal.toStdString(),
- // theMsg->getFrom(),
- // theMsg->getTo(),
- // qstrMethodType.toStdString(),
- // qstrTypeDisplay.toStdString(),
- // str_nym_id,
- // static_cast<time64_t>(theMsg->getSentTime()));
- // } // for (outbox)
- // } // if (!qstrAddress.isEmpty())
- // } // for (addresses)
- // } // if GetAddressesByNym
- // } // if ((nullptr != pModule) && pModule->accessible())
- // } // if (!qstrConnectStr.isEmpty())
- // } // if nFilterByMethodID > 0
- // } // if (stringlist.size() >= 2)
- // } // for (methods)
- // } // if bGotMethods
- // } // for (nyms)
- // // -----------------------------------------------------
- // if (bNeedsReSorting)
- // GetRecordlist().SortRecords();
- // // -----------------------------------------------------
- // // This takes things like market receipts out of the record list
- // // and moves to their own database table.
- // // Same thing for mail messages, etc.
- // //
- // if (!bCurrentlyModifying)
- // modifyRecords();
- //}
- // ---------------------------------------------------------------
- // Check and see if the Nym has exhausted his usage credits.
- //
- // Return value: -2 for error, -1 for "unlimited" (or "server isn't enforcing"),
- // 0 for "exhausted", and non-zero for the exact number of credits available.
- int64_t Moneychanger::HasUsageCredits(const std::string & notary_id,
- const std::string & NYM_ID)
- {
- // Usually when a message fails, Moneychanger calls HasUsageCredits because it assumes
- // the failure probably happened due to a lack of usage credits.
- // ...But what if there was a network failure? What if messages can't even get out?
- //
- if (!ot_.Exec().CheckConnection(notary_id))
- {
- QString qstrErrorMsg;
- qstrErrorMsg = tr("HasUsageCredits: Failed trying to contact the notary. Perhaps it is down, or there might be a network problem.");
- emit appendToLog(qstrErrorMsg);
- return -2;
- }
- // --------------------------------------------------------
- std::string strMessage;
- {
- MTSpinner theSpinner;
- const auto notaryID = opentxs::Identifier::Factory(notary_id);
- const auto nymID = opentxs::Identifier::Factory(NYM_ID);
- auto action = ot_.ServerAction().AdjustUsageCredits(nymID, notaryID, nymID, 0);
- strMessage = action->Run();
- }
- if (strMessage.empty())
- {
- // QString qstrErrorMsg;
- // qstrErrorMsg = tr("Moneychanger::HasUsageCredits: Error 'strMessage' is Empty!");
- // emit appendToLog(qstrErrorMsg);
- return -2;
- }
- // --------------------------------------------------------
- const int64_t lReturnValue = ot_.Exec().Message_GetUsageCredits(strMessage);
- // --------------------------------------------------------
- QString qstrErrorMsg;
- switch (lReturnValue)
- {
- case (-2): // error
- qstrErrorMsg = tr("Error checking usage credits. Perhaps the server is down or inaccessible?");
- break;
- // --------------------------------
- case (-1): // unlimited, or server isn't enforcing
- qstrErrorMsg = tr("Nym has unlimited usage credits (or the server isn't enforcing credits.')");
- break;
- // --------------------------------
- case (0): // Exhausted
- qstrErrorMsg = tr("Sorry, but the Nym attempting this action is all out of usage credits on the server. "
- "(You should contact the server operator and purchase more usage credits.)");
- break;
- // --------------------------------
- default: // Nym has X usage credits remaining.
- qstrErrorMsg = tr("The Nym still has usage credits remaining. Should be fine.");
- break;
- }
- // --------------------------------
- switch (lReturnValue)
- {
- case (-2): // Error
- case (0): // Exhausted
- emit appendToLog(qstrErrorMsg);
- // --------------------------------
- default: // Nym has X usage credits remaining, or server isn't enforcing credits.
- break;
- }
- // --------------------------------
- return lReturnValue;
- }
- int64_t Moneychanger::HasUsageCredits(QString notary_id,
- QString NYM_ID)
- {
- const std::string str_server(notary_id.toStdString());
- const std::string str_nym (NYM_ID .toStdString());
- return HasUsageCredits(str_server, str_nym);
- }
- // ---------------------------------------------------------------
- /**
- * Systray
- **/
- // Startup
- void Moneychanger::bootTray()
- {
- connect(this, SIGNAL(appendT…
Large files files are truncated, but you can click here to view the full file