forked from devaultcrypto/devault
/
rpcwallet.cpp
4519 lines (3954 loc) · 185 KB
/
rpcwallet.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) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <amount.h>
#include <chain.h>
#include <chainparams.h> // for GetConsensus.
#include <config.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <dstencode.h>
#include <init.h>
#include <interfaces/chain.h>
#include <net.h>
#include <policy/fees.h>
#include <policy/policy.h>
#include <pow.h>
#include <rpc/mining.h>
#include <wallet/misc.h>
#include <rpc/util.h>
#include <rpc/rawtransaction.h>
#include <rpc/server.h>
#include <shutdown.h>
#include <timedata.h>
#include <reverse_iterator.h>
#include <util/moneystr.h>
#include <util/system.h>
#include <validation.h>
#include <wallet/coincontrol.h>
#include <wallet/wallet.h>
#include <wallet/walletdb.h>
#include <wallet/walletutil.h>
#include <wallet/walletutil.h>
#include <miner.h> // for CBlockTemplate GenerateUntilShutdown
#include <utxo_functions.h>
#include <univalue.h>
#include <event2/http.h>
#include <thread>
#include <functional>
static std::thread generate_thread;
static std::atomic<bool> stop_generate = false;
// Used for auto threaded generate
void StopGenerateThread() { stop_generate = true;}
static const std::string WALLET_ENDPOINT_BASE = "/wallet/";
static std::string urlDecode(const std::string &urlEncoded) {
std::string res;
if (!urlEncoded.empty()) {
char *decoded = evhttp_uridecode(urlEncoded.c_str(), false, nullptr);
if (decoded) {
res = std::string(decoded);
free(decoded);
}
}
return res;
}
bool GetWalletNameFromJSONRPCRequest(const JSONRPCRequest &request,
std::string &wallet_name) {
if (request.URI.substr(0, WALLET_ENDPOINT_BASE.size()) ==
WALLET_ENDPOINT_BASE) {
// wallet endpoint was used
wallet_name =
urlDecode(request.URI.substr(WALLET_ENDPOINT_BASE.size()));
return true;
}
return false;
}
std::shared_ptr<CWallet>
GetWalletForJSONRPCRequest(const JSONRPCRequest &request) {
std::string wallet_name;
if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) {
std::shared_ptr<CWallet> pwallet = GetWallet(wallet_name);
if (!pwallet) {
throw JSONRPCError(
RPC_WALLET_NOT_FOUND,
"Requested wallet does not exist or is not loaded");
}
return pwallet;
}
std::vector<std::shared_ptr<CWallet>> wallets = GetWallets();
return wallets.size() == 1 || (request.fHelp && wallets.size() > 0)
? wallets[0]
: nullptr;
}
std::string HelpRequiringPassphrase(CWallet *const pwallet) {
return pwallet ? "\nRequires wallet passphrase to "
"be set with walletpassphrase "
"call."
: "";
}
bool EnsureWalletIsAvailable(CWallet *const pwallet, bool avoidException) {
if (pwallet) {
return true;
}
if (avoidException) {
return false;
}
if (!HasWallets()) {
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (wallet "
"method is disabled because "
"no wallet is loaded)");
}
throw JSONRPCError(RPC_WALLET_NOT_SPECIFIED,
"Wallet file not specified (must request wallet RPC "
"through /wallet/<filename> uri-path).");
}
void EnsureWalletIsUnlocked(CWallet *const pwallet) {
if (pwallet->IsLocked()) {
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the "
"wallet passphrase with "
"walletpassphrase first.");
}
}
static void WalletTxToJSON(interfaces::Chain &chain,
interfaces::Chain::Lock &locked_chain,
const CWalletTx &wtx, UniValue &entry) {
int confirms = wtx.GetDepthInMainChain(locked_chain);
entry.pushKV("confirmations", confirms);
if (wtx.IsCoinBase()) {
entry.pushKV("generated", true);
}
if (confirms > 0) {
entry.pushKV("blockhash", wtx.hashBlock.GetHex());
entry.pushKV("blockindex", wtx.nIndex);
entry.pushKV("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime());
} else {
entry.pushKV("trusted", wtx.IsTrusted(locked_chain));
}
uint256 hash = wtx.GetId();
entry.pushKV("txid", hash.GetHex());
UniValue conflicts(UniValue::VARR);
for (const uint256 &conflict : wtx.GetConflicts()) {
conflicts.push_back(conflict.GetHex());
}
entry.pushKV("walletconflicts", conflicts);
entry.pushKV("time", wtx.GetTxTime());
entry.pushKV("timereceived", (int64_t)wtx.nTimeReceived);
for (const auto &item : wtx.mapValue) {
entry.pushKV(item.first, item.second);
}
}
std::string LabelFromValue(const UniValue &value) {
std::string label = value.get_str();
if (label == "*") {
throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, "Invalid label name");
}
return label;
}
std::string generateOneBlock(const Config &config, CScript& coinbaseScript) {
{
// keep cs_main locked.
LOCK(cs_main);
unsigned int nExtraNonce = 0;
std::unique_ptr<CBlockTemplate> pblocktemplate(
BlockAssembler(config, g_mempool)
.CreateNewBlock(coinbaseScript));
if (!pblocktemplate.get()) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
}
CBlock *pblock = &pblocktemplate->block;
IncrementExtraNonce(config, pblock, chainActive.Tip(), nExtraNonce);
while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, config)) {
++pblock->nNonce;
}
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
if (!ProcessNewBlock(config, shared_pblock, true, nullptr)) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
}
return pblock->GetHash().GetHex();
}
}
void generateBlocksUntilShutdown(CWallet* pwallet) {
unsigned blockCount=0;
stop_generate = false;
while (!ShutdownRequested() && !stop_generate) {
if (!pwallet->IsLocked()) {
pwallet->TopUpKeyPool();
}
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwallet->GetKeyFromPool(newKey, false)) {
throw JSONRPCError(
RPC_WALLET_KEYPOOL_RAN_OUT,
"Error: Keypool ran out, please call keypoolrefill first");
}
CScript coinbaseScript = pwallet->GetScriptForMining(newKey);
std::string hex = generateOneBlock(GetConfig(), coinbaseScript);
// Sleep for 10 seconds between blocks to prevent too many
LogPrintf("Block [%d], hash = %s\n",blockCount++, hex);
MilliSleep(10000);
}
}
static UniValue getnewaddress(const Config &config,
const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 1) {
throw std::runtime_error(
"getnewaddress ( \"label\" )\n"
"\nReturns a new Devault address for receiving payments.\n"
"If 'label' is specified, it is added to the address book \n"
"so payments received with the address will be associated with "
"'label'.\n"
"\nArguments:\n"
"1. \"label\" (string, optional) The label name for the "
"address to be linked to. If not provided, the default label \"\" "
"is used. It can also be set to the empty string \"\" to represent "
"the default label. The label does not need to exist, it will be "
"created if there is no label by the given name.\n"
"\nResult:\n"
"\"address\" (string) The new devault address\n"
"\nExamples:\n" +
HelpExampleRpc("getnewaddress", ""));
}
if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
throw JSONRPCError(RPC_WALLET_ERROR,
"Error: Private keys are disabled for this wallet");
}
LOCK2(cs_main, pwallet->cs_wallet);
// Parse the label first so we don't generate a key if there's an error
std::string label;
if (!request.params[0].isNull()) {
label = LabelFromValue(request.params[0]);
}
if (!pwallet->IsLocked()) {
pwallet->TopUpKeyPool();
}
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwallet->GetKeyFromPool(newKey, false)) {
throw JSONRPCError(
RPC_WALLET_KEYPOOL_RAN_OUT,
"Error: Keypool ran out, please call keypoolrefill first");
}
if (pwallet->UseBLSKeys()) {
BKeyID keyID = newKey.GetBLSKeyID();
pwallet->SetAddressBook(keyID, label, "receive");
return EncodeDestination(keyID);
} else {
CKeyID keyID = newKey.GetKeyID();
pwallet->SetAddressBook(keyID, label, "receive");
return EncodeDestination(keyID);
}
}
std::string GetLabelDestination(CWallet *const pwallet, const std::string &label) {
std::string dest;
if (!pwallet->GetLabelDestination(dest, label)) {
throw JSONRPCError(
RPC_MISC_ERROR,
"Error: label has no associated address");
}
return dest;
}
UniValue getlabeladdress(const Config &config, const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1) {
throw std::runtime_error(
"getlabeladdress \"label\"\n"
"\nReturns the current Devault address for receiving payments to "
"this label.\n"
"\nArguments:\n"
"1. \"label\" (string, required) The label name for the "
"address. It can also be set to the empty string \"\" to represent "
"the default label. The label does not need to exist, it will be "
"created and a new address created if there is no label by the "
"given name.\n"
"\nResult:\n"
"\"address\" (string) The label devault address\n"
"\nExamples:\n" +
HelpExampleCli("getlabeladdress", "") +
HelpExampleCli("getlabeladdress", "\"\"") +
HelpExampleCli("getlabeladdress", "\"mylabel\"") +
HelpExampleRpc("getlabeladdress", "\"mylabel\""));
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
// Parse the label first so we don't generate a key if there's an error
std::string label = LabelFromValue(request.params[0]);
UniValue ret(UniValue::VSTR);
ret = GetLabelDestination(pwallet, label);
return ret;
}
static UniValue getrawchangeaddress(const Config &config,
const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 0) {
throw std::runtime_error(
"getrawchangeaddress\n"
"\nReturns a new Devault address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n"
"\nResult:\n"
"\"address\" (string) The address\n"
"\nExamples:\n" +
HelpExampleCli("getrawchangeaddress", "") +
HelpExampleRpc("getrawchangeaddress", ""));
}
if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
throw JSONRPCError(RPC_WALLET_ERROR,
"Error: Private keys are disabled for this wallet");
}
LOCK2(cs_main, pwallet->cs_wallet);
if (!pwallet->IsLocked()) {
pwallet->TopUpKeyPool();
}
CReserveKey reservekey(pwallet);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey, true)) {
throw JSONRPCError(
RPC_WALLET_KEYPOOL_RAN_OUT,
"Error: Keypool ran out, please call keypoolrefill first");
}
reservekey.KeepKey();
CKeyID keyID = vchPubKey.GetKeyID();
return EncodeDestination(keyID);
}
UniValue setlabel(const Config &config, const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 ||
request.params.size() > 2) {
throw std::runtime_error(
"setlabel \"address\" \"label\"\n"
"\nSets the label associated with the given address.\n"
"\nArguments:\n"
"1. \"address\" (string, required) The devault address to "
"be associated with a label.\n"
"2. \"label\" (string, required) The label to assign the "
"address to.\n"
"\nExamples:\n" +
HelpExampleCli("setlabel",
R"("devault:qpzfppqqg5sk6ck8c624tk7vgxeuafaq9uumff5u2u" "tabby")") +
HelpExampleRpc(
"setlabel",
R"("devault:qpzfppqqg5sk6ck8c624tk7vgxeuafaq9uumff5u2u", "tabby")"));
}
LOCK2(cs_main, pwallet->cs_wallet);
CTxDestination dest =
DecodeDestination(request.params[0].get_str(), config.GetChainParams());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,
"Invalid Devault address");
}
std::string label;
if (!request.params[1].isNull()) {
label = LabelFromValue(request.params[1]);
}
if (IsMine(*pwallet, dest)) {
// Only add the label to Address Book if the address is yours.
pwallet->SetAddressBook(dest, label, "receive");
} else {
pwallet->SetLabel(dest, label, "external");
}
return NullUniValue;
}
static UniValue getaddressesbylabels(const Config &config,
const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 0) {
throw std::runtime_error(
"getaddressesbylabels \n"
"\nReturns the list of addresses in your wallet that have labels\n "
"\nResult:\n"
"[ (json array of string)\n"
" \"label\" (string) label associated with the below address\n"
" \"address\" (string) devault address\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getaddressesbylabels","") +
HelpExampleRpc("getaddressesbylabels",""));
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
// Go through AddressBook and list labels with their addresses
std::map<std::string, std::string> setLabels;
// For Labels that are in the Wallet (and previously set in older software)
// NOTE: In future, wallet upgrade should consolidate the older method and rewrite in new format
for (const auto &item : pwallet->mapAddressBook) {
UniValue obj(UniValue::VOBJ);
const CTxDestination &dest = item.first;
const std::string &strName = item.second.name;
setLabels.insert(std::make_pair(strName, EncodeDestination(dest)));
}
// Now use other method
// For Labels that are not in the Wallet (and newly set after version 1.1)
std::map<std::string, std::string> mapLabels;
if (pwallet->FindLabelledAddresses(mapLabels) != DBErrors::LOAD_OK) {
throw JSONRPCError(RPC_WALLET_ERROR,
"Wallet DB error.");
}
// Combine maps
for (const auto &item : mapLabels) setLabels.insert(std::make_pair(item.first, item.second));
UniValue obj(UniValue::VOBJ);
for (const auto &item : setLabels) obj.pushKV(item.first,item.second);
return obj;
}
static CTransactionRef SendMoney(interfaces::Chain::Lock &locked_chain,
CWallet *const pwallet,
const CTxDestination &address, Amount nValue,
bool fSubtractFeeFromAmount,
mapValue_t mapValue, std::string fromAccount) {
Amount curBalance = pwallet->GetBalance();
// Check amount
if (nValue <= Amount::zero()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
}
if (nValue > curBalance) {
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
}
if (pwallet->GetBroadcastTransactions() && !g_connman) {
throw JSONRPCError(
RPC_CLIENT_P2P_DISABLED,
"Error: Peer-to-peer functionality missing or disabled");
}
// Parse Bitcoin address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwallet);
Amount nFeeRequired;
std::string strError;
std::vector<CRecipient> vecSend;
int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
CCoinControl coinControl;
CTransactionRef tx;
if (!pwallet->CreateTransaction(locked_chain, vecSend, tx, reservekey,
nFeeRequired, nChangePosRet, strError,
coinControl)) {
if (!fSubtractFeeFromAmount && nValue + nFeeRequired > curBalance) {
strError = strprintf("Error: This transaction requires a "
"transaction fee of at least %s",
FormatMoney(nFeeRequired));
}
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
CValidationState state;
if (!pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */,
std::move(fromAccount), reservekey,
g_connman.get(), state)) {
strError =
strprintf("Error: The transaction was rejected! Reason given: %s",
state.GetRejectReason());
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
return tx;
}
static UniValue sendtoaddress(const Config &config,
const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 2 ||
request.params.size() > 5) {
throw std::runtime_error(
"sendtoaddress \"address\" amount ( \"comment\" \"comment_to\" "
"subtractfeefromamount )\n"
"\nSend an amount to a given address.\n" +
HelpRequiringPassphrase(pwallet) +
"\nArguments:\n"
"1. \"address\" (string, required) The devault address "
"to send to.\n"
"2. \"amount\" (numeric or string, required) The "
"amount in " +
CURRENCY_UNIT +
" to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to "
"store what the transaction is for. \n"
" This is not part of the transaction, "
"just kept in your wallet.\n"
"4. \"comment_to\" (string, optional) A comment to store "
"the name of the person or organization \n"
" to which you're sending the "
"transaction. This is not part of the \n"
" transaction, just kept in your "
"wallet.\n"
"5. subtractfeefromamount (boolean, optional, default=false) The "
"fee will be deducted from the amount being sent.\n"
" The recipient will receive less "
"devaults than you enter in the amount field.\n"
"\nResult:\n"
"\"txid\" (string) The transaction id.\n"
"\nExamples:\n" +
HelpExampleCli("sendtoaddress",
"\"devault:qp4au0wyh9zj2jchy96glxj9fsng8ru87ugcfylpc9\" 0.1") +
HelpExampleCli("sendtoaddress", "\"devault:qp4au0wyh9zj2jchy96glxj9fsng8ru87ugcfylpc9"
"dd\" 0.1 \"donation\" \"seans "
"outpost\"") +
HelpExampleCli(
"sendtoaddress",
R"("devault:qp4au0wyh9zj2jchy96glxj9fsng8ru87ugcfylpc9" 0.1 "" "" true)") +
HelpExampleRpc("sendtoaddress", "\"devault:qp4au0wyh9zj2jchy96glxj9fsng8ru87ugcfylpc9"
"dd\", 0.1, \"donation\", \"seans "
"outpost\""));
}
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
CTxDestination dest =
DecodeDestination(request.params[0].get_str(), config.GetChainParams());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
// Amount
Amount nAmount = AmountFromValue(request.params[1]);
if (nAmount <= Amount::zero()) {
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
}
// Wallet comments
mapValue_t mapValue;
if (request.params.size() > 2 && !request.params[2].isNull() &&
!request.params[2].get_str().empty()) {
mapValue["comment"] = request.params[2].get_str();
}
if (request.params.size() > 3 && !request.params[3].isNull() &&
!request.params[3].get_str().empty()) {
mapValue["to"] = request.params[3].get_str();
}
bool fSubtractFeeFromAmount = false;
if (request.params.size() > 4) {
fSubtractFeeFromAmount = request.params[4].get_bool();
}
EnsureWalletIsUnlocked(pwallet);
CTransactionRef tx =
SendMoney(*locked_chain, pwallet, dest, nAmount, fSubtractFeeFromAmount,
std::move(mapValue), {} /* fromAccount */);
return tx->GetId().GetHex();
}
UniValue sweeplegacyprivkey(const Config &config, const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"sweeplegacyprivkey \"privkey\"\n"
"\nSend funds from entered legacy (i.e devault: associated) private key to a key in your wallet (HD chain). "
"\nArguments:\n"
"1. \"DeVaultprivkey\" (string, required) The private key (see "
"dumpprivkey)\n"
"\nExamples:\n"
"\nSweep a private key\n" +
HelpExampleCli("sweeplegacyprivkey", "\"myaddress\"") +
"\nSweep a legacy private key\n" +
HelpExampleRpc("sweeplegacyprivkey", R"("mykey")"));
{
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
std::string strSecret = request.params[0].get_str();
CKey key = DecodeSecret(strSecret);
//std::string p = EncodeDestination(key.GetPubKey().GetKeyID());
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
}
FlushStateToDisk();
std::string strFailReason;
CTransactionRef tx;
bool ok = pwallet->SweepCoinsToWallet(key, tx, false, strFailReason);
if (!ok) {
throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
}
return tx->GetId().GetHex();
}
}
UniValue sweepblsprivkey(const Config &config, const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"sweepblsprivkey \"privkey\"\n"
"\nSend funds from entered private key (associated with dvt: address) to a key in your wallet (HD chain). "
"\nArguments:\n"
"1. \"DeVaultprivkey\" (string, required) The private key (see "
"dumpprivkey)\n"
"\nExamples:\n"
"\nSweep a private key\n" +
HelpExampleCli("sweepblsprivkey", "\"myaddress\"") +
"\nSweep the private key\n" +
HelpExampleRpc("sweepblsprivkey", R"("mykey")"));
{
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
std::string strSecret = request.params[0].get_str();
CKey key = DecodeSecret(strSecret);
//std::string p = EncodeDestination(key.GetPubKey().GetKeyID());
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
}
FlushStateToDisk();
std::string strFailReason;
CTransactionRef tx;
bool ok = pwallet->SweepCoinsToWallet(key, tx, true, strFailReason);
if (!ok) {
throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
}
return tx->GetId().GetHex();
}
}
static UniValue consolidaterewards(const Config &config,
const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) {
throw std::runtime_error(
"consolidaterewards \"address\" )\n" +
HelpRequiringPassphrase(pwallet) +
"\nArguments:\n"
"1. \"address\" (string, required) The DeVault address to send to.\n"
"2. \"days\" (int, optional, default=3, min=1,max=30). The number of days back to use coins from (this is based on assuming 720 blocks per day, adjust accordingly)\n"
"3. \"minimum amount\" (int, optional, default=nMinRewardBalance). The transaction will be skipped unless at least this amount and also greater than nMinRewardBalance\n"
"\nResult:\n"
"\"txid\" (string) The transaction id.\n"
"\nExamples:\n" +
HelpExampleCli("consolidaterewards", "\"devault:qp4au0wyh9zj2jchy96glxj9fsng8ru87ugcfylpc9\" 3, 10000)") +
HelpExampleRpc("consolidaterewards", "\"devault:qp4au0wyh9zj2jchy96glxj9fsng8ru87ugcfylpc9\" 3, 10000)"));
}
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
CTxDestination dest = DecodeDestination(request.params[0].get_str(), config.GetChainParams());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
int days = 3;
if (!request.params[1].isNull()) {
days = request.params[1].get_int();
days = std::min(std::max(1,days), 30); // Keep between 1 days and 30
}
double minPercent = 100.0*days/30.0;
std::string message;
int Height = chainActive.Height();
Amount minRewardBalance = Params().GetConsensus().getMinRewardBalance(Height);
Amount minAmount = minRewardBalance;
if (!request.params[2].isNull()) {
Amount coinMin(0);
coinMin = Amount(request.params[2].get_int() * COIN);
if (coinMin < minRewardBalance) coinMin = minRewardBalance;
minAmount = coinMin;
}
if (!pwallet->ConsolidateRewards(dest, minPercent, minAmount, message)) {
std::string strError = strprintf("Error: ConsolidateRewards failed! Reason given: %s", message);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
// message is tx hash if successful
return message;
}
static UniValue listaddressgroupings(const Config &config,
const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 0) {
throw std::runtime_error(
"listaddressgroupings\n"
"\nLists groups of addresses which have had their common "
"ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions\n"
"\nResult:\n"
"[\n"
" [\n"
" [\n"
" \"address\", (string) The devault address\n"
" amount, (numeric) The amount in " +
CURRENCY_UNIT +
"\n"
" \"label\" (string, optional) The label\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listaddressgroupings", "") +
HelpExampleRpc("listaddressgroupings", ""));
}
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
UniValue jsonGroupings(UniValue::VARR);
std::map<CTxDestination, Amount> balances =
pwallet->GetAddressBalances(*locked_chain);
for (const std::set<CTxDestination> &grouping :
pwallet->GetAddressGroupings()) {
UniValue jsonGrouping(UniValue::VARR);
for (const CTxDestination &address : grouping) {
UniValue addressInfo(UniValue::VARR);
addressInfo.push_back(EncodeDestination(address));
addressInfo.push_back(ValueFromAmount(balances[address]));
if (pwallet->mapAddressBook.find(address) !=
pwallet->mapAddressBook.end()) {
addressInfo.push_back(
pwallet->mapAddressBook.find(address)->second.name);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
static UniValue signmessage(const Config &config,
const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 2) {
throw std::runtime_error(
"signmessage \"address\" \"message\"\n"
"\nSign a message with the private key of an address" +
HelpRequiringPassphrase(pwallet) +
"\n"
"\nArguments:\n"
"1. \"address\" (string, required) The devault address to "
"use for the private key.\n"
"2. \"message\" (string, required) The message to create a "
"signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message "
"encoded in base 64\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n" +
HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n" +
HelpExampleCli(
"signmessage",
R"("devault:qpzfppqqg5sk6ck8c624tk7vgxeuafaq9uumff5u2u" "my message")") +
"\nVerify the signature\n" +
HelpExampleCli("signmessage", "\"devault:qplxfq6jfqappmgemvgqup64mg592rh2ssyv8zcze7"
"XX\" \"signature\" \"my "
"message\"") +
"\nAs json rpc\n" +
HelpExampleRpc(
"signmessage",
R"("devault:qpzfppqqg5sk6ck8c624tk7vgxeuafaq9uumff5u2u", "my message")"));
}
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
std::string strAddress = request.params[0].get_str();
std::string strMessage = request.params[1].get_str();
CTxDestination dest = DecodeDestination(strAddress, config.GetChainParams());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
}
std::vector<uint8_t> vchSig;
CKey key;
CKeyID keyID;
BKeyID keyID1;
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
if (std::holds_alternative<CKeyID>(dest)) {
keyID = std::get<CKeyID>(dest);
if (!pwallet->GetKey(keyID, key)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
}
if (!key.SignCompact(ss.GetHash(), vchSig)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
}
} else if (std::holds_alternative<BKeyID>(dest)) {
keyID1 = std::get<BKeyID>(dest);
if (!pwallet->GetKey(keyID1, key)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
}
if (!key.SignBLS(ss.GetHash(), vchSig)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
}
// Now append Public Key to Signature
auto app = ToByteVector(key.GetPubKeyForBLS());
std::copy (app.begin(), app.end(), std::back_inserter(vchSig));
} else {
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
}
return EncodeBase64(&vchSig[0], vchSig.size());
}
static UniValue getreceivedbyaddress(const Config &config,
const JSONRPCRequest &request) {
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
CWallet *const pwallet = wallet.get();
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 ||
request.params.size() > 2) {
throw std::runtime_error(
"getreceivedbyaddress \"address\" ( minconf )\n"
"\nReturns the total amount received by the given address in "
"transactions with at least minconf confirmations.\n"
"\nArguments:\n"
"1. \"address\" (string, required) The devault address for "
"transactions.\n"
"2. minconf (numeric, optional, default=1) Only "
"include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in " +
CURRENCY_UNIT +
" received at this address.\n"
"\nExamples:\n"
"\nThe amount from transactions with at least 1 confirmation\n" +
HelpExampleCli("getreceivedbyaddress",
"\"devault:qpzfppqqg5sk6ck8c624tk7vgxeuafaq9uumff5u2u\"") +
"\nThe amount including unconfirmed transactions, zero "
"confirmations\n" +
HelpExampleCli("getreceivedbyaddress",
"\"devault:qpzfppqqg5sk6ck8c624tk7vgxeuafaq9uumff5u2u\" 0") +
"\nThe amount with at least 6 confirmations\n" +
HelpExampleCli("getreceivedbyaddress",
"\"devault:qpzfppqqg5sk6ck8c624tk7vgxeuafaq9uumff5u2u\" 6") +
"\nAs a json rpc call\n" +
HelpExampleRpc("getreceivedbyaddress",
"\"devault:qpzfppqqg5sk6ck8c624tk7vgxeuafaq9uumff5u2u\", 6"));
}
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
pwallet->BlockUntilSyncedToCurrentChain();
// Temporary, for ContextualCheckTransactionForCurrentBlock below. Removed
// in upcoming commit.
LockAnnotation lock(::cs_main);
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
// Bitcoin address
CTxDestination dest =
DecodeDestination(request.params[0].get_str(), config.GetChainParams());