forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
misc.cpp
1555 lines (1381 loc) · 60.9 KB
/
misc.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-2020 The Bitcoin Core developers
// Copyright (c) 2014-2024 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <addressindex.h>
#include <chainparams.h>
#include <consensus/consensus.h>
#include <deploymentstatus.h>
#include <evo/mnauth.h>
#include <httpserver.h>
#include <index/blockfilterindex.h>
#include <index/coinstatsindex.h>
#include <index/txindex.h>
#include <init.h>
#include <interfaces/chain.h>
#include <interfaces/echo.h>
#include <interfaces/init.h>
#include <interfaces/ipc.h>
#include <key_io.h>
#include <net.h>
#include <node/context.h>
#include <rpc/blockchain.h>
#include <rpc/index_util.h>
#include <rpc/server.h>
#include <rpc/server_util.h>
#include <rpc/util.h>
#include <scheduler.h>
#include <script/descriptor.h>
#include <txmempool.h>
#include <util/check.h>
#include <util/message.h> // For MessageSign(), MessageVerify()
#include <util/strencodings.h>
#include <util/system.h>
#include <validation.h>
#include <masternode/sync.h>
#include <spork.h>
#include <stdint.h>
#ifdef HAVE_MALLOC_INFO
#include <malloc.h>
#endif
#include <univalue.h>
static RPCHelpMan debug()
{
return RPCHelpMan{"debug",
"Change debug category on the fly. Specify single category or use '+' to specify many.\n"
"The valid logging categories are: " + LogInstance().LogCategoriesString() + ".\n"
"libevent logging is configured on startup and cannot be modified by this RPC during runtime.\n"
"There are also a few meta-categories:\n"
" - \"all\", \"1\" and \"\" activate all categories at once;\n"
" - \"dash\" activates all Dash-specific categories at once;\n"
" - \"none\" (or \"0\") deactivates all categories at once.\n"
"Note: If specified category doesn't match any of the above, no error is thrown.\n",
{
{"category", RPCArg::Type::STR, RPCArg::Optional::NO, "The name of the debug category to turn on."},
},
RPCResult{
RPCResult::Type::STR, "result", "\"Debug mode: \" followed by the specified category",
},
RPCExamples {
HelpExampleCli("debug", "dash")
+ HelpExampleRpc("debug", "dash+net")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::string strMode = request.params[0].get_str();
LogInstance().DisableCategory(BCLog::ALL);
std::vector<std::string> categories = SplitString(strMode, '+');
if (std::find(categories.begin(), categories.end(), std::string("0")) == categories.end()) {
for (const auto& cat : categories) {
LogInstance().EnableCategory(cat);
}
}
return "Debug mode: " + LogInstance().LogCategoriesString(/*enabled_only=*/true);
},
};
}
static RPCHelpMan mnsync()
{
return RPCHelpMan{"mnsync",
"Returns the sync status, updates to the next step or resets it entirely.\n",
{
{"mode", RPCArg::Type::STR, RPCArg::Optional::NO, "[status|next|reset]"},
},
{
RPCResult{"for mode = status",
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::NUM, "AssetID", "The asset ID"},
{RPCResult::Type::STR, "AssetName", "The asset name"},
{RPCResult::Type::NUM, "AssetStartTime", "The asset start time"},
{RPCResult::Type::NUM, "Attempt", "The attempt"},
{RPCResult::Type::BOOL, "IsBlockchainSynced", "true if the blockchain synced"},
{RPCResult::Type::BOOL, "IsSynced", "true if synced"},
}},
RPCResult{"for mode = next|reset",
RPCResult::Type::STR, "", ""},
},
RPCExamples{""},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::string strMode = request.params[0].get_str();
const NodeContext& node = EnsureAnyNodeContext(request.context);
CHECK_NONFATAL(node.mn_sync);
auto& mn_sync = *node.mn_sync;
if(strMode == "status") {
UniValue objStatus(UniValue::VOBJ);
objStatus.pushKV("AssetID", mn_sync.GetAssetID());
objStatus.pushKV("AssetName", mn_sync.GetAssetName());
objStatus.pushKV("AssetStartTime", mn_sync.GetAssetStartTime());
objStatus.pushKV("Attempt", mn_sync.GetAttempt());
objStatus.pushKV("IsBlockchainSynced", mn_sync.IsBlockchainSynced());
objStatus.pushKV("IsSynced", mn_sync.IsSynced());
return objStatus;
}
if(strMode == "next")
{
mn_sync.SwitchToNextAsset();
return "sync updated to " + mn_sync.GetAssetName();
}
if(strMode == "reset")
{
mn_sync.Reset(true);
return "success";
}
return "failure";
},
};
}
/*
Used for updating/reading spork settings on the network
*/
static RPCHelpMan spork()
{
// default help, for basic mode
return RPCHelpMan{"spork",
"\nShows information about current state of sporks\n",
{
{"command", RPCArg::Type::STR, RPCArg::Optional::NO, "'show' to show all current spork values, 'active' to show which sporks are active"},
},
{
RPCResult{"For 'show'",
RPCResult::Type::OBJ_DYN, "", "keys are the sporks, and values indicates its value",
{
{RPCResult::Type::NUM, "SPORK_NAME", "The value of the specific spork with the name SPORK_NAME"},
}},
RPCResult{"For 'active'",
RPCResult::Type::OBJ_DYN, "", "keys are the sporks, and values indicates its status",
{
{RPCResult::Type::BOOL, "SPORK_NAME", "'true' for time-based sporks if spork is active and 'false' otherwise"},
}},
},
RPCExamples {
HelpExampleCli("spork", "show")
+ HelpExampleRpc("spork", "\"show\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
// basic mode, show info
std:: string strCommand = request.params[0].get_str();
const NodeContext& node = EnsureAnyNodeContext(request.context);
CHECK_NONFATAL(node.sporkman);
if (strCommand == "show") {
UniValue ret(UniValue::VOBJ);
for (const auto& sporkDef : sporkDefs) {
ret.pushKV(std::string(sporkDef.name), node.sporkman->GetSporkValue(sporkDef.sporkId));
}
return ret;
} else if(strCommand == "active"){
UniValue ret(UniValue::VOBJ);
for (const auto& sporkDef : sporkDefs) {
ret.pushKV(std::string(sporkDef.name), node.sporkman->IsSporkActive(sporkDef.sporkId));
}
return ret;
}
return NullUniValue;
},
};
}
static RPCHelpMan sporkupdate()
{
return RPCHelpMan{"sporkupdate",
"\nUpdate the value of the specific spork. Requires \"-sporkkey\" to be set to sign the message.\n",
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name of the spork to update"},
{"value", RPCArg::Type::NUM, RPCArg::Optional::NO, "The new desired value of the spork"},
},
RPCResult{
RPCResult::Type::STR, "result", "\"success\" if spork value was updated or this help otherwise"
},
RPCExamples{
HelpExampleCli("sporkupdate", "SPORK_2_INSTANTSEND_ENABLED 4070908800")
+ HelpExampleRpc("sporkupdate", "\"SPORK_2_INSTANTSEND_ENABLED\", 4070908800")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
// advanced mode, update spork values
SporkId nSporkID = CSporkManager::GetSporkIDByName(request.params[0].get_str());
if (nSporkID == SPORK_INVALID) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid spork name");
}
const NodeContext& node = EnsureAnyNodeContext(request.context);
PeerManager& peerman = EnsurePeerman(node);
CHECK_NONFATAL(node.sporkman);
// SPORK VALUE
int64_t nValue = request.params[1].get_int64();
// broadcast new spork
if (node.sporkman->UpdateSpork(peerman, nSporkID, nValue)) {
return "success";
}
return NullUniValue;
},
};
}
static RPCHelpMan validateaddress()
{
return RPCHelpMan{"validateaddress",
"\nReturn information about the given Dash address.\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The Dash address to validate"},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::BOOL, "isvalid", "If the address is valid or not"},
{RPCResult::Type::STR, "address", "The Dash address validated"},
{RPCResult::Type::STR_HEX, "scriptPubKey", "The hex-encoded scriptPubKey generated by the address"},
{RPCResult::Type::BOOL, "isscript", "If the key is a script"},
{RPCResult::Type::STR, "error", /* optional */ true, "Error message, if any"},
}
},
RPCExamples{
HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::string error_msg;
CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg);
const bool isValid = IsValidDestination(dest);
CHECK_NONFATAL(isValid == error_msg.empty());
UniValue ret(UniValue::VOBJ);
ret.pushKV("isvalid", isValid);
if (isValid) {
std::string currentAddress = EncodeDestination(dest);
ret.pushKV("address", currentAddress);
CScript scriptPubKey = GetScriptForDestination(dest);
ret.pushKV("scriptPubKey", HexStr(scriptPubKey));;
UniValue detail = DescribeAddress(dest);
ret.pushKVs(detail);
} else {
ret.pushKV("error", error_msg);
}
return ret;
},
};
}
static RPCHelpMan createmultisig()
{
return RPCHelpMan{"createmultisig",
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n",
{
{"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys."},
{"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex-encoded public keys.",
{
{"key", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The hex-encoded public key"},
}},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "address", "The value of the new multisig address."},
{RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script."},
{RPCResult::Type::STR, "descriptor", "The descriptor for this multisig."},
}
},
RPCExamples{
"\nCreate a multisig address from 2 public keys\n"
+ HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("createmultisig", "2, [\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\",\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\"]")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
int required = request.params[0].get_int();
// Get the public keys
const UniValue& keys = request.params[1].get_array();
std::vector<CPubKey> pubkeys;
for (unsigned int i = 0; i < keys.size(); ++i) {
if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) {
pubkeys.push_back(HexToPubKey(keys[i].get_str()));
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid public key: %s\n.", keys[i].get_str()));
}
}
// Construct using pay-to-script-hash:
FillableSigningProvider keystore;
CScript inner;
const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, keystore, inner);
// Make the descriptor
std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore);
UniValue result(UniValue::VOBJ);
result.pushKV("address", EncodeDestination(dest));
result.pushKV("redeemScript", HexStr(inner));
result.pushKV("descriptor", descriptor->ToString());
return result;
},
};
}
static RPCHelpMan getdescriptorinfo()
{
const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)";
return RPCHelpMan{"getdescriptorinfo",
{"\nAnalyses a descriptor.\n"},
{
{"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor"},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "descriptor", "The descriptor in canonical form, without private keys"},
{RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"},
{RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"},
{RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"},
{RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"},
}
},
RPCExamples{
"\nAnalyse a descriptor\n"
+ HelpExampleCli("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"") +
HelpExampleRpc("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
RPCTypeCheck(request.params, {UniValue::VSTR});
FlatSigningProvider provider;
std::string error;
auto desc = Parse(request.params[0].get_str(), provider, error);
if (!desc) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
}
UniValue result(UniValue::VOBJ);
result.pushKV("descriptor", desc->ToString());
result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str()));
result.pushKV("isrange", desc->IsRange());
result.pushKV("issolvable", desc->IsSolvable());
result.pushKV("hasprivatekeys", provider.keys.size() > 0);
return result;
},
};
}
static RPCHelpMan deriveaddresses()
{
const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
return RPCHelpMan{"deriveaddresses",
"\nDerives one or more addresses corresponding to an output descriptor.\n"
"Examples of output descriptors are:\n"
" pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
" sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
" raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
"\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
"or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
"For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
{
{"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor"},
{"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED_NAMED_ARG, "If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive."},
},
RPCResult{
RPCResult::Type::ARR, "", "",
{
{RPCResult::Type::STR, "address", "the derived addresses"},
}
},
RPCExamples{
"\nFirst three receive addresses\n"
+ HelpExampleCli("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\" \"[0,2]\"") +
HelpExampleRpc("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\", \"[0,2]\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType()}); // Range argument is checked later
const std::string desc_str = request.params[0].get_str();
int64_t range_begin = 0;
int64_t range_end = 0;
if (request.params.size() >= 2 && !request.params[1].isNull()) {
std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]);
}
FlatSigningProvider key_provider;
std::string error;
auto desc = Parse(desc_str, key_provider, error, /* require_checksum = */ true);
if (!desc) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
}
if (!desc->IsRange() && request.params.size() > 1) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
}
if (desc->IsRange() && request.params.size() == 1) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
}
UniValue addresses(UniValue::VARR);
for (int i = range_begin; i <= range_end; ++i) {
FlatSigningProvider provider;
std::vector<CScript> scripts;
if (!desc->Expand(i, key_provider, scripts, provider)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
}
for (const CScript &script : scripts) {
CTxDestination dest;
if (!ExtractDestination(script, dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Descriptor does not have a corresponding address");
}
addresses.push_back(EncodeDestination(dest));
}
}
// This should not be possible, but an assert seems overkill:
if (addresses.empty()) {
throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
}
return addresses;
},
};
}
static RPCHelpMan verifymessage()
{
return RPCHelpMan{"verifymessage",
"\nVerify a signed message\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The Dash address to use for the signature."},
{"signature", RPCArg::Type::STR, RPCArg::Optional::NO, "The signature provided by the signer in base 64 encoding (see signmessage)."},
{"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message that was signed."},
},
RPCResult{
RPCResult::Type::BOOL, "", "If the signature is verified or not."
},
RPCExamples{
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"" + EXAMPLE_ADDRESS[0] + "\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"" + EXAMPLE_ADDRESS[0] + "\" \"signature\" \"my message\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("verifymessage", "\"" + EXAMPLE_ADDRESS[0] + "\", \"signature\", \"my message\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
LOCK(cs_main);
std::string strAddress = request.params[0].get_str();
std::string strSign = request.params[1].get_str();
std::string strMessage = request.params[2].get_str();
switch (MessageVerify(strAddress, strSign, strMessage)) {
case MessageVerificationResult::ERR_INVALID_ADDRESS:
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
case MessageVerificationResult::ERR_ADDRESS_NO_KEY:
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
case MessageVerificationResult::ERR_MALFORMED_SIGNATURE:
throw JSONRPCError(RPC_TYPE_ERROR, "Malformed base64 encoding");
case MessageVerificationResult::ERR_PUBKEY_NOT_RECOVERED:
case MessageVerificationResult::ERR_NOT_SIGNED:
return false;
case MessageVerificationResult::OK:
return true;
}
return false;
},
};
}
static RPCHelpMan signmessagewithprivkey()
{
return RPCHelpMan{"signmessagewithprivkey",
"\nSign a message with the private key of an address\n",
{
{"privkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The private key to sign the message with."},
{"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message to create a signature of."},
},
RPCResult{
RPCResult::Type::STR, "signature", "The signature of the message encoded in base 64"
},
RPCExamples{
"\nCreate the signature\n"
+ HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"" + EXAMPLE_ADDRESS[0] + "\" \"signature\" \"my message\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::string strPrivkey = request.params[0].get_str();
std::string strMessage = request.params[1].get_str();
CKey key = DecodeSecret(strPrivkey);
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
}
std::string signature;
if (!MessageSign(key, strMessage, signature)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
}
return signature;
},
};
}
static RPCHelpMan setmocktime()
{
return RPCHelpMan{"setmocktime",
"\nSet the local time to given timestamp (-regtest only)\n",
{
{"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, UNIX_EPOCH_TIME + "\n"
"Pass 0 to go back to using the system time."},
},
RPCResult{RPCResult::Type::NONE, "", ""},
RPCExamples{""},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
if (!Params().IsMockableChain()) {
throw std::runtime_error("setmocktime is for regression testing (-regtest mode) only");
}
// For now, don't change mocktime if we're in the middle of validation, as
// this could have an effect on mempool time-based eviction, as well as
// IsCurrentForFeeEstimation() and IsInitialBlockDownload().
// TODO: figure out the right way to synchronize around mocktime, and
// ensure all call sites of GetTime() are accessing this safely.
LOCK(cs_main);
RPCTypeCheck(request.params, {UniValue::VNUM});
const int64_t time{request.params[0].get_int64()};
if (time < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime can not be negative: %s.", time));
}
SetMockTime(time);
if (auto* node_context = GetContext<NodeContext>(request.context)) {
for (const auto& chain_client : node_context->chain_clients) {
chain_client->setMockTime(time);
}
}
return NullUniValue;
},
};
}
static RPCHelpMan mnauth()
{
return RPCHelpMan{"mnauth",
"\nOverride MNAUTH processing results for the specified node with a user provided data (-regtest only).\n",
{
{"nodeId", RPCArg::Type::NUM, RPCArg::Optional::NO, "Internal peer id of the node the mock data gets added to."},
{"proTxHash", RPCArg::Type::STR, RPCArg::Optional::NO, "The authenticated proTxHash as hex string."},
{"publicKey", RPCArg::Type::STR, RPCArg::Optional::NO, "The authenticated public key as hex string."},
},
RPCResult{
RPCResult::Type::BOOL, "result", "true, if the node was updated"
},
RPCExamples{""},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
if (!Params().MineBlocksOnDemand())
throw std::runtime_error("mnauth for regression testing (-regtest mode) only");
int64_t nodeId = request.params[0].get_int64();
uint256 proTxHash = ParseHashV(request.params[1], "proTxHash");
if (proTxHash.IsNull()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "proTxHash invalid");
}
ChainstateManager& chainman = EnsureAnyChainman(request.context);
CBLSPublicKey publicKey;
const bool bls_legacy_scheme{!DeploymentActiveAfter(chainman.ActiveChain().Tip(), Params().GetConsensus(), Consensus::DEPLOYMENT_V19)};
publicKey.SetHexStr(request.params[2].get_str(), bls_legacy_scheme);
if (!publicKey.IsValid()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "publicKey invalid");
}
const NodeContext& node = EnsureAnyNodeContext(request.context);
bool fSuccess = node.connman->ForNode(nodeId, CConnman::AllNodes, [&](CNode* pNode){
pNode->SetVerifiedProRegTxHash(proTxHash);
pNode->SetVerifiedPubKeyHash(publicKey.GetHash());
return true;
});
return fSuccess;
},
};
}
static bool getAddressFromIndex(const AddressType& type, const uint160 &hash, std::string &address)
{
if (type == AddressType::P2SH) {
address = EncodeDestination(ScriptHash(hash));
} else if (type == AddressType::P2PK_OR_P2PKH) {
address = EncodeDestination(PKHash(hash));
} else {
return false;
}
return true;
}
static bool getIndexKey(const std::string& str, uint160& hashBytes, AddressType& type)
{
CTxDestination dest = DecodeDestination(str);
if (!IsValidDestination(dest)) {
type = AddressType::UNKNOWN;
return false;
}
const PKHash *pkhash = std::get_if<PKHash>(&dest);
const ScriptHash *scriptID = std::get_if<ScriptHash>(&dest);
type = pkhash ? AddressType::P2PK_OR_P2PKH : AddressType::P2SH;
hashBytes = pkhash ? uint160(*pkhash) : uint160(*scriptID);
return true;
}
static bool getAddressesFromParams(const UniValue& params, std::vector<std::pair<uint160, AddressType> > &addresses)
{
if (params[0].isStr()) {
uint160 hashBytes;
AddressType type{AddressType::UNKNOWN};
if (!getIndexKey(params[0].get_str(), hashBytes, type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
addresses.push_back(std::make_pair(hashBytes, type));
} else if (params[0].isObject()) {
UniValue addressValues = find_value(params[0].get_obj(), "addresses");
if (!addressValues.isArray()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Addresses is expected to be an array");
}
for (const auto& address : addressValues.getValues()) {
uint160 hashBytes;
AddressType type{AddressType::UNKNOWN};
if (!getIndexKey(address.get_str(), hashBytes, type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
addresses.push_back(std::make_pair(hashBytes, type));
}
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
return true;
}
static RPCHelpMan getaddressmempool()
{
return RPCHelpMan{"getaddressmempool",
"\nReturns all mempool deltas for an address (requires addressindex to be enabled).\n",
{
{"addresses", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "",
{
{"address", RPCArg::Type::STR, RPCArg::Default{""}, "The base58check encoded address"},
},
},
},
RPCResult{
RPCResult::Type::ARR, "", "",
{
{RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "address", "The base58check encoded address"},
{RPCResult::Type::STR_HEX, "txid", "The related txid"},
{RPCResult::Type::NUM, "index", "The related input or output index"},
{RPCResult::Type::NUM, "satoshis", "The difference of duffs"},
{RPCResult::Type::NUM_TIME, "timestamp", "The time the transaction entered the mempool (seconds)"},
{RPCResult::Type::STR_HEX, "prevtxid", "The previous txid (if spending)"},
{RPCResult::Type::NUM, "prevout", "The previous transaction output index (if spending)"},
}},
}},
RPCExamples{
HelpExampleCli("getaddressmempool", "'{\"addresses\": [\"" + EXAMPLE_ADDRESS[0] + "\"]}'")
+ HelpExampleRpc("getaddressmempool", "{\"addresses\": [\"" + EXAMPLE_ADDRESS[0] + "\"]}")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
CTxMemPool& mempool = EnsureAnyMemPool(request.context);
std::vector<std::pair<uint160, AddressType>> addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<CMempoolAddressDeltaKey> input_addresses;
std::vector<CMempoolAddressDeltaEntry> indexes;
for (const auto& [hash, type] : addresses) {
input_addresses.push_back({type, hash});
}
if (!GetMempoolAddressDeltaIndex(mempool, input_addresses, indexes, /* timestamp_sort = */ true)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
UniValue result(UniValue::VARR);
for (const auto& [mempoolAddressKey, mempoolAddressDelta] : indexes) {
std::string address;
if (!getAddressFromIndex(mempoolAddressKey.m_address_type, mempoolAddressKey.m_address_bytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
UniValue delta(UniValue::VOBJ);
delta.pushKV("address", address);
delta.pushKV("txid", mempoolAddressKey.m_tx_hash.GetHex());
delta.pushKV("index", (int)mempoolAddressKey.m_tx_index);
delta.pushKV("satoshis", mempoolAddressDelta.m_amount);
delta.pushKV("timestamp", count_seconds(mempoolAddressDelta.m_time));
if (mempoolAddressDelta.m_amount < 0) {
delta.pushKV("prevtxid", mempoolAddressDelta.m_prev_hash.GetHex());
delta.pushKV("prevout", (int)mempoolAddressDelta.m_prev_out);
}
result.push_back(delta);
}
return result;
},
};
}
static RPCHelpMan getaddressutxos()
{
return RPCHelpMan{"getaddressutxos",
"\nReturns all unspent outputs for an address (requires addressindex to be enabled).\n",
{
{"addresses", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "",
{
{"address", RPCArg::Type::STR, RPCArg::Default{""}, "The base58check encoded address"},
},
},
},
RPCResult{
RPCResult::Type::ARR, "", "",
{
{RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "address", "The address base58check encoded"},
{RPCResult::Type::STR_HEX, "txid", "The output txid"},
{RPCResult::Type::NUM, "index", "The output index"},
{RPCResult::Type::STR_HEX, "script", "The script hex-encoded"},
{RPCResult::Type::NUM, "satoshis", "The number of duffs of the output"},
{RPCResult::Type::NUM, "height", "The block height"},
}},
}},
RPCExamples{
HelpExampleCli("getaddressutxos", "'{\"addresses\": [\"" + EXAMPLE_ADDRESS[0] + "\"]}'")
+ HelpExampleRpc("getaddressutxos", "{\"addresses\": [\"" + EXAMPLE_ADDRESS[0] + "\"]}")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::vector<std::pair<uint160, AddressType> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<CAddressUnspentIndexEntry> unspentOutputs;
ChainstateManager& chainman = EnsureAnyChainman(request.context);
{
LOCK(::cs_main);
for (const auto& address : addresses) {
if (!GetAddressUnspentIndex(*chainman.m_blockman.m_block_tree_db, address.first, address.second, unspentOutputs,
/* height_sort = */ true)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
}
UniValue result(UniValue::VARR);
for (const auto& [unspentKey, unspentValue] : unspentOutputs) {
UniValue output(UniValue::VOBJ);
std::string address;
if (!getAddressFromIndex(unspentKey.m_address_type, unspentKey.m_address_bytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
output.pushKV("address", address);
output.pushKV("txid", unspentKey.m_tx_hash.GetHex());
output.pushKV("outputIndex", (int)unspentKey.m_tx_index);
output.pushKV("script", HexStr(unspentValue.m_tx_script));
output.pushKV("satoshis", unspentValue.m_amount);
output.pushKV("height", unspentValue.m_block_height);
result.push_back(output);
}
return result;
},
};
}
static RPCHelpMan getaddressdeltas()
{
return RPCHelpMan{"getaddressdeltas",
"\nReturns all changes for an address (requires addressindex to be enabled).\n",
{
{"addresses", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "",
{
{"address", RPCArg::Type::STR, RPCArg::Default{""}, "The base58check encoded address"},
},
},
},
RPCResult{
RPCResult::Type::ARR, "", "",
{
{RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::NUM, "satoshis", "The difference of duffs"},
{RPCResult::Type::STR_HEX, "txid", "The related txid"},
{RPCResult::Type::NUM, "index", "The related input or output index"},
{RPCResult::Type::NUM, "blockindex", "The related block index"},
{RPCResult::Type::NUM, "height", "The block height"},
{RPCResult::Type::STR, "address", "The base58check encoded address"},
}},
}},
RPCExamples{
HelpExampleCli("getaddressdeltas", "'{\"addresses\": [\"" + EXAMPLE_ADDRESS[0] + "\"]}'")
+ HelpExampleRpc("getaddressdeltas", "{\"addresses\": [\"" + EXAMPLE_ADDRESS[0] + "\"]}")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
UniValue startValue = find_value(request.params[0].get_obj(), "start");
UniValue endValue = find_value(request.params[0].get_obj(), "end");
int start = 0;
int end = 0;
if (startValue.isNum() && endValue.isNum()) {
start = startValue.get_int();
end = endValue.get_int();
if (end < start) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "End value is expected to be greater than start");
}
}
std::vector<std::pair<uint160, AddressType> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<CAddressIndexEntry> addressIndex;
ChainstateManager& chainman = EnsureAnyChainman(request.context);
{
LOCK(::cs_main);
for (const auto& address : addresses) {
if (start > 0 && end > 0) {
if (!GetAddressIndex(*chainman.m_blockman.m_block_tree_db, address.first, address.second,
addressIndex, start, end))
{
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
} else {
if (!GetAddressIndex(*chainman.m_blockman.m_block_tree_db, address.first, address.second,
addressIndex))
{
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}
}
}
UniValue result(UniValue::VARR);
for (const auto& [indexKey, indexDelta] : addressIndex) {
std::string address;
if (!getAddressFromIndex(indexKey.m_address_type, indexKey.m_address_bytes, address)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown address type");
}
UniValue delta(UniValue::VOBJ);
delta.pushKV("satoshis", indexDelta);
delta.pushKV("txid", indexKey.m_tx_hash.GetHex());
delta.pushKV("index", (int)indexKey.m_tx_index);
delta.pushKV("blockindex", (int)indexKey.m_block_tx_pos);
delta.pushKV("height", indexKey.m_block_height);
delta.pushKV("address", address);
result.push_back(delta);
}
return result;
},
};
}
static RPCHelpMan getaddressbalance()
{
return RPCHelpMan{"getaddressbalance",
"\nReturns the balance for an address(es) (requires addressindex to be enabled).\n",
{
{"addresses", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "",
{
{"address", RPCArg::Type::STR, RPCArg::Default{""}, "The base58check encoded address"},
},
},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::NUM, "balance", "The current total balance in duffs"},
{RPCResult::Type::NUM, "balance_immature", "The current immature balance in duffs"},
{RPCResult::Type::NUM, "balance_spendable", "The current spendable balance in duffs"},
{RPCResult::Type::NUM, "received", "The total number of duffs received (including change)"},
}},
RPCExamples{
HelpExampleCli("getaddressbalance", "'{\"addresses\": [\"" + EXAMPLE_ADDRESS[0] + "\"]}'")
+ HelpExampleRpc("getaddressbalance", "{\"addresses\": [\"" + EXAMPLE_ADDRESS[0] + "\"]}")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::vector<std::pair<uint160, AddressType> > addresses;
if (!getAddressesFromParams(request.params, addresses)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
std::vector<CAddressIndexEntry> addressIndex;
ChainstateManager& chainman = EnsureAnyChainman(request.context);
int nHeight;
{
LOCK(::cs_main);
for (const auto& address : addresses) {
if (!GetAddressIndex(*chainman.m_blockman.m_block_tree_db, address.first, address.second, addressIndex)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for address");
}
}