forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 717
/
rpcwallet.cpp
4811 lines (3961 loc) · 221 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-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet/rpcwallet.h"
#include "addressbook.h"
#include "amount.h"
#include "coincontrol.h"
#include "core_io.h"
#include "destination_io.h"
#include "httpserver.h"
#include "key_io.h"
#include "key_io.h"
#include "masternode-sync.h"
#include "net.h"
#include "policy/feerate.h"
#include "rpc/server.h"
#include "sapling/sapling_operation.h"
#include "sapling/transaction_builder.h"
#include "sapling/key_io_sapling.h"
#include "spork.h"
#include "timedata.h"
#include "utilmoneystr.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#include "wallet/walletutil.h"
#include "zpivchain.h"
#include <init.h> // for StartShutdown
#include <stdint.h>
#include <univalue.h>
static const std::string WALLET_ENDPOINT_BASE = "/wallet/";
CWallet* GetWalletForJSONRPCRequest(const JSONRPCRequest& request)
{
if (request.URI.substr(0, WALLET_ENDPOINT_BASE.size()) == WALLET_ENDPOINT_BASE) {
// wallet endpoint was used
std::string requestedWallet = urlDecode(request.URI.substr(WALLET_ENDPOINT_BASE.size()));
for (CWalletRef pwallet : ::vpwallets) {
if (pwallet->GetName() == requestedWallet) {
return pwallet;
}
}
throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded");
}
return ::vpwallets.size() == 1 || (request.fHelp && ::vpwallets.size() > 0) ? ::vpwallets[0] : nullptr;
}
std::string HelpRequiringPassphrase(CWallet* const pwallet)
{
return pwallet && pwallet->IsCrypted() ? "\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 (::vpwallets.empty()) {
// Wallet RPC methods are disabled if no wallets are loaded.
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
}
throw JSONRPCError(RPC_WALLET_NOT_SPECIFIED,
"Wallet file not specified (must request wallet RPC through /wallet/<filename> uri-path).");
}
void EnsureWalletIsUnlocked(CWallet* const pwallet, bool fAllowAnonOnly)
{
if (pwallet->IsLocked() || (!fAllowAnonOnly && pwallet->fWalletUnlockStaking))
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.pushKV("confirmations", confirms);
entry.pushKV("bcconfirmations", confirms); // DEPRECATED in 4.3.99
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.pushKV("generated", true);
if (confirms > 0) {
entry.pushKV("blockhash", wtx.m_confirm.hashBlock.GetHex());
entry.pushKV("blockindex", wtx.m_confirm.nIndex);
entry.pushKV("blocktime", mapBlockIndex[wtx.m_confirm.hashBlock]->GetBlockTime());
} else {
entry.pushKV("trusted", wtx.IsTrusted());
}
uint256 hash = wtx.GetHash();
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 std::pair<std::string, std::string> & 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;
}
static CTxDestination GetNewAddressFromLabel(CWallet* const pwallet, const std::string purpose, const UniValue ¶ms,
const CChainParams::Base58Type addrType = CChainParams::PUBKEY_ADDRESS)
{
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 (!params.isNull() && params.size() > 0)
label = LabelFromValue(params[0]);
CTxDestination address;
PairResult r = pwallet->getNewAddress(address, label, purpose, addrType);
if(!r.result)
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, *r.status);
return address;
}
/** Convert CAddressBookData to JSON record. */
static UniValue AddressBookDataToJSON(const AddressBook::CAddressBookData& data, const bool verbose)
{
UniValue ret(UniValue::VOBJ);
if (verbose) {
ret.pushKV("name", data.name);
}
ret.pushKV("purpose", data.purpose);
return ret;
}
/** Checks if a CKey is in the given CWallet compressed or otherwise*/
bool HaveKey(const CWallet* wallet, const CKey& key)
{
CKey key2;
key2.Set(key.begin(), key.end(), !key.IsCompressed());
return wallet->HaveKey(key.GetPubKey().GetID()) || wallet->HaveKey(key2.GetPubKey().GetID());
}
UniValue getaddressinfo(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
const std::string example_address = "\"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\"";
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"getaddressinfo ( \"address\" )\n"
"\nReturn information about the given PIVX address.\n"
"Some of the information will only be present if the address is in the active wallet.\n"
"Metadata for shield addresses is available only if the wallet is unlocked.\n"
"{Result:\n"
" \"address\" : \"address\", (string) The PIVX address validated.\n"
" \"isshield\" : true|false, (boolean) If the address is shield or transparent.\n"
" \"scriptPubKey\" : \"hex\", (string, only if isshield=false) The hex-encoded scriptPubKey generated by the address.\n"
" \"ischange\" : true|false, (boolean) If the transparent address was used for change output.\n"
" \"ismine\" : true|false, (boolean) If the address is yours.\n"
" \"iswatchonly\" : true|false, (boolean) If the address is watchonly.\n"
" \"label\" : \"label\" (string) The label associated with the address, \"\" is the default label.\n"
" \"timestamp\" : timestamp, (number, optional) The creation time of the key, if available, expressed in the UNIX epoch time.\n"
" \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath, if the key is HD and available.\n"
" \"hdseedid\" : \"<hash160>\" (string, optional) The Hash160 of the HD seed.\n"
" \"hdmasterfingerprint\" : \"<hash160>\" (string, optional) The fingerprint of the master key.\n"
" \"labels\" (json object) An array of labels associated with the address. Currently limited to one label but returned\n"
" as an array to keep the API stable if multiple labels are enabled in the future.\n"
" [\n"
" { (json object of label data)\n"
" \"name\" : \"labelname\" (string) The label.\n"
" \"purpose\" : \"purpose\" (string) The purpose of the associated address (send or receive).\n"
" }\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getaddressinfo", example_address) + HelpExampleRpc("getaddressinfo", example_address)
);
LOCK(pwallet->cs_wallet);
const std::string& strAdd = request.params[0].get_str();
UniValue ret(UniValue::VOBJ);
ret.pushKV("address", strAdd);
const CWDestination& dest = Standard::DecodeDestination(strAdd);
// Make sure the destination is valid
if (!Standard::IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
const CTxDestination* pTransDest = Standard::GetTransparentDestination(dest);
ret.pushKV("isshield", pTransDest == nullptr);
if (pTransDest) {
CScript scriptPubKey = GetScriptForDestination(*pTransDest);
ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
ret.pushKV("ischange", pwallet->IsChange(scriptPubKey));
}
isminetype mine = IsMine(*pwallet, dest);
ret.pushKV("ismine", bool(mine & ISMINE_SPENDABLE_ALL));
ret.pushKV("iswatchonly", bool(mine & ISMINE_WATCH_ONLY_ALL));
// Return label field if existing. Currently only one label can be
// associated with an address, so the label should be equivalent to the
// value of the name key/value pair in the labels array below.
if (pwallet->HasAddressBook(dest)) {
ret.pushKV("label", pwallet->GetNameForAddressBookEntry(dest));
}
ScriptPubKeyMan* spk_man = pwallet->GetScriptPubKeyMan();
SaplingScriptPubKeyMan* sspk_man = pwallet->GetSaplingScriptPubKeyMan();
CKeyMetadata* meta = nullptr;
if (spk_man && pTransDest) {
// transparent destination
const CKeyID* keyID = boost::get<CKeyID>(pTransDest);
if (keyID) {
auto it = pwallet->mapKeyMetadata.find(*keyID);
if(it != pwallet->mapKeyMetadata.end()) {
meta = &it->second;
}
}
} else if (sspk_man && !pTransDest) {
// shield destination
const libzcash::SaplingPaymentAddress pa = *Standard::GetShieldedDestination(dest);
libzcash::SaplingExtendedSpendingKey extsk;
if (pwallet->GetSaplingExtendedSpendingKey(pa, extsk)) {
const auto& ivk = extsk.expsk.full_viewing_key().in_viewing_key();
auto it = sspk_man->mapSaplingZKeyMetadata.find(ivk);
if (it != sspk_man->mapSaplingZKeyMetadata.end()) {
meta = &it->second;
}
}
}
// Add metadata
if (meta) {
ret.pushKV("timestamp", meta->nCreateTime);
if (meta->HasKeyOrigin()) {
ret.pushKV("hdkeypath", meta->key_origin.pathToString());
ret.pushKV("hdseedid", meta->hd_seed_id.GetHex());
ret.pushKV("hdmasterfingerprint", HexStr(meta->key_origin.fingerprint, meta->key_origin.fingerprint + 4));
}
}
// Return a `labels` array containing the label associated with the address,
// equivalent to the `label` field above. Currently only one label can be
// associated with an address, but we return an array so the API remains
// stable if we allow multiple labels to be associated with an address in
// the future.
//
// DEPRECATED: The previous behavior of returning an array containing a JSON
// object of `name` and `purpose` key/value pairs has been deprecated.
UniValue labels(UniValue::VARR);
auto addrBookData = pwallet->GetAddressBookEntry(dest);
if (addrBookData) {
labels.push_back(AddressBookDataToJSON(*addrBookData, true));
}
ret.pushKV("labels", std::move(labels));
return ret;
}
UniValue getaddressesbylabel(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"getaddressesbylabel \"label\"\n"
"\nReturns the list of addresses assigned the specified label.\n"
"\nArguments:\n"
"1. \"label\" (string, required) The label.\n"
"\nResult:\n"
"{ (json object with addresses as keys)\n"
" \"address\": { (json object with information about address)\n"
" \"purpose\": \"string\" (string) Purpose of address (\"send\" for sending address, \"receive\" for receiving address)\n"
" },...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressesbylabel", "\"tabby\"")
+ HelpExampleRpc("getaddressesbylabel", "\"tabby\"")
);
LOCK(pwallet->cs_wallet);
std::string label = LabelFromValue(request.params[0]);
// Find all addresses that have the given label
UniValue ret(UniValue::VOBJ);
for (auto it = pwallet->NewAddressBookIterator(); it.IsValid(); it.Next()) {
auto addrBook = it.GetValue();
if (!addrBook.isShielded() && addrBook.name == label) {
ret.pushKV(EncodeDestination(*it.GetCTxDestKey(), AddressBook::IsColdStakingPurpose(addrBook.purpose)), AddressBookDataToJSON(addrBook, false));
}
}
if (ret.empty()) {
throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, std::string("No addresses with label " + label));
}
return ret;
}
UniValue listlabels(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"listlabels ( \"purpose\" )\n"
"\nReturns the list of all labels, or labels that are assigned to addresses with a specific purpose.\n"
"\nArguments:\n"
"1. \"purpose\" (string, optional) Address purpose to list labels for ('send','receive', 'delegable', 'delegator', 'coldstaking', 'coldstaking_send', 'refund'). An empty string is the same as not providing this argument.\n"
"\nResult:\n"
"[ (json array of string)\n"
" \"label\", (string) Label name\n"
" ...\n"
"]\n"
"\nExamples:\n"
"\nList all labels\n"
+ HelpExampleCli("listlabels", "") +
"\nList labels that have receiving addresses\n"
+ HelpExampleCli("listlabels", "receive") +
"\nList labels that have sending addresses\n"
+ HelpExampleCli("listlabels", "send") +
"\nAs json rpc call\n"
+ HelpExampleRpc("listlabels", "receive")
);
LOCK(pwallet->cs_wallet);
std::string purpose;
if (!request.params[0].isNull()) {
purpose = request.params[0].get_str();
}
// Add to a set to sort by label name, then insert into Univalue array
std::set<std::string> label_set;
for (auto it = pwallet->NewAddressBookIterator(); it.IsValid(); it.Next()) {
auto addrBook = it.GetValue();
if (purpose.empty() || addrBook.purpose == purpose) {
label_set.insert(addrBook.name);
}
}
UniValue ret(UniValue::VARR);
for (const std::string& name : label_set) {
ret.push_back(name);
}
return ret;
}
CPubKey parseWIFKey(std::string strKey, CWallet* pwallet)
{
CKey key = KeyIO::DecodeSecret(strKey);
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
}
if (HaveKey(pwallet, key)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key (either as an HD seed or as a loose private key)");
}
return pwallet->GetScriptPubKeyMan()->DeriveNewSeed(key);
}
UniValue upgradewallet(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error("upgradewallet\n"
"Bump the wallet features to the latest supported version. Non-HD wallets will be upgraded to HD wallet functionality. "
"Marking all the previous keys as pre-split keys and managing them separately. Once the last key in the pre-split keypool gets marked as used (received balance), the wallet will automatically start using the HD generated keys.\n"
"The upgraded HD wallet will have a new HD seed set so that new keys added to the keypool will be derived from this new seed.\n"
"Wallets that are already runnning the latest HD version will be upgraded to Sapling support\n"
"Enabling the Sapling key manager. Sapling keys will be deterministically derived by the same HD wallet seed.\n"
"Wallets that are running the latest Sapling version will not be upgraded"
"\nNote that you will need to MAKE A NEW BACKUP of your wallet after upgrade it.\n"
+ HelpRequiringPassphrase(pwallet) + "\n"
+ HelpExampleCli("upgradewallet", "") + HelpExampleRpc("upgradewallet", "")
);
LOCK2(cs_main, pwallet->cs_wallet);
// Do not do anything to wallets already upgraded
if (pwallet->CanSupportFeature(FEATURE_LATEST)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Cannot upgrade the wallet. The wallet is already running the latest version");
}
EnsureWalletIsUnlocked(pwallet);
// Get version
int prev_version = pwallet->GetVersion();
// Upgrade wallet's version
pwallet->SetMinVersion(FEATURE_LATEST);
pwallet->SetMaxVersion(FEATURE_LATEST);
// Upgrade to HD
std::string upgradeError;
if (!pwallet->Upgrade(upgradeError, prev_version)) {
upgradeError = strprintf("Error: Cannot upgrade wallet, %s", upgradeError);
throw JSONRPCError(RPC_WALLET_ERROR, upgradeError);
}
return NullUniValue;
}
UniValue sethdseed(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error("sethdseed ( newkeypool \"seed\" )\n"
"Set or generate a new HD wallet seed. Non-HD wallets will not be upgraded to being a HD wallet. Wallets that are already\n"
"HD will have a new HD seed set so that new keys added to the keypool will be derived from this new seed.\n"
"\nNote that you will need to MAKE A NEW BACKUP of your wallet after setting the HD wallet seed.\n"
+ HelpRequiringPassphrase(pwallet) + "\n"
"\nArguments:\n"
"1. newkeypool (boolean, optional, default true): Whether to flush old unused addresses, including change addresses, from the keypool and regenerate it.\n"
" If true, the next address from getnewaddress and change address from getrawchangeaddress will be from this new seed.\n"
" If false, addresses (including change addresses if the wallet already had HD Chain Split enabled) from the existing\n"
" keypool will be used until it has been depleted."
"2. \"seed\" (string, optional, default random seed): The WIF private key to use as the new HD seed.\n"
" The seed value can be retrieved using the dumpwallet command. It is the private key marked hdseed=1"
+ HelpExampleCli("sethdseed", "")
+ HelpExampleCli("sethdseed", "false")
+ HelpExampleCli("sethdseed", "true \"wifkey\"")
+ HelpExampleRpc("sethdseed", "true, \"wifkey\"")
);
if (IsInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Cannot set a new HD seed while still in Initial Block Download");
}
// 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);
// Do not do anything to non-HD wallets
if (!pwallet->CanSupportFeature(FEATURE_PRE_SPLIT_KEYPOOL)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Cannot set a HD seed on a non-HD wallet. Start with -upgradewallet in order to upgrade a non-HD wallet to HD");
}
EnsureWalletIsUnlocked(pwallet);
bool flush_key_pool = true;
if (!request.params[0].isNull()) {
flush_key_pool = request.params[0].get_bool();
}
ScriptPubKeyMan* spk_man = pwallet->GetScriptPubKeyMan();
CPubKey master_pub_key = request.params[1].isNull() ?
spk_man->GenerateNewSeed() : parseWIFKey(request.params[1].get_str(), pwallet);
spk_man->SetHDSeed(master_pub_key, true);
if (flush_key_pool) spk_man->NewKeyPool();
// Update Sapling chain
SaplingScriptPubKeyMan* sspk_man = pwallet->CanSupportFeature(FEATURE_SAPLING) ?
pwallet->GetSaplingScriptPubKeyMan() : nullptr;
if (sspk_man) {
sspk_man->SetHDSeed(master_pub_key, true);
}
return NullUniValue;
}
UniValue getnewaddress(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"getnewaddress ( \"label\" )\n"
"\nReturns a new PIVX 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"
"\"pivxaddress\" (string) The new pivx address\n"
"\nExamples:\n" +
HelpExampleCli("getnewaddress", "") + HelpExampleRpc("getnewaddress", ""));
return EncodeDestination(GetNewAddressFromLabel(pwallet, AddressBook::AddressBookPurpose::RECEIVE, request.params));
}
UniValue getnewstakingaddress(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"getnewstakingaddress ( \"label\" )\n"
"\nReturns a new PIVX cold staking address for receiving delegated cold stakes.\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"
"\"pivxaddress\" (string) The new pivx address\n"
"\nExamples:\n" +
HelpExampleCli("getnewstakingaddress", "") + HelpExampleRpc("getnewstakingaddress", ""));
return EncodeDestination(GetNewAddressFromLabel(pwallet, "coldstaking", request.params, CChainParams::STAKING_ADDRESS), CChainParams::STAKING_ADDRESS);
}
UniValue getnewshieldaddress(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || !request.params.empty())
throw std::runtime_error(
"getnewshieldaddress\n"
"\nReturns a new shield address for receiving payments.\n"
+ HelpRequiringPassphrase(pwallet) + "\n"
"\nResult:\n"
"\"address\" (string) The new shield address.\n"
"\nExamples:\n"
+ HelpExampleCli("getnewshieldaddress", "")
+ HelpExampleRpc("getnewshieldaddress", "")
);
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
return KeyIO::EncodePaymentAddress(pwallet->GenerateNewSaplingZKey());
}
UniValue listshieldunspent(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() > 4)
throw std::runtime_error(
"listshieldunspent ( minconf maxconf include_watchonly [\"shield_addr\",...] )\n"
"\nReturns array of unspent shield notes with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include notes sent to specified addresses.\n"
"When minconf is 0, unspent notes with zero confirmations are returned, even though they are not immediately spendable.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. include_watchonly (bool, optional, default=false) Also include watchonly addresses (see 'importsaplingviewingkey')\n"
"4. \"addresses\" (string) A json array of shield addrs to filter on. Duplicate addresses not allowed.\n"
" [\n"
" \"address\" (string) shield addr\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"outindex\" (sapling) : n, (numeric) the output index\n"
" \"confirmations\" : n, (numeric) the number of confirmations\n"
" \"spendable\" : true|false, (boolean) true if note can be spent by wallet, false if address is watchonly\n"
" \"address\" : \"address\", (string) the shield address\n"
" \"amount\": xxxxx, (numeric) the amount of value in the note\n"
" \"memo\": xxxxx, (string) hexademical string representation of memo field\n"
" \"change\": true|false, (boolean) true if the address that received the note is also one of the sending addresses\n"
" \"nullifier\": xxxxx, (string) the note's nullifier, hex encoded"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n"
+ HelpExampleCli("listshieldunspent", "")
+ HelpExampleCli("listshieldunspent", "6 9999999 false \"[\\\"ptestsapling1h0w73csah2aq0a32h42kr7tq4htlt5wfn4ejxfnm56f6ehjvek7k4e244g6v8v3pgylmz5ea8jh\\\",\\\"ptestsapling1h0w73csah2aq0a32h42kr7tq4htlt5wfn4ejxfnm56f6ehjvek7k4e244g6v8v3pgylmz5ea8jh\\\"]\"")
+ HelpExampleRpc("listshieldunspent", "6 9999999 false \"[\\\"ptestsapling1h0w73csah2aq0a32h42kr7tq4htlt5wfn4ejxfnm56f6ehjvek7k4e244g6v8v3pgylmz5ea8jh\\\",\\\"ptestsapling1h0w73csah2aq0a32h42kr7tq4htlt5wfn4ejxfnm56f6ehjvek7k4e244g6v8v3pgylmz5ea8jh\\\"]\"")
);
RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM, UniValue::VBOOL, UniValue::VARR});
int nMinDepth = request.params.size() > 0 ? request.params[0].get_int() : 1;
if (nMinDepth < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Minimum number of confirmations cannot be less than 0");
}
int nMaxDepth = request.params.size() > 1 ? request.params[1].get_int() : 9999999;
if (nMaxDepth < nMinDepth) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Maximum number of confirmations must be greater or equal to the minimum number of confirmations");
}
std::set<libzcash::PaymentAddress> shieldAddrs = {};
bool fIncludeWatchonly = request.params.size() > 2 && request.params[2].get_bool();
LOCK2(cs_main, pwallet->cs_wallet);
// User has supplied shield addrs to filter on
if (request.params.size() > 3) {
UniValue addresses = request.params[3].get_array();
if (addresses.size()==0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, addresses array is empty.");
// Keep track of addresses to spot duplicates
std::set<std::string> setAddress;
// Sources
for (const UniValue& o : addresses.getValues()) {
if (!o.isStr()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected string");
}
std::string address = o.get_str();
auto shieldAddr = KeyIO::DecodePaymentAddress(address);
if (!IsValidPaymentAddress(shieldAddr)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, address is not a valid shield address: ") + address);
}
libzcash::SaplingPaymentAddress paymentAddress = *boost::get<libzcash::SaplingPaymentAddress>(&shieldAddr);
bool hasSpendingKey = pwallet->HaveSpendingKeyForPaymentAddress(paymentAddress);
if (!fIncludeWatchonly && !hasSpendingKey) {
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, spending key for address does not belong to wallet: ") + address);
}
shieldAddrs.insert(shieldAddr);
if (setAddress.count(address)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + address);
}
setAddress.insert(address);
}
} else {
// User did not provide shield addrs, so use default i.e. all addresses
std::set<libzcash::SaplingPaymentAddress> saplingzaddrs = {};
pwallet->GetSaplingPaymentAddresses(saplingzaddrs);
shieldAddrs.insert(saplingzaddrs.begin(), saplingzaddrs.end());
}
UniValue results(UniValue::VARR);
if (shieldAddrs.size() > 0) {
std::vector<SaplingNoteEntry> saplingEntries;
pwallet->GetSaplingScriptPubKeyMan()->GetFilteredNotes(saplingEntries, shieldAddrs, nMinDepth, nMaxDepth, true, !fIncludeWatchonly, false);
std::set<std::pair<libzcash::PaymentAddress, uint256>> nullifierSet = pwallet->GetSaplingScriptPubKeyMan()->GetNullifiersForAddresses(shieldAddrs);
for (const auto& entry : saplingEntries) {
UniValue obj(UniValue::VOBJ);
obj.pushKV("txid", entry.op.hash.ToString());
obj.pushKV("outindex", (int)entry.op.n);
obj.pushKV("confirmations", entry.confirmations);
bool hasSaplingSpendingKey = pwallet->HaveSpendingKeyForPaymentAddress(entry.address);
obj.pushKV("spendable", hasSaplingSpendingKey);
obj.pushKV("address", KeyIO::EncodePaymentAddress(entry.address));
obj.pushKV("amount", ValueFromAmount(CAmount(entry.note.value()))); // note.value() is equivalent to plaintext.value()
obj.pushKV("memo", HexStrTrimmed(entry.memo));
if (hasSaplingSpendingKey) {
obj.pushKV("change", pwallet->GetSaplingScriptPubKeyMan()->IsNoteSaplingChange(nullifierSet, entry.address, entry.op));
}
const auto& nd = pwallet->mapWallet.at(entry.op.hash).mapSaplingNoteData.at(entry.op);
if (nd.nullifier) {
obj.pushKV("nullifier", nd.nullifier->ToString());
}
results.push_back(obj);
}
}
return results;
}
UniValue delegatoradd(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"delegatoradd \"address\" ( \"label\" )\n"
"\nAdd the provided address <address> into the allowed delegators AddressBook.\n"
"This enables the staking of coins delegated to this wallet, owned by <addr>\n"
"\nArguments:\n"
"1. \"address\" (string, required) The address to whitelist\n"
"2. \"label\" (string, optional) A label for the address to whitelist\n"
"\nResult:\n"
"true|false (boolean) true if successful.\n"
"\nExamples:\n" +
HelpExampleCli("delegatoradd", "DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6") +
HelpExampleRpc("delegatoradd", "\"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\"") +
HelpExampleRpc("delegatoradd", "\"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\" \"myPaperWallet\""));
bool isStakingAddress = false;
CTxDestination dest = DecodeDestination(request.params[0].get_str(), isStakingAddress);
if (!IsValidDestination(dest) || isStakingAddress)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PIVX address");
const std::string strLabel = (request.params.size() > 1 ? request.params[1].get_str() : "");
const CKeyID* keyID = boost::get<CKeyID>(&dest);
if (!keyID)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to get KeyID from PIVX address");
return pwallet->SetAddressBook(*keyID, strLabel, AddressBook::AddressBookPurpose::DELEGATOR);
}
UniValue delegatorremove(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"delegatorremove \"address\"\n"
"\nUpdates the provided address <address> from the allowed delegators keystore to a \"delegable\" status.\n"
"This disables the staking of coins delegated to this wallet, owned by <addr>\n"
"\nArguments:\n"
"1. \"address\" (string, required) The address to blacklist\n"
"\nResult:\n"
"true|false (boolean) true if successful.\n"
"\nExamples:\n" +
HelpExampleCli("delegatorremove", "DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6") +
HelpExampleRpc("delegatorremove", "\"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\""));
bool isStakingAddress = false;
CTxDestination dest = DecodeDestination(request.params[0].get_str(), isStakingAddress);
if (!IsValidDestination(dest) || isStakingAddress)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PIVX address");
const CKeyID* keyID = boost::get<CKeyID>(&dest);
if (!keyID)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to get KeyID from PIVX address");
if (!pwallet->HasAddressBook(*keyID))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to get PIVX address from addressBook");
std::string label = "";
auto optAdd = pwallet->GetAddressBookEntry(dest);
if (optAdd) {
label = optAdd->name;
}
return pwallet->SetAddressBook(*keyID, label, AddressBook::AddressBookPurpose::DELEGABLE);
}
static UniValue ListaddressesForPurpose(CWallet* const pwallet, const std::string strPurpose)
{
const CChainParams::Base58Type addrType = (
AddressBook::IsColdStakingPurpose(strPurpose) ?
CChainParams::STAKING_ADDRESS :
CChainParams::PUBKEY_ADDRESS);
UniValue ret(UniValue::VARR);
{
LOCK(pwallet->cs_wallet);
for (auto it = pwallet->NewAddressBookIterator(); it.IsValid(); it.Next()) {
auto addrBook = it.GetValue();
if (addrBook.purpose != strPurpose) continue;
auto dest = it.GetCTxDestKey();
if (!dest) continue;
UniValue entry(UniValue::VOBJ);
entry.pushKV("label", addrBook.name);
entry.pushKV("address", EncodeDestination(*dest, addrType));
ret.push_back(entry);
}
}
return ret;
}
UniValue listdelegators(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"listdelegators ( blacklist )\n"
"\nShows the list of allowed delegator addresses for cold staking.\n"
"\nArguments:\n"
"1. blacklist (boolean, optional, default = false) Show addresses removed\n"
" from the delegators whitelist\n"
"\nResult:\n"
"[\n"
" {\n"
" \"label\": \"yyy\", (string) Address label\n"
" \"address\": \"xxx\", (string) PIVX address string\n"
" }\n"
" ...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listdelegators" , "") +
HelpExampleRpc("listdelegators", ""));
const bool fBlacklist = (request.params.size() > 0 ? request.params[0].get_bool() : false);
return (fBlacklist ?
ListaddressesForPurpose(pwallet, AddressBook::AddressBookPurpose::DELEGABLE) :
ListaddressesForPurpose(pwallet, AddressBook::AddressBookPurpose::DELEGATOR));
}
UniValue liststakingaddresses(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || !request.params.empty())
throw std::runtime_error(
"liststakingaddresses\n"
"\nShows the list of staking addresses for this wallet.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"label\": \"yyy\", (string) Address label\n"
" \"address\": \"xxx\", (string) PIVX address string\n"
" }\n"
" ...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("liststakingaddresses" , "") +
HelpExampleRpc("liststakingaddresses", ""));
return ListaddressesForPurpose(pwallet, AddressBook::AddressBookPurpose::COLD_STAKING);
}
UniValue listshieldaddresses(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"listshieldaddresses ( include_watchonly )\n"
"\nReturns the list of shield addresses belonging to the wallet.\n"
"\nArguments:\n"
"1. include_watchonly (bool, optional, default=false) Also include watchonly addresses (see 'importviewingkey')\n"
"\nResult:\n"
"[ (json array of string)\n"
" \"addr\" (string) a shield address belonging to the wallet\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listshieldaddresses", "")
+ HelpExampleRpc("listshieldaddresses", "")
);
LOCK2(cs_main, pwallet->cs_wallet);
bool fIncludeWatchonly = false;
if (request.params.size() > 0) {
fIncludeWatchonly = request.params[0].get_bool();
}
UniValue ret(UniValue::VARR);
std::set<libzcash::SaplingPaymentAddress> addresses;
pwallet->GetSaplingPaymentAddresses(addresses);
libzcash::SaplingIncomingViewingKey ivk;
libzcash::SaplingExtendedFullViewingKey extfvk;
for (libzcash::SaplingPaymentAddress addr : addresses) {
if (fIncludeWatchonly || pwallet->HaveSpendingKeyForPaymentAddress(addr)) {
ret.push_back(KeyIO::EncodePaymentAddress(addr));
}
}
return ret;
}
UniValue getrawchangeaddress(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || !request.params.empty())
throw std::runtime_error(
"getrawchangeaddress\n"
"\nReturns a new PIVX 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", ""));
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.GetID();
return EncodeDestination(keyID);
}
UniValue setlabel(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || 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 pivx address to be associated with a label.\n"
"2. \"label\" (string, required) The label to assign to the address.\n"
"\nExamples:\n" +
HelpExampleCli("setlabel", "\"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\" \"tabby\"") + HelpExampleRpc("setlabel", "\"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\", \"tabby\""));
LOCK2(cs_main, pwallet->cs_wallet);
CTxDestination dest = DecodeDestination(request.params[0].get_str());
if (!IsValidDestination(dest))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PIVX address");
std::string old_label = pwallet->GetNameForAddressBookEntry(dest);
std::string label = LabelFromValue(request.params[1]);
pwallet->SetAddressBook(dest, label, "");
return NullUniValue;
}