-
Notifications
You must be signed in to change notification settings - Fork 0
/
WalletService.cpp
1435 lines (1124 loc) · 53.3 KB
/
WalletService.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
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
// Copyright (c) 2014-2018, The Monero Project
// Copyright (c) 2018, The MONCoin Developers
//
// Please see the included LICENSE file for more information.
#include "WalletService.h"
#include <future>
#include <assert.h>
#include <sstream>
#include <unordered_set>
#include <tuple>
#include <boost/filesystem/operations.hpp>
#include <System/Timer.h>
#include <System/InterruptedException.h>
#include "Common/Base58.h"
#include "Common/Util.h"
#include "crypto/crypto.h"
#include "CryptoNote.h"
#include "CryptoNoteCore/CryptoNoteFormatUtils.h"
#include "CryptoNoteCore/CryptoNoteBasicImpl.h"
#include "CryptoNoteCore/CryptoNoteTools.h"
#include "CryptoNoteCore/TransactionExtra.h"
#include "CryptoNoteCore/Account.h"
#include "CryptoNoteCore/Mixins.h"
#include <System/EventLock.h>
#include <System/RemoteContext.h>
#include "PaymentServiceJsonRpcMessages.h"
#include "NodeFactory.h"
#include "Wallet/WalletGreen.h"
#include "Wallet/WalletErrors.h"
#include "Wallet/WalletUtils.h"
#include "WalletServiceErrorCategory.h"
#include "Mnemonics/Mnemonics.h"
namespace PaymentService {
namespace {
bool checkPaymentId(const std::string& paymentId) {
if (paymentId.size() != 64) {
return false;
}
return std::all_of(paymentId.begin(), paymentId.end(), [] (const char c) {
if (c >= '0' && c <= '9') {
return true;
}
if (c >= 'a' && c <= 'f') {
return true;
}
if (c >= 'A' && c <= 'F') {
return true;
}
return false;
});
}
Crypto::Hash parsePaymentId(const std::string& paymentIdStr) {
if (!checkPaymentId(paymentIdStr)) {
throw std::system_error(make_error_code(CryptoNote::error::WalletServiceErrorCode::WRONG_PAYMENT_ID_FORMAT));
}
Crypto::Hash paymentId;
bool r = Common::podFromHex(paymentIdStr, paymentId);
if (r) {}
assert(r);
return paymentId;
}
bool getPaymentIdFromExtra(const std::string& binaryString, Crypto::Hash& paymentId) {
return CryptoNote::getPaymentIdFromTxExtra(Common::asBinaryArray(binaryString), paymentId);
}
std::string getPaymentIdStringFromExtra(const std::string& binaryString) {
Crypto::Hash paymentId;
try {
if (!getPaymentIdFromExtra(binaryString, paymentId)) {
return std::string();
}
} catch (std::exception&) {
return std::string();
}
return Common::podToHex(paymentId);
}
}
struct TransactionsInBlockInfoFilter {
TransactionsInBlockInfoFilter(const std::vector<std::string>& addressesVec, const std::string& paymentIdStr) {
addresses.insert(addressesVec.begin(), addressesVec.end());
if (!paymentIdStr.empty()) {
paymentId = parsePaymentId(paymentIdStr);
havePaymentId = true;
} else {
havePaymentId = false;
}
}
bool checkTransaction(const CryptoNote::WalletTransactionWithTransfers& transaction) const {
if (havePaymentId) {
Crypto::Hash transactionPaymentId;
if (!getPaymentIdFromExtra(transaction.transaction.extra, transactionPaymentId)) {
return false;
}
if (paymentId != transactionPaymentId) {
return false;
}
}
if (addresses.empty()) {
return true;
}
bool haveAddress = false;
for (const CryptoNote::WalletTransfer& transfer: transaction.transfers) {
if (addresses.find(transfer.address) != addresses.end()) {
haveAddress = true;
break;
}
}
return haveAddress;
}
std::unordered_set<std::string> addresses;
bool havePaymentId = false;
Crypto::Hash paymentId;
};
namespace {
void addPaymentIdToExtra(const std::string& paymentId, std::string& extra) {
std::vector<uint8_t> extraVector;
if (!CryptoNote::createTxExtraWithPaymentId(paymentId, extraVector)) {
throw std::system_error(make_error_code(CryptoNote::error::BAD_PAYMENT_ID));
}
std::copy(extraVector.begin(), extraVector.end(), std::back_inserter(extra));
}
void validatePaymentId(const std::string& paymentId, Logging::LoggerRef logger) {
if (!checkPaymentId(paymentId)) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Can't validate payment id: " << paymentId;
throw std::system_error(make_error_code(CryptoNote::error::WalletServiceErrorCode::WRONG_PAYMENT_ID_FORMAT));
}
}
Crypto::Hash parseHash(const std::string& hashString, Logging::LoggerRef logger) {
Crypto::Hash hash;
if (!Common::podFromHex(hashString, hash)) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Can't parse hash string " << hashString;
throw std::system_error(make_error_code(CryptoNote::error::WalletServiceErrorCode::WRONG_HASH_FORMAT));
}
return hash;
}
std::vector<CryptoNote::TransactionsInBlockInfo> filterTransactions(
const std::vector<CryptoNote::TransactionsInBlockInfo>& blocks,
const TransactionsInBlockInfoFilter& filter) {
std::vector<CryptoNote::TransactionsInBlockInfo> result;
for (const auto& block: blocks) {
CryptoNote::TransactionsInBlockInfo item;
item.blockHash = block.blockHash;
for (const auto& transaction: block.transactions) {
if (transaction.transaction.state != CryptoNote::WalletTransactionState::DELETED && filter.checkTransaction(transaction)) {
item.transactions.push_back(transaction);
}
}
if (!block.transactions.empty()) {
result.push_back(std::move(item));
}
}
return result;
}
PaymentService::TransactionRpcInfo convertTransactionWithTransfersToTransactionRpcInfo(
const CryptoNote::WalletTransactionWithTransfers& transactionWithTransfers) {
PaymentService::TransactionRpcInfo transactionInfo;
transactionInfo.state = static_cast<uint8_t>(transactionWithTransfers.transaction.state);
transactionInfo.transactionHash = Common::podToHex(transactionWithTransfers.transaction.hash);
transactionInfo.blockIndex = transactionWithTransfers.transaction.blockHeight;
transactionInfo.timestamp = transactionWithTransfers.transaction.timestamp;
transactionInfo.isBase = transactionWithTransfers.transaction.isBase;
transactionInfo.unlockTime = transactionWithTransfers.transaction.unlockTime;
transactionInfo.amount = transactionWithTransfers.transaction.totalAmount;
transactionInfo.fee = transactionWithTransfers.transaction.fee;
transactionInfo.extra = Common::toHex(transactionWithTransfers.transaction.extra.data(), transactionWithTransfers.transaction.extra.size());
transactionInfo.paymentId = getPaymentIdStringFromExtra(transactionWithTransfers.transaction.extra);
for (const CryptoNote::WalletTransfer& transfer: transactionWithTransfers.transfers) {
PaymentService::TransferRpcInfo rpcTransfer;
rpcTransfer.address = transfer.address;
rpcTransfer.amount = transfer.amount;
rpcTransfer.type = static_cast<uint8_t>(transfer.type);
transactionInfo.transfers.push_back(std::move(rpcTransfer));
}
return transactionInfo;
}
std::vector<PaymentService::TransactionsInBlockRpcInfo> convertTransactionsInBlockInfoToTransactionsInBlockRpcInfo(
const std::vector<CryptoNote::TransactionsInBlockInfo>& blocks) {
std::vector<PaymentService::TransactionsInBlockRpcInfo> rpcBlocks;
rpcBlocks.reserve(blocks.size());
for (const auto& block: blocks) {
PaymentService::TransactionsInBlockRpcInfo rpcBlock;
rpcBlock.blockHash = Common::podToHex(block.blockHash);
for (const CryptoNote::WalletTransactionWithTransfers& transactionWithTransfers: block.transactions) {
PaymentService::TransactionRpcInfo transactionInfo = convertTransactionWithTransfersToTransactionRpcInfo(transactionWithTransfers);
rpcBlock.transactions.push_back(std::move(transactionInfo));
}
rpcBlocks.push_back(std::move(rpcBlock));
}
return rpcBlocks;
}
std::vector<PaymentService::TransactionHashesInBlockRpcInfo> convertTransactionsInBlockInfoToTransactionHashesInBlockRpcInfo(
const std::vector<CryptoNote::TransactionsInBlockInfo>& blocks) {
std::vector<PaymentService::TransactionHashesInBlockRpcInfo> transactionHashes;
transactionHashes.reserve(blocks.size());
for (const CryptoNote::TransactionsInBlockInfo& block: blocks) {
PaymentService::TransactionHashesInBlockRpcInfo item;
item.blockHash = Common::podToHex(block.blockHash);
for (const CryptoNote::WalletTransactionWithTransfers& transaction: block.transactions) {
item.transactionHashes.emplace_back(Common::podToHex(transaction.transaction.hash));
}
transactionHashes.push_back(std::move(item));
}
return transactionHashes;
}
void validateAddresses(const std::vector<std::string>& addresses, const CryptoNote::Currency& currency, Logging::LoggerRef logger) {
for (const auto& address: addresses) {
if (!CryptoNote::validateAddress(address, currency)) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Can't validate address " << address;
throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS));
}
}
}
std::tuple<std::string, std::string> decodeIntegratedAddress(const std::string& integratedAddr, const CryptoNote::Currency& currency, Logging::LoggerRef logger) {
std::string decoded;
uint64_t prefix;
/* Need to be able to decode the string as an address */
if (!Tools::Base58::decode_addr(integratedAddr, prefix, decoded))
{
throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS));
}
/* The prefix needs to be the same as the base58 prefix */
if (prefix !=
CryptoNote::parameters::CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX)
{
throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS));
}
const uint64_t paymentIDLen = 64;
/* Grab the payment ID from the decoded address */
std::string paymentID = decoded.substr(0, paymentIDLen);
/* Check the extracted payment ID is good. */
validatePaymentId(paymentID, logger);
/* The binary array encoded keys are the rest of the address */
std::string keys = decoded.substr(paymentIDLen, std::string::npos);
CryptoNote::AccountPublicAddress addr;
CryptoNote::BinaryArray ba = Common::asBinaryArray(keys);
if (!CryptoNote::fromBinaryArray(addr, ba))
{
throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS));
}
/* Parse the AccountPublicAddress into a standard wallet address */
/* Use the calculated prefix from earlier for less typing :p */
std::string address = CryptoNote::getAccountAddressAsStr(prefix, addr);
/* Check the extracted address is good. */
validateAddresses({address}, currency, logger);
return std::make_tuple(address, paymentID);
}
std::string getValidatedTransactionExtraString(const std::string& extraString) {
std::vector<uint8_t> binary;
if (!Common::fromHex(extraString, binary)) {
throw std::system_error(make_error_code(CryptoNote::error::BAD_TRANSACTION_EXTRA));
}
return Common::asString(binary);
}
std::vector<std::string> collectDestinationAddresses(const std::vector<PaymentService::WalletRpcOrder>& orders) {
std::vector<std::string> result;
result.reserve(orders.size());
for (const auto& order: orders) {
result.push_back(order.address);
}
return result;
}
std::vector<CryptoNote::WalletOrder> convertWalletRpcOrdersToWalletOrders(const std::vector<PaymentService::WalletRpcOrder>& orders, const std::string nodeAddress, const uint32_t nodeFee) {
std::vector<CryptoNote::WalletOrder> result;
if (!nodeAddress.empty() && nodeFee != 0) {
result.reserve(orders.size() + 1);
result.emplace_back(CryptoNote::WalletOrder {nodeAddress, nodeFee});
} else {
result.reserve(orders.size());
}
for (const auto& order: orders) {
result.emplace_back(CryptoNote::WalletOrder {order.address, order.amount});
}
return result;
}
}
void generateNewWallet(const CryptoNote::Currency& currency, const WalletConfiguration& conf, std::shared_ptr<Logging::ILogger> logger, System::Dispatcher& dispatcher) {
Logging::LoggerRef log(logger, "generateNewWallet");
CryptoNote::INode* nodeStub = NodeFactory::createNodeStub();
std::unique_ptr<CryptoNote::INode> nodeGuard(nodeStub);
CryptoNote::IWallet* wallet = new CryptoNote::WalletGreen(dispatcher, currency, *nodeStub, logger);
std::unique_ptr<CryptoNote::IWallet> walletGuard(wallet);
std::string address;
if (conf.secretSpendKey.empty() && conf.secretViewKey.empty() && conf.mnemonicSeed.empty())
{
log(Logging::INFO, Logging::BRIGHT_WHITE) << "Generating new wallet";
Crypto::SecretKey private_view_key;
CryptoNote::KeyPair spendKey;
Crypto::generate_keys(spendKey.publicKey, spendKey.secretKey);
CryptoNote::AccountBase::generateViewFromSpend(spendKey.secretKey, private_view_key);
wallet->initializeWithViewKey(conf.walletFile, conf.walletPassword, private_view_key, 0, true);
address = wallet->createAddress(spendKey.secretKey, 0, true);
log(Logging::INFO, Logging::BRIGHT_WHITE) << "New wallet is generated. Address: " << address;
}
else if (!conf.mnemonicSeed.empty())
{
log(Logging::INFO, Logging::BRIGHT_WHITE) << "Attempting to import wallet from mnemonic seed";
auto [error, private_spend_key] = Mnemonics::MnemonicToPrivateKey(conf.mnemonicSeed);
if (error)
{
log(Logging::ERROR, Logging::BRIGHT_RED) << error;
return;
}
Crypto::SecretKey private_view_key;
CryptoNote::AccountBase::generateViewFromSpend(private_spend_key, private_view_key);
wallet->initializeWithViewKey(conf.walletFile, conf.walletPassword, private_view_key, conf.scanHeight, false);
address = wallet->createAddress(private_spend_key, conf.scanHeight, false);
log(Logging::INFO, Logging::BRIGHT_WHITE) << "Imported wallet successfully.";
}
else
{
if (conf.secretSpendKey.empty() || conf.secretViewKey.empty())
{
log(Logging::ERROR, Logging::BRIGHT_RED) << "Need both secret spend key and secret view key.";
return;
}
else
{
log(Logging::INFO, Logging::BRIGHT_WHITE) << "Attemping to import wallet from keys";
Crypto::Hash private_spend_key_hash;
Crypto::Hash private_view_key_hash;
uint64_t size;
if (!Common::fromHex(conf.secretSpendKey, &private_spend_key_hash, sizeof(private_spend_key_hash), size) || size != sizeof(private_spend_key_hash)) {
log(Logging::ERROR, Logging::BRIGHT_RED) << "Invalid spend key";
return;
}
if (!Common::fromHex(conf.secretViewKey, &private_view_key_hash, sizeof(private_view_key_hash), size) || size != sizeof(private_spend_key_hash)) {
log(Logging::ERROR, Logging::BRIGHT_RED) << "Invalid view key";
return;
}
Crypto::SecretKey private_spend_key = *(struct Crypto::SecretKey *) &private_spend_key_hash;
Crypto::SecretKey private_view_key = *(struct Crypto::SecretKey *) &private_view_key_hash;
wallet->initializeWithViewKey(conf.walletFile, conf.walletPassword, private_view_key, conf.scanHeight, false);
address = wallet->createAddress(private_spend_key, conf.scanHeight, false);
log(Logging::INFO, Logging::BRIGHT_WHITE) << "Imported wallet successfully.";
}
}
wallet->save(CryptoNote::WalletSaveLevel::SAVE_KEYS_ONLY);
log(Logging::INFO, Logging::BRIGHT_WHITE) << "Wallet is saved";
}
WalletService::WalletService(const CryptoNote::Currency& currency, System::Dispatcher& sys, CryptoNote::INode& node,
CryptoNote::IWallet& wallet, CryptoNote::IFusionManager& fusionManager, const WalletConfiguration& conf, std::shared_ptr<Logging::ILogger> logger) :
currency(currency),
wallet(wallet),
fusionManager(fusionManager),
node(node),
config(conf),
inited(false),
logger(logger, "WalletService"),
dispatcher(sys),
readyEvent(dispatcher),
refreshContext(dispatcher)
{
readyEvent.set();
}
WalletService::~WalletService() {
if (inited) {
wallet.stop();
refreshContext.wait();
wallet.shutdown();
}
}
void WalletService::init() {
loadWallet();
loadTransactionIdIndex();
getNodeFee();
refreshContext.spawn([this] { refresh(); });
inited = true;
}
void WalletService::getNodeFee() {
logger(Logging::DEBUGGING) <<
"Trying to retrieve node fee information." << std::endl;
m_node_address = node.feeAddress();
m_node_fee = node.feeAmount();
if (!m_node_address.empty() && m_node_fee != 0) {
// Partially borrowed from <zedwallet/Tools.h>
uint32_t div = static_cast<uint32_t>(pow(10, CryptoNote::parameters::CRYPTONOTE_DISPLAY_DECIMAL_POINT));
uint32_t coins = m_node_fee / div;
uint32_t cents = m_node_fee % div;
std::stringstream stream;
stream << std::setfill('0') << std::setw(CryptoNote::parameters::CRYPTONOTE_DISPLAY_DECIMAL_POINT) << cents;
std::string amount = std::to_string(coins) + "." + stream.str();
logger(Logging::INFO, Logging::RED) <<
"You have connected to a node that charges " <<
"a fee to send transactions." << std::endl;
logger(Logging::INFO, Logging::RED) <<
"The fee for sending transactions is: " <<
amount << " per transaction." << std::endl ;
logger(Logging::INFO, Logging::RED) <<
"If you don't want to pay the node fee, please " <<
"relaunch this program and specify a different " <<
"node or run your own." << std::endl;
}
}
void WalletService::saveWallet() {
wallet.save();
logger(Logging::INFO, Logging::BRIGHT_WHITE) << "Wallet is saved";
}
void WalletService::loadWallet() {
logger(Logging::INFO, Logging::BRIGHT_WHITE) << "Loading wallet";
wallet.load(config.walletFile, config.walletPassword);
logger(Logging::INFO, Logging::BRIGHT_WHITE) << "Wallet loading is finished.";
}
void WalletService::loadTransactionIdIndex() {
transactionIdIndex.clear();
for (size_t i = 0; i < wallet.getTransactionCount(); ++i) {
transactionIdIndex.emplace(Common::podToHex(wallet.getTransaction(i).hash), i);
}
}
std::error_code WalletService::saveWalletNoThrow() {
try {
System::EventLock lk(readyEvent);
logger(Logging::INFO, Logging::BRIGHT_WHITE) << "Saving wallet...";
if (!inited) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Save impossible: Wallet Service is not initialized";
return make_error_code(CryptoNote::error::NOT_INITIALIZED);
}
saveWallet();
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while saving wallet: " << x.what();
return x.code();
} catch (std::exception& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while saving wallet: " << x.what();
return make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR);
}
return std::error_code();
}
std::error_code WalletService::exportWallet(const std::string& fileName) {
try {
System::EventLock lk(readyEvent);
if (!inited) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Export impossible: Wallet Service is not initialized";
return make_error_code(CryptoNote::error::NOT_INITIALIZED);
}
boost::filesystem::path walletPath(config.walletFile);
boost::filesystem::path exportPath = walletPath.parent_path() / fileName;
logger(Logging::INFO, Logging::BRIGHT_WHITE) << "Exporting wallet to " << exportPath.string();
wallet.exportWallet(exportPath.string());
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while exporting wallet: " << x.what();
return x.code();
} catch (std::exception& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while exporting wallet: " << x.what();
return make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR);
}
return std::error_code();
}
std::error_code WalletService::resetWallet(const uint64_t scanHeight) {
try {
System::EventLock lk(readyEvent);
logger(Logging::INFO, Logging::BRIGHT_WHITE) << "Resetting wallet";
if (!inited) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Reset impossible: Wallet Service is not initialized";
return make_error_code(CryptoNote::error::NOT_INITIALIZED);
}
reset(scanHeight);
logger(Logging::INFO, Logging::BRIGHT_WHITE) << "Wallet has been reset";
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while resetting wallet: " << x.what();
return x.code();
} catch (std::exception& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while resetting wallet: " << x.what();
return make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR);
}
return std::error_code();
}
std::error_code WalletService::createAddress(const std::string& spendSecretKeyText, uint64_t scanHeight, bool newAddress, std::string& address) {
try {
System::EventLock lk(readyEvent);
logger(Logging::DEBUGGING) << "Creating address";
Crypto::SecretKey secretKey;
if (!Common::podFromHex(spendSecretKeyText, secretKey)) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Wrong key format: " << spendSecretKeyText;
return make_error_code(CryptoNote::error::WalletServiceErrorCode::WRONG_KEY_FORMAT);
}
address = wallet.createAddress(secretKey, scanHeight, newAddress);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while creating address: " << x.what();
return x.code();
}
logger(Logging::DEBUGGING) << "Created address " << address;
return std::error_code();
}
std::error_code WalletService::createAddressList(const std::vector<std::string>& spendSecretKeysText, uint64_t scanHeight, bool newAddress, std::vector<std::string>& addresses) {
try {
System::EventLock lk(readyEvent);
logger(Logging::DEBUGGING) << "Creating " << spendSecretKeysText.size() << " addresses...";
std::vector<Crypto::SecretKey> secretKeys;
std::unordered_set<std::string> unique;
secretKeys.reserve(spendSecretKeysText.size());
unique.reserve(spendSecretKeysText.size());
for (auto& keyText : spendSecretKeysText) {
auto insertResult = unique.insert(keyText);
if (!insertResult.second) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Not unique key";
return make_error_code(CryptoNote::error::WalletServiceErrorCode::DUPLICATE_KEY);
}
Crypto::SecretKey key;
if (!Common::podFromHex(keyText, key)) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Wrong key format: " << keyText;
return make_error_code(CryptoNote::error::WalletServiceErrorCode::WRONG_KEY_FORMAT);
}
secretKeys.push_back(std::move(key));
}
addresses = wallet.createAddressList(secretKeys, scanHeight, newAddress);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while creating addresses: " << x.what();
return x.code();
}
logger(Logging::DEBUGGING) << "Created " << addresses.size() << " addresses";
return std::error_code();
}
std::error_code WalletService::createAddress(std::string& address) {
try {
System::EventLock lk(readyEvent);
logger(Logging::DEBUGGING) << "Creating address";
address = wallet.createAddress();
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while creating address: " << x.what();
return x.code();
}
logger(Logging::DEBUGGING) << "Created address " << address;
return std::error_code();
}
std::error_code WalletService::createTrackingAddress(const std::string& spendPublicKeyText, uint64_t scanHeight, bool newAddress, std::string& address) {
try {
System::EventLock lk(readyEvent);
logger(Logging::DEBUGGING) << "Creating tracking address";
Crypto::PublicKey publicKey;
if (!Common::podFromHex(spendPublicKeyText, publicKey)) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Wrong key format: " << spendPublicKeyText;
return make_error_code(CryptoNote::error::WalletServiceErrorCode::WRONG_KEY_FORMAT);
}
address = wallet.createAddress(publicKey, scanHeight, true);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while creating tracking address: " << x.what();
return x.code();
}
logger(Logging::DEBUGGING) << "Created address " << address;
return std::error_code();
}
std::error_code WalletService::deleteAddress(const std::string& address) {
try {
System::EventLock lk(readyEvent);
logger(Logging::DEBUGGING) << "Delete address request came";
wallet.deleteAddress(address);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while deleting address: " << x.what();
return x.code();
}
logger(Logging::DEBUGGING) << "Address " << address << " successfully deleted";
return std::error_code();
}
std::error_code WalletService::getSpendkeys(const std::string& address, std::string& publicSpendKeyText, std::string& secretSpendKeyText) {
try {
System::EventLock lk(readyEvent);
CryptoNote::KeyPair key = wallet.getAddressSpendKey(address);
publicSpendKeyText = Common::podToHex(key.publicKey);
secretSpendKeyText = Common::podToHex(key.secretKey);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting spend key: " << x.what();
return x.code();
}
return std::error_code();
}
std::error_code WalletService::getBalance(const std::string& address, uint64_t& availableBalance, uint64_t& lockedAmount) {
try {
System::EventLock lk(readyEvent);
logger(Logging::DEBUGGING) << "Getting balance for address " << address;
availableBalance = wallet.getActualBalance(address);
lockedAmount = wallet.getPendingBalance(address);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting balance: " << x.what();
return x.code();
}
logger(Logging::DEBUGGING) << address << " actual balance: " << availableBalance << ", pending: " << lockedAmount;
return std::error_code();
}
std::error_code WalletService::getBalance(uint64_t& availableBalance, uint64_t& lockedAmount) {
try {
System::EventLock lk(readyEvent);
logger(Logging::DEBUGGING) << "Getting wallet balance";
availableBalance = wallet.getActualBalance();
lockedAmount = wallet.getPendingBalance();
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting balance: " << x.what();
return x.code();
}
logger(Logging::DEBUGGING) << "Wallet actual balance: " << availableBalance << ", pending: " << lockedAmount;
return std::error_code();
}
std::error_code WalletService::getBlockHashes(uint32_t firstBlockIndex, uint32_t blockCount, std::vector<std::string>& blockHashes) {
try {
System::EventLock lk(readyEvent);
std::vector<Crypto::Hash> hashes = wallet.getBlockHashes(firstBlockIndex, blockCount);
blockHashes.reserve(hashes.size());
for (const auto& hash: hashes) {
blockHashes.push_back(Common::podToHex(hash));
}
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting block hashes: " << x.what();
return x.code();
}
return std::error_code();
}
std::error_code WalletService::getViewKey(std::string& viewSecretKey) {
try {
System::EventLock lk(readyEvent);
CryptoNote::KeyPair viewKey = wallet.getViewKey();
viewSecretKey = Common::podToHex(viewKey.secretKey);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting view key: " << x.what();
return x.code();
}
return std::error_code();
}
std::error_code WalletService::getMnemonicSeed(const std::string& address, std::string& mnemonicSeed) {
try {
System::EventLock lk(readyEvent);
CryptoNote::KeyPair key = wallet.getAddressSpendKey(address);
CryptoNote::KeyPair viewKey = wallet.getViewKey();
Crypto::SecretKey deterministic_private_view_key;
CryptoNote::AccountBase::generateViewFromSpend(key.secretKey, deterministic_private_view_key);
bool deterministic_private_keys = deterministic_private_view_key == viewKey.secretKey;
if (deterministic_private_keys) {
mnemonicSeed = Mnemonics::PrivateKeyToMnemonic(key.secretKey);
} else {
/* Have to be able to derive view key from spend key to create a mnemonic
seed, due to being able to generate multiple addresses we can't do
this in walletd as the default */
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Your private keys are not deterministic and so a mnemonic seed cannot be generated!";
return make_error_code(CryptoNote::error::WalletServiceErrorCode::KEYS_NOT_DETERMINISTIC);
}
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting mnemonic seed: " << x.what();
return x.code();
}
return std::error_code();
}
std::error_code WalletService::getTransactionHashes(const std::vector<std::string>& addresses, const std::string& blockHashString,
uint32_t blockCount, const std::string& paymentId, std::vector<TransactionHashesInBlockRpcInfo>& transactionHashes) {
try {
System::EventLock lk(readyEvent);
validateAddresses(addresses, currency, logger);
if (!paymentId.empty()) {
validatePaymentId(paymentId, logger);
}
TransactionsInBlockInfoFilter transactionFilter(addresses, paymentId);
Crypto::Hash blockHash = parseHash(blockHashString, logger);
transactionHashes = getRpcTransactionHashes(blockHash, blockCount, transactionFilter);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transactions: " << x.what();
return x.code();
} catch (std::exception& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transactions: " << x.what();
return make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR);
}
return std::error_code();
}
std::error_code WalletService::getTransactionHashes(const std::vector<std::string>& addresses, uint32_t firstBlockIndex,
uint32_t blockCount, const std::string& paymentId, std::vector<TransactionHashesInBlockRpcInfo>& transactionHashes) {
try {
System::EventLock lk(readyEvent);
validateAddresses(addresses, currency, logger);
if (!paymentId.empty()) {
validatePaymentId(paymentId, logger);
}
TransactionsInBlockInfoFilter transactionFilter(addresses, paymentId);
transactionHashes = getRpcTransactionHashes(firstBlockIndex, blockCount, transactionFilter);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transactions: " << x.what();
return x.code();
} catch (std::exception& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transactions: " << x.what();
return make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR);
}
return std::error_code();
}
std::error_code WalletService::getTransactions(const std::vector<std::string>& addresses, const std::string& blockHashString,
uint32_t blockCount, const std::string& paymentId, std::vector<TransactionsInBlockRpcInfo>& transactions) {
try {
System::EventLock lk(readyEvent);
validateAddresses(addresses, currency, logger);
if (!paymentId.empty()) {
validatePaymentId(paymentId, logger);
}
TransactionsInBlockInfoFilter transactionFilter(addresses, paymentId);
Crypto::Hash blockHash = parseHash(blockHashString, logger);
transactions = getRpcTransactions(blockHash, blockCount, transactionFilter);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transactions: " << x.what();
return x.code();
} catch (std::exception& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transactions: " << x.what();
return make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR);
}
return std::error_code();
}
std::error_code WalletService::getTransactions(const std::vector<std::string>& addresses, uint32_t firstBlockIndex,
uint32_t blockCount, const std::string& paymentId, std::vector<TransactionsInBlockRpcInfo>& transactions) {
try {
System::EventLock lk(readyEvent);
validateAddresses(addresses, currency, logger);
if (!paymentId.empty()) {
validatePaymentId(paymentId, logger);
}
TransactionsInBlockInfoFilter transactionFilter(addresses, paymentId);
transactions = getRpcTransactions(firstBlockIndex, blockCount, transactionFilter);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transactions: " << x.what();
return x.code();
} catch (std::exception& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transactions: " << x.what();
return make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR);
}
return std::error_code();
}
std::error_code WalletService::getTransaction(const std::string& transactionHash, TransactionRpcInfo& transaction) {
try {
System::EventLock lk(readyEvent);
Crypto::Hash hash = parseHash(transactionHash, logger);
CryptoNote::WalletTransactionWithTransfers transactionWithTransfers = wallet.getTransaction(hash);
if (transactionWithTransfers.transaction.state == CryptoNote::WalletTransactionState::DELETED) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Transaction " << transactionHash << " is deleted";
return make_error_code(CryptoNote::error::OBJECT_NOT_FOUND);
}
transaction = convertTransactionWithTransfersToTransactionRpcInfo(transactionWithTransfers);
} catch (std::system_error& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transaction: " << x.what();
return x.code();
} catch (std::exception& x) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Error while getting transaction: " << x.what();
return make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR);
}
return std::error_code();
}
std::error_code WalletService::getAddresses(std::vector<std::string>& addresses) {
try {
System::EventLock lk(readyEvent);
addresses.clear();
addresses.reserve(wallet.getAddressCount());
for (size_t i = 0; i < wallet.getAddressCount(); ++i) {
addresses.push_back(wallet.getAddress(i));
}
} catch (std::exception& e) {
logger(Logging::WARNING, Logging::BRIGHT_YELLOW) << "Can't get addresses: " << e.what();
return make_error_code(CryptoNote::error::INTERNAL_WALLET_ERROR);
}
return std::error_code();
}
std::error_code WalletService::sendTransaction(SendTransaction::Request& request, std::string& transactionHash) {
try {
System::EventLock lk(readyEvent);
/* Integrated address payment ID's are uppercase - lets convert the input
payment ID to upper so we can compare with more ease */
std::transform(request.paymentId.begin(), request.paymentId.end(), request.paymentId.begin(), ::toupper);
std::vector<std::string> paymentIDs;
for (auto &transfer : request.transfers)
{
std::string addr = transfer.address;
/* It's not a standard address. Is it an integrated address? */
if (!CryptoNote::validateAddress(addr, currency))
{
std::string address, paymentID;
std::tie(address, paymentID) = decodeIntegratedAddress(addr, currency, logger);
/* A payment ID was specified with the transaction, and it is not
the same as the decoded one -> we can't send a transaction
with two different payment ID's! */
if (request.paymentId != "" && request.paymentId != paymentID)
{
throw std::system_error(make_error_code(CryptoNote::error::CONFLICTING_PAYMENT_IDS));
}
/* Replace the integrated transfer address with the actual
decoded address */
transfer.address = address;
paymentIDs.push_back(paymentID);
}
}
/* Only one integrated address specified, set the payment ID to the
decoded value */