forked from RussianMiningCoin/RMCWallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
walletmain.cpp
1158 lines (966 loc) · 37.1 KB
/
walletmain.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <QApplication>
#include <QMessageBox>
#include <QStandardPaths>
#include <QFile>
#include <QDir>
#include <QTimer>
#include <QClipboard>
#include <QtGlobal>
#include <QSslCertificate>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QtNetwork>
#include "walletmain.h"
#include "ui_walletmain.h"
#include "transactionpreview.h"
#include "transactionview.h"
#include "doublevalidator.h"
#include "intvalidator.h"
#include "importdialog.h"
#include "enterpassword.h"
#include "aboutdialog.h"
#include "switchaccount.h"
#include "proxysettings.h"
#include "format.h"
#include "iniworker.h"
#include <stoxum/protocol/AccountID.h>
#include <stoxum/protocol/PublicKey.h>
#include <stoxum/protocol/SecretKey.h>
#include <stoxum/protocol/digest.h>
#include <stoxum/protocol/HashPrefix.h>
#include <stoxum/protocol/JsonFields.h>
#include <stoxum/protocol/Sign.h>
#include <stoxum/protocol/st.h>
#include <stoxum/protocol/TxFlags.h>
#include <stoxum/basics/StringUtilities.h>
#include <algorithm>
#include <random>
#include <tuple>
// Core routines
Error WalletMain::createPaymentTx(const QString& psRecvAcc, std::int64_t pnAmount, std::int64_t pnTxFee, std::int64_t pnTagID, QString& psJson, QString& psHex)
{
using namespace ripple;
auto const destination = parseBase58<AccountID>(psRecvAcc.toStdString());
if (! destination)
return Error(E_FATAL, "Payment", "Invalid receiver address");
if (pnAmount <= 0)
return Error(E_FATAL, "Payment", "You can send only positive amounts.");
auto& kData = vkStore[nMainAccount];
STTx noopTx(ttPAYMENT,
[&](auto& obj)
{
// General transaction fields
obj[sfAccount] = kData.raAccountID;
obj[sfFee] = STAmount{ static_cast<uint64_t>(pnTxFee) };
obj[sfFlags] = tfFullyCanonicalSig;
obj[sfSequence] = vnSequences[nMainAccount];
obj[sfSigningPubKey] = kData.rpPublicKey.slice();
// Payment-specific fields
obj[sfAmount] = STAmount { static_cast<uint64_t>(pnAmount) };
obj[sfDestination] = *destination;
if (pnTagID != 0)
obj[sfDestinationTag] = pnTagID;
});
try
{
auto eRes = askPassword();
if (eNone != eRes)
return eRes;
noopTx.sign(kData.rpPublicKey, kData.rsSecretKey);
if (nDeriveIterations != 0)
kData.rsSecretKey.~SecretKey();
psJson = noopTx.getJson(0).toStyledString().c_str();
psHex = strHex(noopTx.getSerializer().peekData()).c_str();
}
catch(const std::exception e)
{
return Error(E_FATAL, "Payment", e.what());
}
return eNone;
}
Error WalletMain::processWalletEntry(const QJsonObject& poKey, KeyData& pkData)
{
using namespace ripple;
if (poKey["account_id"].isUndefined())
return Error(E_FATAL, "Wallet", "Senseless wallet record found: no account ID");
auto decodeResult1 = parseBase58<AccountID>(poKey["account_id"].toString().toStdString());
if (! decodeResult1)
return Error(E_FATAL, "Wallet", "Unable to decode your account ID, it looks like your wallet data was corrupted.");
if (poKey["private_key"].isUndefined() && poKey["encrypted_private_key"].isUndefined())
return Error(E_FATAL, "Wallet", "Senseless wallet record found: no keys data for account " + poKey["account_id"].toString());
if (!poKey["encrypted_private_key"].isUndefined() && poKey["public_key"].isUndefined())
return Error(E_FATAL, "Wallet", "Senseless wallet record found: encrypted private key is present, but no public key available for account " + poKey["account_id"].toString());
pkData.raAccountID = *decodeResult1;
if ( !poKey["private_key"].isUndefined() && !poKey["private_key"].isNull())
{
// Plain wallet
auto decodeResult = parseBase58<SecretKey>(TokenType::AccountSecret, poKey["private_key"].toString().toStdString());
if (! decodeResult)
return Error(E_FATAL, "Wallet", "Unable to read private key, it looks like your wallet data was corrupted");
pkData.rsSecretKey = *decodeResult;
pkData.rpPublicKey = derivePublicKey(KeyType::secp256k1, pkData.rsSecretKey);
if (pkData.raAccountID != calcAccountID(pkData.rpPublicKey))
return Error(E_FATAL, "Wallet", "Private key doesn't match your account ID, it looks like your wallet data was corrupted");
return eNone;
}
else
{
// Encrypted wallet
// TODO: finish it
// auto decodeResult2 = parseHex<std::vector<unsigned char> >(poKey["encrypted_private_key"].toString().toStdString());
// auto decodeResult4 = parseHex<std::vector<unsigned char> >(poKey["public_key"].toString().toStdString());
// if (! decodeResult2 || ! decodeResult4)
// return Error(E_FATAL, "Wallet", "Unable to decode encrypted key, it looks like your wallet data was corrupted");
// pkData.vchCryptedKey = *decodeResult2;
// pkData.rpPublicKey = PublicKey(makeSlice(*decodeResult4));
// return eNone;
}
}
Error WalletMain::processWallet(const QJsonObject& poKey)
{
using namespace ripple;
const auto& accs = poKey["accounts"];
int nSize = 0;
if (!accs.isArray() || 0 == (nSize = accs.toArray().size()))
return Error(E_FATAL, "Wallet", "Incorrect wallet JSON: unable to fetch accounts");
for (const auto& account : accs.toArray())
{
KeyData keyData;
auto eRes = processWalletEntry(account.toObject(), keyData);
if (eNone != eRes)
return eRes;
vkStore.push_back(keyData);
vsAccounts.push_back(toBase58(keyData.raAccountID).c_str());
}
vnBalances = std::vector<int64_t>(nSize, 0);
vnSequences = std::vector<int>(nSize, 0);
vtTransactions = std::vector<TxVector>(nSize, TxVector());
return eNone;
}
Error WalletMain::loadWallet()
{
using namespace ripple;
QFile keyFile;
keyFile.setFileName(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + QDir::separator() + ".STMStore.json");
bool fOpened = keyFile.open(QIODevice::ReadOnly | QIODevice::Text);
if (!fOpened)
{
// Brand new wallet
ImportDialog importReq;
QString sAccID;
while (true)
{
// Ask user to import his WIF formatted key
if (importReq.exec() == QDialog::Accepted)
{
auto eRes = importKey(importReq.getKeyData(), sAccID);
if (eNoWif == eRes)
continue; // Incorrect WIF string entered, ask user again
if( eNone != eRes)
return eRes;
}
else
{
auto eRes = newKey(sAccID); // User refused, generating new private key
if (eNone != eRes)
Show(eRes);
}
break;
}
return eNone;
}
else
{
auto keyObj = QJsonDocument::fromJson(keyFile.readAll()).object();
if (keyObj["encryption"].isObject())
{
// Encrypted wallet
// auto decodeResult1 = parseHex<std::vector<unsigned char> >(keyObj["encryption"].toObject()["salt"].toString().toStdString());
// auto decodeResult2 = parseHex<std::vector<unsigned char> >(keyObj["encryption"].toObject()["encrypted_master_private_key"].toString().toStdString());
// if (! decodeResult1 || ! decodeResult2)
// return Error(E_FATAL, "Wallet", "Unable to decode encrypted wallet metadata");
// vchDerivationSalt = *decodeResult1;
// vchCryptedMasterKey = *decodeResult2;
// sMasterPubKey = keyObj["encryption"].toObject()["master_public_key"].toString().toStdString();
// nDeriveIterations = keyObj["encryption"].toObject()["iterations"].toInt();
// if (nDeriveIterations == 0) nDeriveIterations = 500000;
}
// Multi wallet mode
if (keyObj["main_account"].isDouble())
{
// Multi wallet mode
nMainAccount = keyObj["main_account"].toDouble();
return processWallet(keyObj);
}
return processWallet(keyObj);
}
return Error(E_FATAL, "Wallet", "Shouldn't happen in real life");
}
void WalletMain::saveKeys(bool pbOverwrite)
{
using namespace ripple;
QJsonArray keysArr;
for(const auto &keyData : vkStore)
{
QJsonObject keyObj;
keyObj["account_id"] = toBase58(keyData.raAccountID).c_str();
if (keyData.vchCryptedKey.size() != 0)
{
keyObj["encrypted_private_key"] = strHex(keyData.vchCryptedKey.data(), keyData.vchCryptedKey.size()).c_str();
keyObj["public_key"] = strHex(keyData.rpPublicKey.data(), keyData.rpPublicKey.size()).c_str();
}
else
keyObj["private_key"] = toBase58(TokenType::AccountSecret, keyData.rsSecretKey).c_str();
keysArr.push_back(keyObj);
}
QJsonObject walletObj
{
{ "main_account", nMainAccount },
{ "accounts", keysArr },
};
if (nDeriveIterations != 0)
{
walletObj["encryption"] = QJsonObject
{
{ "master_public_key", sMasterPubKey.c_str() },
{ "encrypted_master_private_key", strHex(vchCryptedMasterKey.data(), vchCryptedMasterKey.size()).c_str() },
{ "salt", strHex(vchDerivationSalt.data(), vchDerivationSalt.size()).c_str() },
{ "iterations", nDeriveIterations }
};
}
auto walletDoc = QJsonDocument (walletObj).toJson();
QFile keyFile;
keyFile.setFileName(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + QDir::separator() + ".STMStore.json");
if (pbOverwrite)
{
// Overwrite old file contents with zeros
keyFile.open(QIODevice::WriteOnly | QIODevice::Text);
QByteArray arrZeros(keyFile.size(), '0');
keyFile.write(arrZeros, arrZeros.size());
keyFile.close();
}
keyFile.open(QIODevice::WriteOnly | QIODevice::Text);
keyFile.write(walletDoc, walletDoc.size());
keyFile.close();
}
Error WalletMain::newKey(QString& psNewAccID)
{
using namespace ripple;
KeyData keyData;
std::tie(keyData.rpPublicKey, keyData.rsSecretKey) = randomKeyPair(KeyType::secp256k1);
keyData.raAccountID = calcAccountID(keyData.rpPublicKey);
if (nDeriveIterations != 0)
{
// Encrypt new key
if (! encryptSecretKey(keyData.rsSecretKey, sMasterPubKey, keyData.vchCryptedKey))
return Error(E_FATAL, "New key", "Error while encrypting new key, operation has been aborted");
keyData.rsSecretKey.~SecretKey(); // Destroy secret key object
}
psNewAccID = toBase58(keyData.raAccountID).c_str();
vkStore.push_back(keyData);
vsAccounts.push_back(psNewAccID);
vnBalances.push_back(0);
vnSequences.push_back(0);
vtTransactions.push_back(TxVector());
saveKeys();
accInfoRequest({ psNewAccID });
accTxRequest({ psNewAccID });
subsLedgerAndAccountRequest();
return eNone;
}
Error WalletMain::importKey(const secure::string& psKey, QString& psNewAccID)
{
using namespace ripple;
auto decodeResult = parseBase58<SecretKey>(TokenType::AccountSecret, psKey.c_str());
if (! decodeResult)
return eNoWif; // Incorrect WIF string
KeyData keyData;
keyData.rsSecretKey = *decodeResult;
keyData.rpPublicKey = derivePublicKey(KeyType::secp256k1, keyData.rsSecretKey);
keyData.raAccountID = calcAccountID(keyData.rpPublicKey);
psNewAccID = toBase58(keyData.raAccountID).c_str();
if (nDeriveIterations != 0)
{
// Encrypt new key
if (! encryptSecretKey(keyData.rsSecretKey, sMasterPubKey, keyData.vchCryptedKey))
return Error(E_FATAL, "Key import", "Error while encrypting new key, operation has been aborted");
keyData.rsSecretKey.~SecretKey(); // Destroy secret key object
}
auto it = std::find(vsAccounts.begin(), vsAccounts.end(), psNewAccID);
if (it != vsAccounts.end())
return Error(E_WARN, "Key import", "This key already exists in your wallet");
vkStore.push_back(keyData);
vsAccounts.push_back(psNewAccID);
vnBalances.push_back(0);
vnSequences.push_back(0);
vtTransactions.push_back(TxVector());
saveKeys();
accInfoRequest({ psNewAccID });
accTxRequest({ psNewAccID });
subsLedgerAndAccountRequest();
return eNone;
}
Error WalletMain::exportKey(QString& psKey)
{
using namespace ripple;
auto eRes = askPassword();
if (eNone == eRes)
psKey = toBase58(TokenType::AccountSecret, vkStore[nMainAccount].rsSecretKey).c_str();
return eRes;
}
Error WalletMain::askPassword()
{
using namespace ripple;
auto& keyData = vkStore[nMainAccount];
if (nDeriveIterations == 0)
return eNone;
while (true)
{
EnterPassword pwDialog(this);
if (pwDialog.exec() != QDialog::Accepted)
return eNoPassword; // User refused to enter the password
bool fOk = true;
secure::string decryptionKey;
fOk = decryptRSAKey(vchCryptedMasterKey, pwDialog.getPassword(), vchDerivationSalt, nDeriveIterations, decryptionKey);
if (fOk)
{
fOk = decryptSecretKey(keyData.vchCryptedKey, decryptionKey, keyData.rsSecretKey);
fOk = fOk && (keyData.raAccountID == calcAccountID(keyData.rpPublicKey));
}
if (fOk) return eNone;
// Wrong password, try again
continue;
}
}
WalletMain::WalletMain(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::WalletMain)
{
#ifdef QT_NO_SSL
#error "SSL support is required"
#endif
auto eRes = loadWallet();
if ( eNone != eRes)
{
if (eRes != eNoPassword)
Show(eRes);
QTimer::singleShot(250, qApp, SLOT(quit()));
return;
}
ui->setupUi(this);
// Init in offline state
setOnline(false, "Initialization is in progress");
setupControls(parent);
// Set message handlers
connect(&wSockConn, &QWebSocket::connected, this, &WalletMain::onConnected);
connect(&wSockConn, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onConnectionError(QAbstractSocket::SocketError)));
//socketConnect();
QTimer::singleShot(500, this, SLOT(doReconnect()));
}
void WalletMain::onConnectionError(QAbstractSocket::SocketError psError)
{
switch (psError) {
case QAbstractSocket::ConnectionRefusedError:
case QAbstractSocket::HostNotFoundError:
{
switch(psError) {
case QAbstractSocket::ConnectionRefusedError:
setOnline(false, "The connection was refused by the peer. Please try again later. ");
break;
case QAbstractSocket::HostNotFoundError:
setOnline(false, "The host was not found. Please check your internet connection settings.");
break;
default:
setOnline(false, QString("The following error occurred: %1.").arg(wSockConn.errorString()));
}
nConnectAttempt += 4;
return;
}
case QAbstractSocket::RemoteHostClosedError:
setOnline(false, "Connection was closed by remote host.");
break;
default:
setOnline(false, QString("The following error occurred: %1.").arg(wSockConn.errorString()));
}
if (nConnectAttempt <= 3)
doReconnect();
nConnectAttempt++;
}
void WalletMain::setOnline(bool pbFlag, const QString& psReason)
{
using namespace ripple;
QString strAccountID = toBase58(vkStore[nMainAccount].raAccountID).c_str();
this->setWindowTitle(QString("STM Wallet [%1%2]").arg(strAccountID).arg(pbFlag ? "" : ", offline"));
// Select default tab
if (! pbFlag) ui->tabWidget->setCurrentIndex(0);
if (! pbFlag) vnBalances[nMainAccount] = 0;
if (! pbFlag) nIndex = -1;
if (pbFlag) nConnectAttempt = 0;
// Send form and tab widget headers
ui->sendButton->setEnabled(pbFlag);
ui->previewButton->setEnabled(pbFlag);
ui->tabWidget->setTabEnabled(1, pbFlag);
ui->tabWidget->setTabEnabled(2, pbFlag);
ui->sendTransactionFeeValue->setPlaceholderText(Amount(nFeeRef));
// Statusbar labels
balanceLabel.setText(QString("Balance: %1").arg(AmountWithSign(vnBalances[nMainAccount])));
ledgerLabel.setText(QString("Current ledger: %1").arg(nIndex));
networkStatusLabel.setText(QString("Network status: %1").arg(psReason));
// Network info tab
ui->latestLedgerHash->setText(sHash);
ui->latestLedgerNum->setText(QString("%1").arg(nIndex));
ui->transactionsCount->setText(QString("%1").arg(nTxes));
ui->closeTime->setText(timeFormat(nCloseTime));
ui->baseFeeValue->setText(AmountWithSign(nFee));
ui->feeRefValue->setText(AmountWithSign(nFeeRef));
ui->baseReserveValue->setText(AmountWithSign(nReserve));
}
void WalletMain::setupControls(QWidget *parent)
{
// Setup amount validator
std::unique_ptr<DoubleValidator> amountValidator(new DoubleValidator(parent));
amountValidator->setDecimals(6);
amountValidator->setBottom(0.00);
amountValidator->setTop(10757.0);
amountValidator->setNotation(QDoubleValidator::StandardNotation);
ui->amountToSend->setValidator(amountValidator.get());
ui->sendTransactionFeeValue->setValidator(amountValidator.get());
// Setup tag validator
std::unique_ptr<IntValidator> tagValidator(new IntValidator(parent));
amountValidator->setBottom(0);
ui->destinationTag->setValidator(tagValidator.get());
// Hide columns
ui->txView->setColumnHidden(4, true);
// Set column sizes
for(auto nCol : {0, 1, 3})
ui->txView->setColumnWidth(nCol, 150);
// Add statusBar labels
for (auto pW : {&balanceLabel, &ledgerLabel, &networkStatusLabel})
ui->statusBar->addWidget(pW);
ui->txView->verticalHeader()->setVisible(false);
ui->txView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->txView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
ui->actionEncrypt_wallet->setDisabled(vkStore[nMainAccount].vchCryptedKey.size() != 0);
connect(ui->txView, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(txItemClicked(int,int)));
}
WalletMain::~WalletMain()
{
delete ui;
}
void WalletMain::socketConnect()
{
using namespace std;
// Connect to random RPC server
vector<QString> servers = {"wss://h1.stoxum.com:51231/", "wss://h2.stoxum.com:51231/", "wss://h3.stoxum.com:51231/"};
random_device random_device;
mt19937 engine{random_device()};
uniform_int_distribution<int> dist(0, servers.size() - 1);
wSockConn.open(QUrl(servers[dist(engine)]));
}
void WalletMain::onConnected()
{
connect(&wSockConn, &QWebSocket::textMessageReceived,
this, &WalletMain::onTextMessageReceived);
accInfoRequest();
accTxRequest();
subsLedgerAndAccountRequest();
}
void WalletMain::doReconnect()
{
setOnline(false, "Reconnecting");
//reqMap.clear();
if (wSockConn.state() == QAbstractSocket::SocketState::ConnectedState)
wSockConn.close();
socketConnect();
}
void WalletMain::onTextMessageReceived(QString psMsg)
{
auto msgDoc = QJsonDocument::fromJson(psMsg.toUtf8());
auto msgObj = msgDoc.object();
// Check validity of received message
if (!msgObj.contains("id") && !msgObj.contains("type"))
{
qDebug() << "Malformed JSON message received:" << psMsg;
return;
}
// Check whether this message is a response or notification
if (msgObj.contains("id"))
{
// Exctract and check ID against the map of previously made requests
int nMsgId = msgObj["id"].toInt();
if (!msgObj["error"].isUndefined() && !msgObj["error"].isNull())
{
// QString errType = msgObj["error"].toString();
// if (errType == "actNotFound") ...
// TODO: Network error handling
// Remove message ID from the map and return
nmReqMap.erase(nMsgId);
return;
}
if (msgObj["result"].isNull() || msgObj["result"].isUndefined())
{
qDebug() << "Something went wrong, NULL data received instead of proper response";
// Remove message ID from the map and return
nmReqMap.erase(nMsgId);
return;
}
try
{
// Find message type
auto msgKind = nmReqMap.at(nMsgId);
// Remove message ID from the map
nmReqMap.erase(nMsgId);
switch(msgKind)
{
case MSG_ACCOUNT_INFO:
return accInfoResponse(msgObj);
case MSG_ACCOUNT_TX:
return accTxResponse(msgObj);
case MSG_SUBMIT_TX:
return submitResponse(msgObj);
case MSG_SUBSCRIBE_LEDGER_AND_ACCOUNT:
return subsLedgerAndAccountResponse(msgObj);
}
}
catch(std::out_of_range e)
{
qDebug() << "Unrequested message received: " << psMsg;
}
}
if (msgObj.contains("type"))
{
// New transaction accepted
if (msgObj["type"] == "transaction")
return processTxMessage(msgObj);
// New ledger closed
if (msgObj["type"] == "ledgerClosed")
return processLedgerMessage(msgObj);
}
}
void WalletMain::processTxMessage(QJsonObject poTxn)
{
auto txMetaObj = poTxn["meta"].toObject();
auto txObj = poTxn["transaction"].toObject();
// Ignore unsuccessful transactions
if (poTxn["engine_result"] != "tesSUCCESS")
return accInfoRequest();
// Parse transaction metadata
if (txObj["TransactionType"] == "Payment" && !txObj["Amount"].isObject())
{
// Parse affected nodes list
for (const auto& affRecord : txMetaObj["AffectedNodes"].toArray())
{
QJsonObject fieldsObj;
// Check if our account was created just now
if (affRecord.toObject()["CreatedNode"].isObject())
{
auto nodeObj = affRecord.toObject()["CreatedNode"].toObject();
if (nodeObj["LedgerEntryType"] == "AccountRoot") {
fieldsObj = nodeObj["NewFields"].toObject();
} else continue;
}
else
{
auto nodeObj = affRecord.toObject()["ModifiedNode"].toObject();
if (nodeObj["LedgerEntryType"] == "AccountRoot") {
fieldsObj = nodeObj["FinalFields"].toObject();
} else continue;
}
auto it = std::find(vsAccounts.begin(), vsAccounts.end(), fieldsObj["Account"]);
if (it != vsAccounts.end())
{
int nAccountIndex = std::distance(vsAccounts.begin(), it);
vnBalances[nAccountIndex] = fieldsObj["Balance"].toString().toDouble();
vnSequences[nAccountIndex] = fieldsObj["Sequence"].toDouble();
}
}
auto it1 = std::find(vsAccounts.begin(), vsAccounts.end(), txObj["Account"]);
auto it2 = std::find(vsAccounts.begin(), vsAccounts.end(), txObj["Destination"]);
if (it1 != vsAccounts.end())
{
// We are sender, add debit record
int acc_idx = std::distance(vsAccounts.begin(), it1);
auto& rowData = vtTransactions[acc_idx];
rowData.insert(rowData.begin(), {
timeFormat(txObj["date"].toInt()),
txObj["TransactionType"].toString(),
txObj["hash"].toString(),
AmountWithSign(txObj["Amount"].toString().toDouble(), true),
QJsonDocument(txObj).toJson()
});
if (nMainAccount == acc_idx)
refreshTxView();
}
if (it2 != vsAccounts.end())
{
// We are receiver, add credit record
int acc_idx = std::distance(vsAccounts.begin(), it2);
auto& rowData = vtTransactions[acc_idx];
rowData.insert(rowData.begin(), {
timeFormat(txObj["date"].toInt()),
txObj["TransactionType"].toString(),
txObj["hash"].toString(),
AmountWithSign(txObj["Amount"].toString().toDouble()),
QJsonDocument(txObj).toJson()
});
if (nMainAccount == acc_idx)
refreshTxView();
}
}
else
{
// No support for "complex" transactions yet, just ask to send us fresh transaction list
accTxRequest();
}
// Update current ledger index
ledgerLabel.setText("Current ledger: " + QString("%1").arg(poTxn["ledger_index"].toDouble()));
}
void WalletMain::processLedgerMessage(QJsonObject poLedger)
{
nIndex = poLedger["ledger_index"].toDouble();
nFee = poLedger["fee_base"].toDouble();
nFeeRef = poLedger["fee_ref"].toDouble();
nReserve = poLedger["reserve_base"].toDouble();
sHash = poLedger["ledger_hash"].toString();
nCloseTime = poLedger["ledger_time"].toDouble();
nTxes = poLedger["txn_count"].toInt();
setOnline(true, QString("ledger %1 closed").arg(sHash.left(6)));
}
void WalletMain::accInfoResponse(const QJsonObject& poResp)
{
auto result = poResp["result"].toObject();
auto accountData = result["account_data"].toObject();
auto it = std::find(vsAccounts.begin(), vsAccounts.end(), accountData["Account"]);
if (it != vsAccounts.end())
{
auto acc_idx = std::distance(vsAccounts.begin(), it);
vnSequences[acc_idx] = accountData["Sequence"].toDouble();
vnBalances[acc_idx] = accountData["Balance"].toString().toDouble();
}
setOnline(true, "Account info retrieved");
}
void WalletMain::accTxResponse(const QJsonObject& poResp)
{
QJsonObject result = poResp["result"].toObject();
QJsonArray txes = result["transactions"].toArray();
// Get account ID as string.
QString strAccountID = result["account"].toString();
auto it = std::find(vsAccounts.begin(), vsAccounts.end(), strAccountID);
auto acc_idx = std::distance(vsAccounts.begin(), it);
auto& rowData = vtTransactions[acc_idx];
rowData.clear();
for (int i = 0; i < txes.size(); i++)
{
QJsonObject txObj = txes[i].toObject();
if (!txObj["validated"].toBool())
continue;
if (txObj["meta"].toObject()["TransactionResult"].toString() != "tesSUCCESS")
continue;
txObj = txObj["tx"].toObject();
bool isDebit = (txObj["Destination"].toString() != strAccountID);
rowData.insert(rowData.end(), std::vector<QString> {
timeFormat(txObj["date"].toDouble()),
txObj["TransactionType"].toString(),
txObj["hash"].toString(),
AmountWithSign(txObj["Amount"].toString().toDouble(), isDebit),
QJsonDocument(txObj).toJson()
});
}
if (nMainAccount == acc_idx)
refreshTxView();
setOnline(true, "New transaction entry received");
}
void WalletMain::refreshTxView()
{
const auto& rowData = vtTransactions[nMainAccount];
ui->txView->clearContents();
ui->txView->setRowCount(rowData.size());
for (auto nRow = 0u; nRow < rowData.size(); ++nRow)
{
for (auto nCol = 0u; nCol < rowData[nRow].size(); ++nCol)
{
QTableWidgetItem *newItem = new QTableWidgetItem();
newItem->setText(rowData[nRow][nCol]);
if (nCol == 5) newItem->setTextAlignment(Qt::AlignRight);
ui->txView->setItem( nRow, nCol, newItem);
}
}
}
void WalletMain::submitResponse(const QJsonObject& poResp)
{
QJsonObject result = poResp["result"].toObject();
if (result["status"] == "error")
Show("Transaction error", QString("Failure while committing transaction to the STM network: ") + poResp["error_message"].toString(), E_WARN);
else if (result["engine_result"].toString() != "tesSUCCESS")
Show("Transaction error", QString("Error while processing transaction by the STM network: ") + result["engine_result_message"].toString(), E_WARN);
else
Show("Transaction applied", result["engine_result_message"].toString(), E_INFO);
}
void WalletMain::subsLedgerAndAccountResponse(const QJsonObject& poResp)
{
QJsonObject result = poResp["result"].toObject();
nFee = result["fee_base"].toDouble();
nFeeRef = result["fee_ref"].toDouble();
nIndex = result["ledger_index"].toDouble();
nReserve = result["reserve_base"].toDouble();
setOnline(true, "Subscribed to ledger and account notifications");
}
void WalletMain::accInfoRequest(QJsonArray poAccs)
{
for (const auto& accountID : (poAccs.size() > 0 ? poAccs : vsAccounts))
{
// Request account info
nmReqMap[nRequestID] = MSG_ACCOUNT_INFO;
wSockConn.sendTextMessage(
QJsonDocument(
QJsonObject {
{"id", nRequestID++},
{"command", "account_info"},
{"account", accountID.toString() },
}).toJson());
}
}
void WalletMain::accTxRequest(QJsonArray poAccs)
{
for (const auto& accountID : (poAccs.size() > 0 ? poAccs : vsAccounts))
{
// Request account transactions
nmReqMap[nRequestID] = MSG_ACCOUNT_TX;
wSockConn.sendTextMessage(
QJsonDocument(
QJsonObject {
{"id", nRequestID++},
{"command", "account_tx"},
{"account", accountID.toString() },
{"ledger_index_min", -1 },
{"ledger_index_max", -1 },
//{"limit", -1 },
{"forward", false },
}).toJson());
}
}
void WalletMain::submitRequest(QString hexBlobData)
{
nmReqMap[nRequestID] = MSG_SUBMIT_TX;
wSockConn.sendTextMessage(
QJsonDocument(
QJsonObject {
{"id", nRequestID++},
{"command", "submit"},
{"tx_blob", hexBlobData },
{"fail_hard", true}
}).toJson());
}
void WalletMain::subsLedgerAndAccountRequest()
{
// Subscribe to ledger and account streams
nmReqMap[nRequestID] = MSG_SUBSCRIBE_LEDGER_AND_ACCOUNT;
wSockConn.sendTextMessage(
QJsonDocument(
QJsonObject {
{"id", nRequestID++},
{"command", "subscribe"},
{"accounts", vsAccounts },
{"streams", QJsonArray { "ledger" } },
}).toJson());
}
void WalletMain::sendPayment(bool pbJustAsk)
{
auto& kData = vkStore[nMainAccount];
if (ui->receiverAddressEdit->text() == ripple::toBase58(kData.raAccountID).c_str() )
return Show("Error", "Sending to self basically has no sense and is not supported.", E_WARN);
QString sHex, sJSON;
QString sRecvAcc = ui->receiverAddressEdit->text();
int64_t nAmount = readDouble(ui->amountToSend) * coinAsInt;
int64_t nTagID = readInt(ui->destinationTag);
int64_t nTxFee = readDouble(ui->sendTransactionFeeValue) * coinAsInt;
if (nTxFee == 0) nTxFee = nFeeRef;
if (nAmount > (vnBalances[nMainAccount] - nTxFee - nReserve))
return Show("Warning", "Transaction amount is greater than amount of available funds. This could happen if your available balance doesn't comply with either fee or reserve requirements.", E_WARN);
auto eRes = createPaymentTx(sRecvAcc, nAmount, nTxFee, nTagID, sJSON, sHex);
if (eNone == eRes)
{
int nExpected = 0;
QDialog* qActionDlg = nullptr;
if (pbJustAsk)
{
QString strConf = "I'm about to send " + ui->amountToSend->text()
+ " STM to " + ui->receiverAddressEdit->text() + ". Do you agree?";
nExpected = QMessageBox::Yes;
qActionDlg = new QMessageBox(QMessageBox::Information, "Confirmation", strConf, QMessageBox::Yes | QMessageBox::No);
}
else
{
nExpected = QDialog::Accepted;
qActionDlg = new TransactionPreview(nullptr, sJSON, sHex);
}
auto nChoice = qActionDlg->exec();
delete qActionDlg;
if (nChoice == nExpected)
{
// Submit transaction and disable send button till confirmation from server
submitRequest(sHex);
ui->sendButton->setEnabled(false);
ui->previewButton->setEnabled(false);
ui->receiverAddressEdit->setText("");
ui->amountToSend->setText("");
ui->destinationTag->setText("");
}
return;
}
if (eRes != eNoPassword)
Show(eRes);
}
// Interface handlers
void WalletMain::txItemClicked(int pnRow, int pnCol)
{
Q_UNUSED(pnCol);
QTableWidgetItem *item = new QTableWidgetItem;
item = ui->txView->item(pnRow, 4);
TransactionView txDlg(nullptr, item->text());
txDlg.exec();
}
void WalletMain::on_actionExit_triggered()
{
qApp->quit();
}
void WalletMain::on_clearButton_clicked()
{
ui->receiverAddressEdit->setText("");
ui->amountToSend->setText("");
ui->destinationTag->setText("");
}
void WalletMain::on_previewButton_clicked()
{
sendPayment(false);
}
void WalletMain::on_sendButton_clicked()
{
sendPayment(true);
}