Bitcoin ABC 0.32.4
P2P Digital Currency
rpcwallet.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <chainparams.h> // for GetConsensus.
7#include <coins.h>
8#include <common/system.h>
9#include <config.h>
10#include <consensus/amount.h>
12#include <core_io.h>
13#include <interfaces/chain.h>
14#include <key_io.h>
15#include <node/context.h>
16#include <outputtype.h>
17#include <policy/fees.h>
18#include <policy/policy.h>
20#include <rpc/server.h>
21#include <rpc/util.h>
22#include <script/descriptor.h>
23#include <util/bip32.h>
24#include <util/error.h>
25#include <util/moneystr.h>
26#include <util/result.h>
27#include <util/string.h>
28#include <util/translation.h>
29#include <util/url.h>
30#include <util/vector.h>
31#include <wallet/coincontrol.h>
32#include <wallet/context.h>
33#include <wallet/load.h>
34#include <wallet/receive.h>
35#include <wallet/rpc/util.h>
36#include <wallet/rpcwallet.h>
37#include <wallet/spend.h>
38#include <wallet/wallet.h>
39#include <wallet/walletdb.h>
40#include <wallet/walletutil.h>
41
42#include <univalue.h>
43
44#include <event2/http.h>
45
46#include <optional>
47#include <variant>
48
50
54bool HaveKey(const SigningProvider &wallet, const CKey &key) {
55 CKey key2;
56 key2.Set(key.begin(), key.end(), !key.IsCompressed());
57 return wallet.HaveKey(key.GetPubKey().GetID()) ||
58 wallet.HaveKey(key2.GetPubKey().GetID());
59}
60
61static void WalletTxToJSON(const CWallet &wallet, const CWalletTx &wtx,
62 UniValue &entry)
64 interfaces::Chain &chain = wallet.chain();
65 int confirms = wallet.GetTxDepthInMainChain(wtx);
66 entry.pushKV("confirmations", confirms);
67 if (wtx.IsCoinBase()) {
68 entry.pushKV("generated", true);
69 }
70 if (confirms > 0) {
71 entry.pushKV("blockhash", wtx.m_confirm.hashBlock.GetHex());
72 entry.pushKV("blockheight", wtx.m_confirm.block_height);
73 entry.pushKV("blockindex", wtx.m_confirm.nIndex);
74 int64_t block_time;
75 CHECK_NONFATAL(chain.findBlock(wtx.m_confirm.hashBlock,
76 FoundBlock().time(block_time)));
77 entry.pushKV("blocktime", block_time);
78 } else {
79 entry.pushKV("trusted", CachedTxIsTrusted(wallet, wtx));
80 }
81 uint256 hash = wtx.GetId();
82 entry.pushKV("txid", hash.GetHex());
83 UniValue conflicts(UniValue::VARR);
84 for (const uint256 &conflict : wallet.GetTxConflicts(wtx)) {
85 conflicts.push_back(conflict.GetHex());
86 }
87 entry.pushKV("walletconflicts", conflicts);
88 entry.pushKV("time", wtx.GetTxTime());
89 entry.pushKV("timereceived", int64_t{wtx.nTimeReceived});
90
91 for (const std::pair<const std::string, std::string> &item : wtx.mapValue) {
92 entry.pushKV(item.first, item.second);
93 }
94}
95
97 return RPCHelpMan{
98 "getnewaddress",
99 "Returns a new eCash address for receiving payments.\n"
100 "If 'label' is specified, it is added to the address book \n"
101 "so payments received with the address will be associated with "
102 "'label'.\n",
103 {
104 {"label", RPCArg::Type::STR, RPCArg::Default{""},
105 "The label name for the address to be linked to. If not provided, "
106 "the default label \"\" is used. It can also be set to the empty "
107 "string \"\" to represent the default label. The label does not "
108 "need to exist, it will be created if there is no label by the "
109 "given name."},
110 },
111 RPCResult{RPCResult::Type::STR, "address", "The new eCash address"},
112 RPCExamples{HelpExampleCli("getnewaddress", "") +
113 HelpExampleRpc("getnewaddress", "")},
114 [&](const RPCHelpMan &self, const Config &config,
115 const JSONRPCRequest &request) -> UniValue {
116 std::shared_ptr<CWallet> const wallet =
118 if (!wallet) {
119 return NullUniValue;
120 }
121 CWallet *const pwallet = wallet.get();
122 LOCK(pwallet->cs_wallet);
123
124 if (!pwallet->CanGetAddresses()) {
126 "Error: This wallet has no available keys");
127 }
128
129 // Parse the label first so we don't generate a key if there's an
130 // error
131 std::string label;
132 if (!request.params[0].isNull()) {
133 label = LabelFromValue(request.params[0]);
134 }
135
136 auto op_dest =
137 pwallet->GetNewDestination(OutputType::LEGACY, label);
138 if (!op_dest) {
140 util::ErrorString(op_dest).original);
141 }
142
143 return EncodeDestination(*op_dest, config);
144 },
145 };
146}
147
149 return RPCHelpMan{
150 "getrawchangeaddress",
151 "Returns a new Bitcoin address, for receiving change.\n"
152 "This is for use with raw transactions, NOT normal use.\n",
153 {},
154 RPCResult{RPCResult::Type::STR, "address", "The address"},
155 RPCExamples{HelpExampleCli("getrawchangeaddress", "") +
156 HelpExampleRpc("getrawchangeaddress", "")},
157 [&](const RPCHelpMan &self, const Config &config,
158 const JSONRPCRequest &request) -> UniValue {
159 std::shared_ptr<CWallet> const wallet =
161 if (!wallet) {
162 return NullUniValue;
163 }
164 CWallet *const pwallet = wallet.get();
165
166 LOCK(pwallet->cs_wallet);
167
168 if (!pwallet->CanGetAddresses(true)) {
170 "Error: This wallet has no available keys");
171 }
172
173 OutputType output_type = pwallet->m_default_change_type.value_or(
174 pwallet->m_default_address_type);
175 if (!request.params[0].isNull()) {
176 if (!ParseOutputType(request.params[0].get_str(),
177 output_type)) {
179 strprintf("Unknown address type '%s'",
180 request.params[0].get_str()));
181 }
182 }
183
184 auto op_dest = pwallet->GetNewChangeDestination(output_type);
185 if (!op_dest) {
187 util::ErrorString(op_dest).original);
188 }
189 return EncodeDestination(*op_dest, config);
190 },
191 };
192}
193
195 return RPCHelpMan{
196 "setlabel",
197 "Sets the label associated with the given address.\n",
198 {
200 "The bitcoin address to be associated with a label."},
202 "The label to assign to the address."},
203 },
206 HelpExampleCli("setlabel",
207 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"tabby\"") +
209 "setlabel",
210 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"tabby\"")},
211 [&](const RPCHelpMan &self, const Config &config,
212 const JSONRPCRequest &request) -> UniValue {
213 std::shared_ptr<CWallet> const wallet =
215 if (!wallet) {
216 return NullUniValue;
217 }
218 CWallet *const pwallet = wallet.get();
219
220 LOCK(pwallet->cs_wallet);
221
222 CTxDestination dest = DecodeDestination(request.params[0].get_str(),
223 wallet->GetChainParams());
224 if (!IsValidDestination(dest)) {
226 "Invalid Bitcoin address");
227 }
228
229 std::string label = LabelFromValue(request.params[1]);
230
231 if (pwallet->IsMine(dest)) {
232 pwallet->SetAddressBook(dest, label, "receive");
233 } else {
234 pwallet->SetAddressBook(dest, label, "send");
235 }
236
237 return NullUniValue;
238 },
239 };
240}
241
242void ParseRecipients(const UniValue &address_amounts,
243 const UniValue &subtract_fee_outputs,
244 std::vector<CRecipient> &recipients,
245 const CChainParams &chainParams) {
246 std::set<CTxDestination> destinations;
247 int i = 0;
248 for (const std::string &address : address_amounts.getKeys()) {
249 CTxDestination dest = DecodeDestination(address, chainParams);
250 if (!IsValidDestination(dest)) {
252 std::string("Invalid Bitcoin address: ") +
253 address);
254 }
255
256 if (destinations.count(dest)) {
257 throw JSONRPCError(
259 std::string("Invalid parameter, duplicated address: ") +
260 address);
261 }
262 destinations.insert(dest);
263
264 CScript script_pub_key = GetScriptForDestination(dest);
265 Amount amount = AmountFromValue(address_amounts[i++]);
266
267 bool subtract_fee = false;
268 for (unsigned int idx = 0; idx < subtract_fee_outputs.size(); idx++) {
269 const UniValue &addr = subtract_fee_outputs[idx];
270 if (addr.get_str() == address) {
271 subtract_fee = true;
272 }
273 }
274
275 CRecipient recipient = {script_pub_key, amount, subtract_fee};
276 recipients.push_back(recipient);
277 }
278}
279
280UniValue SendMoney(CWallet *const pwallet, const CCoinControl &coin_control,
281 std::vector<CRecipient> &recipients, mapValue_t map_value,
282 bool broadcast = true) {
283 EnsureWalletIsUnlocked(pwallet);
284
285 // Shuffle recipient list
286 std::shuffle(recipients.begin(), recipients.end(), FastRandomContext());
287
288 // Send
289 constexpr int RANDOM_CHANGE_POSITION = -1;
290 auto res = CreateTransaction(
291 *pwallet, recipients, RANDOM_CHANGE_POSITION, coin_control,
293 if (!res) {
295 util::ErrorString(res).original);
296 }
297 const CTransactionRef &tx = res->tx;
298 pwallet->CommitTransaction(tx, std::move(map_value), /*orderForm=*/{},
299 broadcast);
300 return tx->GetId().GetHex();
301}
302
304 return RPCHelpMan{
305 "sendtoaddress",
306 "Send an amount to a given address.\n" + HELP_REQUIRING_PASSPHRASE,
307 {
309 "The bitcoin address to send to."},
311 "The amount in " + Currency::get().ticker + " to send. eg 0.1"},
313 "A comment used to store what the transaction is for.\n"
314 " This is not part of the "
315 "transaction, just kept in your wallet."},
317 "A comment to store the name of the person or organization\n"
318 " to which you're sending the "
319 "transaction. This is not part of the \n"
320 " transaction, just kept in "
321 "your wallet."},
322 {"subtractfeefromamount", RPCArg::Type::BOOL,
323 RPCArg::Default{false},
324 "The fee will be deducted from the amount being sent.\n"
325 " The recipient will receive "
326 "less bitcoins than you enter in the amount field."},
327 {"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{true},
328 "(only available if avoid_reuse wallet flag is set) Avoid "
329 "spending from dirty addresses; addresses are considered\n"
330 " dirty if they have previously "
331 "been used in a transaction."},
332 },
333 RPCResult{RPCResult::Type::STR_HEX, "txid", "The transaction id."},
335 HelpExampleCli("sendtoaddress",
336 "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 100000") +
337 HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvay"
338 "dd\" 100000 \"donation\" \"seans "
339 "outpost\"") +
340 HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44"
341 "Jvaydd\" 100000 \"\" \"\" true") +
342 HelpExampleRpc("sendtoaddress",
343 "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvay"
344 "dd\", 100000, \"donation\", \"seans "
345 "outpost\"")},
346 [&](const RPCHelpMan &self, const Config &config,
347 const JSONRPCRequest &request) -> UniValue {
348 std::shared_ptr<CWallet> const wallet =
350 if (!wallet) {
351 return NullUniValue;
352 }
353 CWallet *const pwallet = wallet.get();
354
355 // Make sure the results are valid at least up to the most recent
356 // block the user could have gotten from another RPC command prior
357 // to now
358 pwallet->BlockUntilSyncedToCurrentChain();
359
360 LOCK(pwallet->cs_wallet);
361
362 // Wallet comments
363 mapValue_t mapValue;
364 if (!request.params[2].isNull() &&
365 !request.params[2].get_str().empty()) {
366 mapValue["comment"] = request.params[2].get_str();
367 }
368 if (!request.params[3].isNull() &&
369 !request.params[3].get_str().empty()) {
370 mapValue["to"] = request.params[3].get_str();
371 }
372
373 bool fSubtractFeeFromAmount = false;
374 if (!request.params[4].isNull()) {
375 fSubtractFeeFromAmount = request.params[4].get_bool();
376 }
377
378 CCoinControl coin_control;
379 coin_control.m_avoid_address_reuse =
380 GetAvoidReuseFlag(pwallet, request.params[5]);
381 // We also enable partial spend avoidance if reuse avoidance is set.
382 coin_control.m_avoid_partial_spends |=
383 coin_control.m_avoid_address_reuse;
384
385 EnsureWalletIsUnlocked(pwallet);
386
387 UniValue address_amounts(UniValue::VOBJ);
388 const std::string address = request.params[0].get_str();
389 address_amounts.pushKV(address, request.params[1]);
390 UniValue subtractFeeFromAmount(UniValue::VARR);
391 if (fSubtractFeeFromAmount) {
392 subtractFeeFromAmount.push_back(address);
393 }
394
395 std::vector<CRecipient> recipients;
396 ParseRecipients(address_amounts, subtractFeeFromAmount, recipients,
397 wallet->GetChainParams());
398
399 return SendMoney(pwallet, coin_control, recipients, mapValue);
400 },
401 };
402}
403
405 return RPCHelpMan{
406 "listaddressgroupings",
407 "Lists groups of addresses which have had their common ownership\n"
408 "made public by common use as inputs or as the resulting change\n"
409 "in past transactions\n",
410 {},
412 "",
413 "",
414 {
416 "",
417 "",
418 {
420 "",
421 "",
422 {
423 {RPCResult::Type::STR, "address",
424 "The bitcoin address"},
426 "The amount in " + Currency::get().ticker},
427 {RPCResult::Type::STR, "label",
428 /* optional */ true, "The label"},
429 }},
430 }},
431 }},
432 RPCExamples{HelpExampleCli("listaddressgroupings", "") +
433 HelpExampleRpc("listaddressgroupings", "")},
434 [&](const RPCHelpMan &self, const Config &config,
435 const JSONRPCRequest &request) -> UniValue {
436 std::shared_ptr<CWallet> const wallet =
438 if (!wallet) {
439 return NullUniValue;
440 }
441 const CWallet *const pwallet = wallet.get();
442
443 // Make sure the results are valid at least up to the most recent
444 // block the user could have gotten from another RPC command prior
445 // to now
446 pwallet->BlockUntilSyncedToCurrentChain();
447
448 LOCK(pwallet->cs_wallet);
449
450 UniValue jsonGroupings(UniValue::VARR);
451 std::map<CTxDestination, Amount> balances =
452 GetAddressBalances(*pwallet);
453 for (const std::set<CTxDestination> &grouping :
454 GetAddressGroupings(*pwallet)) {
455 UniValue jsonGrouping(UniValue::VARR);
456 for (const CTxDestination &address : grouping) {
457 UniValue addressInfo(UniValue::VARR);
458 addressInfo.push_back(EncodeDestination(address, config));
459 addressInfo.push_back(balances[address]);
460
461 const auto *address_book_entry =
462 pwallet->FindAddressBookEntry(address);
463 if (address_book_entry) {
464 addressInfo.push_back(address_book_entry->GetLabel());
465 }
466 jsonGrouping.push_back(addressInfo);
467 }
468 jsonGroupings.push_back(jsonGrouping);
469 }
470
471 return jsonGroupings;
472 },
473 };
474}
475
476static Amount GetReceived(const CWallet &wallet, const UniValue &params,
477 bool by_label)
479 std::set<CTxDestination> address_set;
480
481 if (by_label) {
482 // Get the set of addresses assigned to label
483 std::string label = LabelFromValue(params[0]);
484 address_set = wallet.GetLabelAddresses(label);
485 } else {
486 // Get the address
487 CTxDestination dest =
488 DecodeDestination(params[0].get_str(), wallet.GetChainParams());
489 if (!IsValidDestination(dest)) {
491 "Invalid Bitcoin address");
492 }
493 CScript script_pub_key = GetScriptForDestination(dest);
494 if (!wallet.IsMine(script_pub_key)) {
495 throw JSONRPCError(RPC_WALLET_ERROR, "Address not found in wallet");
496 }
497 address_set.insert(dest);
498 }
499
500 // Minimum confirmations
501 int min_depth = 1;
502 if (!params[1].isNull()) {
503 min_depth = params[1].getInt<int>();
504 }
505
506 // Tally
507 Amount amount = Amount::zero();
508 for (const std::pair<const TxId, CWalletTx> &wtx_pair : wallet.mapWallet) {
509 const CWalletTx &wtx = wtx_pair.second;
510 if (wtx.IsCoinBase() || wallet.GetTxDepthInMainChain(wtx) < min_depth) {
511 continue;
512 }
513
514 for (const CTxOut &txout : wtx.tx->vout) {
515 CTxDestination address;
516 if (ExtractDestination(txout.scriptPubKey, address) &&
517 wallet.IsMine(address) && address_set.count(address)) {
518 amount += txout.nValue;
519 }
520 }
521 }
522
523 return amount;
524}
525
527 return RPCHelpMan{
528 "getreceivedbyaddress",
529 "Returns the total amount received by the given address in "
530 "transactions with at least minconf confirmations.\n",
531 {
533 "The bitcoin address for transactions."},
534 {"minconf", RPCArg::Type::NUM, RPCArg::Default{1},
535 "Only include transactions confirmed at least this many times."},
536 },
538 "The total amount in " + Currency::get().ticker +
539 " received at this address."},
541 "\nThe amount from transactions with at least 1 confirmation\n" +
542 HelpExampleCli("getreceivedbyaddress",
543 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\"") +
544 "\nThe amount including unconfirmed transactions, zero "
545 "confirmations\n" +
546 HelpExampleCli("getreceivedbyaddress",
547 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" 0") +
548 "\nThe amount with at least 6 confirmations\n" +
549 HelpExampleCli("getreceivedbyaddress",
550 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" 6") +
551 "\nAs a JSON-RPC call\n" +
552 HelpExampleRpc("getreceivedbyaddress",
553 "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", 6")},
554 [&](const RPCHelpMan &self, const Config &config,
555 const JSONRPCRequest &request) -> UniValue {
556 std::shared_ptr<CWallet> const wallet =
558 if (!wallet) {
559 return NullUniValue;
560 }
561 const CWallet *const pwallet = wallet.get();
562
563 // Make sure the results are valid at least up to the most recent
564 // block the user could have gotten from another RPC command prior
565 // to now
566 pwallet->BlockUntilSyncedToCurrentChain();
567
568 LOCK(pwallet->cs_wallet);
569
570 return GetReceived(*pwallet, request.params,
571 /* by_label */ false);
572 },
573 };
574}
575
577 return RPCHelpMan{
578 "getreceivedbylabel",
579 "Returns the total amount received by addresses with <label> in "
580 "transactions with at least [minconf] confirmations.\n",
581 {
583 "The selected label, may be the default label using \"\"."},
584 {"minconf", RPCArg::Type::NUM, RPCArg::Default{1},
585 "Only include transactions confirmed at least this many times."},
586 },
588 "The total amount in " + Currency::get().ticker +
589 " received for this label."},
590 RPCExamples{"\nAmount received by the default label with at least 1 "
591 "confirmation\n" +
592 HelpExampleCli("getreceivedbylabel", "\"\"") +
593 "\nAmount received at the tabby label including "
594 "unconfirmed amounts with zero confirmations\n" +
595 HelpExampleCli("getreceivedbylabel", "\"tabby\" 0") +
596 "\nThe amount with at least 6 confirmations\n" +
597 HelpExampleCli("getreceivedbylabel", "\"tabby\" 6") +
598 "\nAs a JSON-RPC call\n" +
599 HelpExampleRpc("getreceivedbylabel", "\"tabby\", 6")},
600 [&](const RPCHelpMan &self, const Config &config,
601 const JSONRPCRequest &request) -> UniValue {
602 std::shared_ptr<CWallet> const wallet =
604 if (!wallet) {
605 return NullUniValue;
606 }
607 CWallet *const pwallet = wallet.get();
608
609 // Make sure the results are valid at least up to the most recent
610 // block the user could have gotten from another RPC command prior
611 // to now
612 pwallet->BlockUntilSyncedToCurrentChain();
613
614 LOCK(pwallet->cs_wallet);
615
616 return GetReceived(*pwallet, request.params,
617 /* by_label */ true);
618 },
619 };
620}
621
623 return RPCHelpMan{
624 "getbalance",
625 "Returns the total available balance.\n"
626 "The available balance is what the wallet considers currently "
627 "spendable, and is\n"
628 "thus affected by options which limit spendability such as "
629 "-spendzeroconfchange.\n",
630 {
632 "Remains for backward compatibility. Must be excluded or set to "
633 "\"*\"."},
634 {"minconf", RPCArg::Type::NUM, RPCArg::Default{0},
635 "Only include transactions confirmed at least this many times."},
636 {"include_watchonly", RPCArg::Type::BOOL,
638 "true for watch-only wallets, otherwise false"},
639 "Also include balance in watch-only addresses (see "
640 "'importaddress')"},
641 {"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{true},
642 "(only available if avoid_reuse wallet flag is set) Do not "
643 "include balance in dirty outputs; addresses are considered dirty "
644 "if they have previously been used in a transaction."},
645 },
647 "The total amount in " + Currency::get().ticker +
648 " received for this wallet."},
650 "\nThe total amount in the wallet with 0 or more confirmations\n" +
651 HelpExampleCli("getbalance", "") +
652 "\nThe total amount in the wallet with at least 6 confirmations\n" +
653 HelpExampleCli("getbalance", "\"*\" 6") + "\nAs a JSON-RPC call\n" +
654 HelpExampleRpc("getbalance", "\"*\", 6")},
655 [&](const RPCHelpMan &self, const Config &config,
656 const JSONRPCRequest &request) -> UniValue {
657 std::shared_ptr<CWallet> const wallet =
659 if (!wallet) {
660 return NullUniValue;
661 }
662 const CWallet *const pwallet = wallet.get();
663
664 // Make sure the results are valid at least up to the most recent
665 // block the user could have gotten from another RPC command prior
666 // to now
667 pwallet->BlockUntilSyncedToCurrentChain();
668
669 LOCK(pwallet->cs_wallet);
670
671 const auto dummy_value{self.MaybeArg<std::string>("dummy")};
672 if (dummy_value && *dummy_value != "*") {
673 throw JSONRPCError(
675 "dummy first argument must be excluded or set to \"*\".");
676 }
677
678 const auto min_depth{self.Arg<int>("minconf")};
679
680 bool include_watchonly =
681 ParseIncludeWatchonly(request.params[2], *pwallet);
682
683 bool avoid_reuse = GetAvoidReuseFlag(pwallet, request.params[3]);
684
685 const auto bal = GetBalance(*pwallet, min_depth, avoid_reuse);
686
687 return bal.m_mine_trusted + (include_watchonly
688 ? bal.m_watchonly_trusted
689 : Amount::zero());
690 },
691 };
692}
693
695 return RPCHelpMan{
696 "getunconfirmedbalance",
697 "DEPRECATED\nIdentical to getbalances().mine.untrusted_pending\n",
698 {},
699 RPCResult{RPCResult::Type::NUM, "", "The balance"},
700 RPCExamples{""},
701 [&](const RPCHelpMan &self, const Config &config,
702 const JSONRPCRequest &request) -> UniValue {
703 std::shared_ptr<CWallet> const wallet =
705 if (!wallet) {
706 return NullUniValue;
707 }
708 const CWallet *const pwallet = wallet.get();
709
710 // Make sure the results are valid at least up to the most recent
711 // block the user could have gotten from another RPC command prior
712 // to now
713 pwallet->BlockUntilSyncedToCurrentChain();
714
715 LOCK(pwallet->cs_wallet);
716
717 return GetBalance(*pwallet).m_mine_untrusted_pending;
718 },
719 };
720}
721
723 return RPCHelpMan{
724 "sendmany",
725 "Send multiple times. Amounts are double-precision "
726 "floating point numbers." +
728 {
730 "Must be set to \"\" for backwards compatibility.",
732 .oneline_description = "\"\""}},
733 {
734 "amounts",
737 "The addresses and amounts",
738 {
740 "The bitcoin address is the key, the numeric amount (can "
741 "be string) in " +
742 Currency::get().ticker + " is the value"},
743 },
744 },
745 {"minconf", RPCArg::Type::NUM, RPCArg::Default{1},
746 "Only use the balance confirmed at least this many times."},
748 "A comment"},
749 {
750 "subtractfeefrom",
753 "The addresses.\n"
754 " The fee will be equally deducted "
755 "from the amount of each selected address.\n"
756 " Those recipients will receive less "
757 "bitcoins than you enter in their corresponding amount field.\n"
758 " If no addresses are specified "
759 "here, the sender pays the fee.",
760 {
762 "Subtract fee from this address"},
763 },
764 },
765 },
767 "The transaction id for the send. Only 1 transaction is "
768 "created regardless of the number of addresses."},
770 "\nSend two amounts to two different addresses:\n" +
772 "sendmany",
773 "\"\" "
774 "\"{\\\"bchtest:qplljx455cznj2yrtdhj0jcm7syxlzqnaqt0ku5kjl\\\":"
775 "0.01,"
776 "\\\"bchtest:qzmnuh8t24yrxq4mvjakt84r7j3f9tunlvm2p7qef9\\\":0."
777 "02}\"") +
778 "\nSend two amounts to two different addresses setting the "
779 "confirmation and comment:\n" +
781 "sendmany",
782 "\"\" "
783 "\"{\\\"bchtest:qplljx455cznj2yrtdhj0jcm7syxlzqnaqt0ku5kjl\\\":"
784 "0.01,"
785 "\\\"bchtest:qzmnuh8t24yrxq4mvjakt84r7j3f9tunlvm2p7qef9\\\":0."
786 "02}\" "
787 "6 \"testing\"") +
788 "\nSend two amounts to two different addresses, subtract fee "
789 "from amount:\n" +
791 "sendmany",
792 "\"\" "
793 "\"{\\\"bchtest:qplljx455cznj2yrtdhj0jcm7syxlzqnaqt0ku5kjl\\\":"
794 "0.01,"
795 "\\\"bchtest:qzmnuh8t24yrxq4mvjakt84r7j3f9tunlvm2p7qef9\\\":0."
796 "02}\" 1 \"\" "
797 "\"[\\\"bchtest:qplljx455cznj2yrtdhj0jcm7syxlzqnaqt0ku5kjl\\\","
798 "\\\"bchtest:qzmnuh8t24yrxq4mvjakt84r7j3f9tunlvm2p7qef9\\\"]"
799 "\"") +
800 "\nAs a JSON-RPC call\n" +
802 "sendmany",
803 "\"\", "
804 "{\"bchtest:qplljx455cznj2yrtdhj0jcm7syxlzqnaqt0ku5kjl\":0.01,"
805 "\"bchtest:qzmnuh8t24yrxq4mvjakt84r7j3f9tunlvm2p7qef9\":0.02}, "
806 "6, "
807 "\"testing\"")},
808 [&](const RPCHelpMan &self, const Config &config,
809 const JSONRPCRequest &request) -> UniValue {
810 std::shared_ptr<CWallet> const wallet =
812 if (!wallet) {
813 return NullUniValue;
814 }
815 CWallet *const pwallet = wallet.get();
816
817 // Make sure the results are valid at least up to the most recent
818 // block the user could have gotten from another RPC command prior
819 // to now
820 pwallet->BlockUntilSyncedToCurrentChain();
821
822 LOCK(pwallet->cs_wallet);
823
824 if (!request.params[0].isNull() &&
825 !request.params[0].get_str().empty()) {
827 "Dummy value must be set to \"\"");
828 }
829 UniValue sendTo = request.params[1].get_obj();
830
831 mapValue_t mapValue;
832 if (!request.params[3].isNull() &&
833 !request.params[3].get_str().empty()) {
834 mapValue["comment"] = request.params[3].get_str();
835 }
836
837 UniValue subtractFeeFromAmount(UniValue::VARR);
838 if (!request.params[4].isNull()) {
839 subtractFeeFromAmount = request.params[4].get_array();
840 }
841
842 std::vector<CRecipient> recipients;
843 ParseRecipients(sendTo, subtractFeeFromAmount, recipients,
844 wallet->GetChainParams());
845
846 CCoinControl coin_control;
847 return SendMoney(pwallet, coin_control, recipients,
848 std::move(mapValue));
849 },
850 };
851}
852
854 return RPCHelpMan{
855 "addmultisigaddress",
856 "Add an nrequired-to-sign multisignature address to the wallet. "
857 "Requires a new wallet backup.\n"
858 "Each key is a Bitcoin address or hex-encoded public key.\n"
859 "This functionality is only intended for use with non-watchonly "
860 "addresses.\n"
861 "See `importaddress` for watchonly p2sh address support.\n"
862 "If 'label' is specified (DEPRECATED), assign address to that label.\n"
863 "Note: This command is only compatible with legacy wallets.\n",
864 {
866 "The number of required signatures out of the n keys or "
867 "addresses."},
868 {
869 "keys",
872 "The bitcoin addresses or hex-encoded public keys",
873 {
875 "bitcoin address or hex-encoded public key"},
876 },
877 },
879 "A label to assign the addresses to."},
880 },
882 "",
883 "",
884 {
885 {RPCResult::Type::STR, "address",
886 "The value of the new multisig address"},
887 {RPCResult::Type::STR_HEX, "redeemScript",
888 "The string value of the hex-encoded redemption script"},
889 {RPCResult::Type::STR, "descriptor",
890 "The descriptor for this multisig"},
891 }},
893 "\nAdd a multisig address from 2 addresses\n" +
894 HelpExampleCli("addmultisigaddress",
895 "2 "
896 "\"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\","
897 "\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
898 "\nAs a JSON-RPC call\n" +
899 HelpExampleRpc("addmultisigaddress",
900 "2, "
901 "\"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\","
902 "\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")},
903 [&](const RPCHelpMan &self, const Config &config,
904 const JSONRPCRequest &request) -> UniValue {
905 std::shared_ptr<CWallet> const wallet =
907 if (!wallet) {
908 return NullUniValue;
909 }
910 CWallet *const pwallet = wallet.get();
911
912 LegacyScriptPubKeyMan &spk_man =
914
915 LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);
916
917 std::string label;
918 if (!request.params[2].isNull()) {
919 label = LabelFromValue(request.params[2]);
920 }
921
922 int required = request.params[0].getInt<int>();
923
924 // Get the public keys
925 const UniValue &keys_or_addrs = request.params[1].get_array();
926 std::vector<CPubKey> pubkeys;
927 for (size_t i = 0; i < keys_or_addrs.size(); ++i) {
928 if (IsHex(keys_or_addrs[i].get_str()) &&
929 (keys_or_addrs[i].get_str().length() == 66 ||
930 keys_or_addrs[i].get_str().length() == 130)) {
931 pubkeys.push_back(HexToPubKey(keys_or_addrs[i].get_str()));
932 } else {
933 pubkeys.push_back(AddrToPubKey(wallet->GetChainParams(),
934 spk_man,
935 keys_or_addrs[i].get_str()));
936 }
937 }
938
939 OutputType output_type = pwallet->m_default_address_type;
940
941 // Construct using pay-to-script-hash:
942 CScript inner;
944 required, pubkeys, output_type, spk_man, inner);
945 pwallet->SetAddressBook(dest, label, "send");
946
947 // Make the descriptor
948 std::unique_ptr<Descriptor> descriptor =
950
951 UniValue result(UniValue::VOBJ);
952 result.pushKV("address", EncodeDestination(dest, config));
953 result.pushKV("redeemScript", HexStr(inner));
954 result.pushKV("descriptor", descriptor->ToString());
955 return result;
956 },
957 };
958}
959
960struct tallyitem {
962 int nConf{std::numeric_limits<int>::max()};
963 std::vector<uint256> txids;
964 bool fIsWatchonly{false};
965 tallyitem() = default;
966};
967
968static UniValue ListReceived(const Config &config, const CWallet *const pwallet,
969 const UniValue &params, bool by_label)
970 EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
971 // Minimum confirmations
972 int nMinDepth = 1;
973 if (!params[0].isNull()) {
974 nMinDepth = params[0].getInt<int>();
975 }
976
977 // Whether to include empty labels
978 bool fIncludeEmpty = false;
979 if (!params[1].isNull()) {
980 fIncludeEmpty = params[1].get_bool();
981 }
982
984 if (ParseIncludeWatchonly(params[2], *pwallet)) {
985 filter |= ISMINE_WATCH_ONLY;
986 }
987
988 bool has_filtered_address = false;
989 CTxDestination filtered_address = CNoDestination();
990 if (!by_label && params.size() > 3) {
991 if (!IsValidDestinationString(params[3].get_str(),
992 pwallet->GetChainParams())) {
994 "address_filter parameter was invalid");
995 }
996 filtered_address =
997 DecodeDestination(params[3].get_str(), pwallet->GetChainParams());
998 has_filtered_address = true;
999 }
1000
1001 // Tally
1002 std::map<CTxDestination, tallyitem> mapTally;
1003 for (const std::pair<const TxId, CWalletTx> &pairWtx : pwallet->mapWallet) {
1004 const CWalletTx &wtx = pairWtx.second;
1005
1006 if (wtx.IsCoinBase()) {
1007 continue;
1008 }
1009
1010 int nDepth = pwallet->GetTxDepthInMainChain(wtx);
1011 if (nDepth < nMinDepth) {
1012 continue;
1013 }
1014
1015 for (const CTxOut &txout : wtx.tx->vout) {
1016 CTxDestination address;
1017 if (!ExtractDestination(txout.scriptPubKey, address)) {
1018 continue;
1019 }
1020
1021 if (has_filtered_address && !(filtered_address == address)) {
1022 continue;
1023 }
1024
1025 isminefilter mine = pwallet->IsMine(address);
1026 if (!(mine & filter)) {
1027 continue;
1028 }
1029
1030 tallyitem &item = mapTally[address];
1031 item.nAmount += txout.nValue;
1032 item.nConf = std::min(item.nConf, nDepth);
1033 item.txids.push_back(wtx.GetId());
1034 if (mine & ISMINE_WATCH_ONLY) {
1035 item.fIsWatchonly = true;
1036 }
1037 }
1038 }
1039
1040 // Reply
1042 std::map<std::string, tallyitem> label_tally;
1043
1044 // Create m_address_book iterator
1045 // If we aren't filtering, go from begin() to end()
1046 auto start = pwallet->m_address_book.begin();
1047 auto end = pwallet->m_address_book.end();
1048 // If we are filtering, find() the applicable entry
1049 if (has_filtered_address) {
1050 start = pwallet->m_address_book.find(filtered_address);
1051 if (start != end) {
1052 end = std::next(start);
1053 }
1054 }
1055
1056 for (auto item_it = start; item_it != end; ++item_it) {
1057 if (item_it->second.IsChange()) {
1058 continue;
1059 }
1060 const CTxDestination &address = item_it->first;
1061 const std::string &label = item_it->second.GetLabel();
1062 std::map<CTxDestination, tallyitem>::iterator it =
1063 mapTally.find(address);
1064 if (it == mapTally.end() && !fIncludeEmpty) {
1065 continue;
1066 }
1067
1068 Amount nAmount = Amount::zero();
1069 int nConf = std::numeric_limits<int>::max();
1070 bool fIsWatchonly = false;
1071 if (it != mapTally.end()) {
1072 nAmount = (*it).second.nAmount;
1073 nConf = (*it).second.nConf;
1074 fIsWatchonly = (*it).second.fIsWatchonly;
1075 }
1076
1077 if (by_label) {
1078 tallyitem &_item = label_tally[label];
1079 _item.nAmount += nAmount;
1080 _item.nConf = std::min(_item.nConf, nConf);
1081 _item.fIsWatchonly = fIsWatchonly;
1082 } else {
1084 if (fIsWatchonly) {
1085 obj.pushKV("involvesWatchonly", true);
1086 }
1087 obj.pushKV("address", EncodeDestination(address, config));
1088 obj.pushKV("amount", nAmount);
1089 obj.pushKV("confirmations",
1090 (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
1091 obj.pushKV("label", label);
1092 UniValue transactions(UniValue::VARR);
1093 if (it != mapTally.end()) {
1094 for (const uint256 &_item : (*it).second.txids) {
1095 transactions.push_back(_item.GetHex());
1096 }
1097 }
1098 obj.pushKV("txids", transactions);
1099 ret.push_back(obj);
1100 }
1101 }
1102
1103 if (by_label) {
1104 for (const auto &entry : label_tally) {
1105 Amount nAmount = entry.second.nAmount;
1106 int nConf = entry.second.nConf;
1108 if (entry.second.fIsWatchonly) {
1109 obj.pushKV("involvesWatchonly", true);
1110 }
1111 obj.pushKV("amount", nAmount);
1112 obj.pushKV("confirmations",
1113 (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
1114 obj.pushKV("label", entry.first);
1115 ret.push_back(obj);
1116 }
1117 }
1118
1119 return ret;
1120}
1121
1123 return RPCHelpMan{
1124 "listreceivedbyaddress",
1125 "List balances by receiving address.\n",
1126 {
1127 {"minconf", RPCArg::Type::NUM, RPCArg::Default{1},
1128 "The minimum number of confirmations before payments are "
1129 "included."},
1130 {"include_empty", RPCArg::Type::BOOL, RPCArg::Default{false},
1131 "Whether to include addresses that haven't received any "
1132 "payments."},
1133 {"include_watchonly", RPCArg::Type::BOOL,
1135 "true for watch-only wallets, otherwise false"},
1136 "Whether to include watch-only addresses (see 'importaddress')."},
1137 {"address_filter", RPCArg::Type::STR, RPCArg::Optional::OMITTED,
1138 "If present, only return information on this address."},
1139 },
1140 RPCResult{
1142 "",
1143 "",
1144 {
1146 "",
1147 "",
1148 {
1149 {RPCResult::Type::BOOL, "involvesWatchonly",
1150 "Only returns true if imported addresses were involved "
1151 "in transaction"},
1152 {RPCResult::Type::STR, "address", "The receiving address"},
1153 {RPCResult::Type::STR_AMOUNT, "amount",
1154 "The total amount in " + Currency::get().ticker +
1155 " received by the address"},
1156 {RPCResult::Type::NUM, "confirmations",
1157 "The number of confirmations of the most recent "
1158 "transaction included"},
1159 {RPCResult::Type::STR, "label",
1160 "The label of the receiving address. The default label "
1161 "is \"\""},
1163 "txids",
1164 "",
1165 {
1166 {RPCResult::Type::STR_HEX, "txid",
1167 "The ids of transactions received with the address"},
1168 }},
1169 }},
1170 }},
1172 HelpExampleCli("listreceivedbyaddress", "") +
1173 HelpExampleCli("listreceivedbyaddress", "6 true") +
1174 HelpExampleRpc("listreceivedbyaddress", "6, true, true") +
1176 "listreceivedbyaddress",
1177 "6, true, true, \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\"")},
1178 [&](const RPCHelpMan &self, const Config &config,
1179 const JSONRPCRequest &request) -> UniValue {
1180 std::shared_ptr<CWallet> const wallet =
1182 if (!wallet) {
1183 return NullUniValue;
1184 }
1185 const CWallet *const pwallet = wallet.get();
1186
1187 // Make sure the results are valid at least up to the most recent
1188 // block the user could have gotten from another RPC command prior
1189 // to now
1190 pwallet->BlockUntilSyncedToCurrentChain();
1191
1192 LOCK(pwallet->cs_wallet);
1193
1194 return ListReceived(config, pwallet, request.params, false);
1195 },
1196 };
1197}
1198
1200 return RPCHelpMan{
1201 "listreceivedbylabel",
1202 "List received transactions by label.\n",
1203 {
1204 {"minconf", RPCArg::Type::NUM, RPCArg::Default{1},
1205 "The minimum number of confirmations before payments are "
1206 "included."},
1207 {"include_empty", RPCArg::Type::BOOL, RPCArg::Default{false},
1208 "Whether to include labels that haven't received any payments."},
1209 {"include_watchonly", RPCArg::Type::BOOL,
1211 "true for watch-only wallets, otherwise false"},
1212 "Whether to include watch-only addresses (see 'importaddress')."},
1213 },
1214 RPCResult{
1216 "",
1217 "",
1218 {
1220 "",
1221 "",
1222 {
1223 {RPCResult::Type::BOOL, "involvesWatchonly",
1224 "Only returns true if imported addresses were involved "
1225 "in transaction"},
1226 {RPCResult::Type::STR_AMOUNT, "amount",
1227 "The total amount received by addresses with this label"},
1228 {RPCResult::Type::NUM, "confirmations",
1229 "The number of confirmations of the most recent "
1230 "transaction included"},
1231 {RPCResult::Type::STR, "label",
1232 "The label of the receiving address. The default label "
1233 "is \"\""},
1234 }},
1235 }},
1236 RPCExamples{HelpExampleCli("listreceivedbylabel", "") +
1237 HelpExampleCli("listreceivedbylabel", "6 true") +
1238 HelpExampleRpc("listreceivedbylabel", "6, true, true")},
1239 [&](const RPCHelpMan &self, const Config &config,
1240 const JSONRPCRequest &request) -> UniValue {
1241 std::shared_ptr<CWallet> const wallet =
1243 if (!wallet) {
1244 return NullUniValue;
1245 }
1246 const CWallet *const pwallet = wallet.get();
1247
1248 // Make sure the results are valid at least up to the most recent
1249 // block the user could have gotten from another RPC command prior
1250 // to now
1251 pwallet->BlockUntilSyncedToCurrentChain();
1252
1253 LOCK(pwallet->cs_wallet);
1254
1255 return ListReceived(config, pwallet, request.params, true);
1256 },
1257 };
1258}
1259
1260static void MaybePushAddress(UniValue &entry, const CTxDestination &dest) {
1261 if (IsValidDestination(dest)) {
1262 entry.pushKV("address", EncodeDestination(dest, GetConfig()));
1263 }
1264}
1265
1278template <class Vec>
1279static void ListTransactions(const CWallet *const pwallet, const CWalletTx &wtx,
1280 int nMinDepth, bool fLong, Vec &ret,
1281 const isminefilter &filter_ismine,
1282 const std::string *filter_label)
1283 EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
1284 Amount nFee;
1285 std::list<COutputEntry> listReceived;
1286 std::list<COutputEntry> listSent;
1287
1288 CachedTxGetAmounts(*pwallet, wtx, listReceived, listSent, nFee,
1289 filter_ismine);
1290
1291 bool involvesWatchonly = CachedTxIsFromMe(*pwallet, wtx, ISMINE_WATCH_ONLY);
1292
1293 // Sent
1294 if (!filter_label) {
1295 for (const COutputEntry &s : listSent) {
1296 UniValue entry(UniValue::VOBJ);
1297 if (involvesWatchonly ||
1298 (pwallet->IsMine(s.destination) & ISMINE_WATCH_ONLY)) {
1299 entry.pushKV("involvesWatchonly", true);
1300 }
1301 MaybePushAddress(entry, s.destination);
1302 entry.pushKV("category", "send");
1303 entry.pushKV("amount", -s.amount);
1304 const auto *address_book_entry =
1305 pwallet->FindAddressBookEntry(s.destination);
1306 if (address_book_entry) {
1307 entry.pushKV("label", address_book_entry->GetLabel());
1308 }
1309 entry.pushKV("vout", s.vout);
1310 entry.pushKV("fee", -1 * nFee);
1311 if (fLong) {
1312 WalletTxToJSON(*pwallet, wtx, entry);
1313 }
1314 entry.pushKV("abandoned", wtx.isAbandoned());
1315 ret.push_back(entry);
1316 }
1317 }
1318
1319 // Received
1320 if (listReceived.size() > 0 &&
1321 pwallet->GetTxDepthInMainChain(wtx) >= nMinDepth) {
1322 for (const COutputEntry &r : listReceived) {
1323 std::string label;
1324 const auto *address_book_entry =
1325 pwallet->FindAddressBookEntry(r.destination);
1326 if (address_book_entry) {
1327 label = address_book_entry->GetLabel();
1328 }
1329 if (filter_label && label != *filter_label) {
1330 continue;
1331 }
1332 UniValue entry(UniValue::VOBJ);
1333 if (involvesWatchonly ||
1334 (pwallet->IsMine(r.destination) & ISMINE_WATCH_ONLY)) {
1335 entry.pushKV("involvesWatchonly", true);
1336 }
1337 MaybePushAddress(entry, r.destination);
1338 if (wtx.IsCoinBase()) {
1339 if (pwallet->GetTxDepthInMainChain(wtx) < 1) {
1340 entry.pushKV("category", "orphan");
1341 } else if (pwallet->IsTxImmatureCoinBase(wtx)) {
1342 entry.pushKV("category", "immature");
1343 } else {
1344 entry.pushKV("category", "generate");
1345 }
1346 } else {
1347 entry.pushKV("category", "receive");
1348 }
1349 entry.pushKV("amount", r.amount);
1350 if (address_book_entry) {
1351 entry.pushKV("label", label);
1352 }
1353 entry.pushKV("vout", r.vout);
1354 if (fLong) {
1355 WalletTxToJSON(*pwallet, wtx, entry);
1356 }
1357 ret.push_back(entry);
1358 }
1359 }
1360}
1361
1362static std::vector<RPCResult> TransactionDescriptionString() {
1363 return {
1364 {RPCResult::Type::NUM, "confirmations",
1365 "The number of confirmations for the transaction. Negative "
1366 "confirmations means the\n"
1367 "transaction conflicted that many blocks ago."},
1368 {RPCResult::Type::BOOL, "generated",
1369 "Only present if transaction only input is a coinbase one."},
1370 {RPCResult::Type::BOOL, "trusted",
1371 "Only present if we consider transaction to be trusted and so safe to "
1372 "spend from."},
1373 {RPCResult::Type::STR_HEX, "blockhash",
1374 "The block hash containing the transaction."},
1375 {RPCResult::Type::NUM, "blockheight",
1376 "The block height containing the transaction."},
1377 {RPCResult::Type::NUM, "blockindex",
1378 "The index of the transaction in the block that includes it."},
1379 {RPCResult::Type::NUM_TIME, "blocktime",
1380 "The block time expressed in " + UNIX_EPOCH_TIME + "."},
1381 {RPCResult::Type::STR_HEX, "txid", "The transaction id."},
1383 "walletconflicts",
1384 "Conflicting transaction ids.",
1385 {
1386 {RPCResult::Type::STR_HEX, "txid", "The transaction id."},
1387 }},
1389 "The transaction time expressed in " + UNIX_EPOCH_TIME + "."},
1390 {RPCResult::Type::NUM_TIME, "timereceived",
1391 "The time received expressed in " + UNIX_EPOCH_TIME + "."},
1392 {RPCResult::Type::STR, "comment",
1393 "If a comment is associated with the transaction, only present if not "
1394 "empty."},
1395 };
1396}
1397
1399 const auto &ticker = Currency::get().ticker;
1400 return RPCHelpMan{
1401 "listtransactions",
1402 "If a label name is provided, this will return only incoming "
1403 "transactions paying to addresses with the specified label.\n"
1404 "\nReturns up to 'count' most recent transactions skipping the first "
1405 "'from' transactions.\n",
1406 {
1408 "If set, should be a valid label name to return only incoming "
1409 "transactions with the specified label, or \"*\" to disable "
1410 "filtering and return all transactions."},
1411 {"count", RPCArg::Type::NUM, RPCArg::Default{10},
1412 "The number of transactions to return"},
1414 "The number of transactions to skip"},
1415 {"include_watchonly", RPCArg::Type::BOOL,
1417 "true for watch-only wallets, otherwise false"},
1418 "Include transactions to watch-only addresses (see "
1419 "'importaddress')"},
1420 },
1421 RPCResult{
1423 "",
1424 "",
1425 {
1426 {RPCResult::Type::OBJ, "", "",
1427 Cat(Cat<std::vector<RPCResult>>(
1428 {
1429 {RPCResult::Type::BOOL, "involvesWatchonly",
1430 "Only returns true if imported addresses were "
1431 "involved in transaction."},
1432 {RPCResult::Type::STR, "address",
1433 "The bitcoin address of the transaction."},
1434 {RPCResult::Type::STR, "category",
1435 "The transaction category.\n"
1436 "\"send\" Transactions sent.\n"
1437 "\"receive\" Non-coinbase "
1438 "transactions received.\n"
1439 "\"generate\" Coinbase transactions "
1440 "received with more than 100 confirmations.\n"
1441 "\"immature\" Coinbase transactions "
1442 "received with 100 or fewer confirmations.\n"
1443 "\"orphan\" Orphaned coinbase "
1444 "transactions received."},
1445 {RPCResult::Type::STR_AMOUNT, "amount",
1446 "The amount in " + ticker +
1447 ". This is negative for the 'send' category, "
1448 "and is positive\n"
1449 "for all other categories"},
1450 {RPCResult::Type::STR, "label",
1451 "A comment for the address/transaction, if any"},
1452 {RPCResult::Type::NUM, "vout", "the vout value"},
1454 "The amount of the fee in " + ticker +
1455 ". This is negative and only available for "
1456 "the\n"
1457 "'send' category of transactions."},
1458 },
1460 {
1461 {RPCResult::Type::BOOL, "abandoned",
1462 "'true' if the transaction has been abandoned "
1463 "(inputs are respendable). Only available for the \n"
1464 "'send' category of transactions."},
1465 })},
1466 }},
1467 RPCExamples{"\nList the most recent 10 transactions in the systems\n" +
1468 HelpExampleCli("listtransactions", "") +
1469 "\nList transactions 100 to 120\n" +
1470 HelpExampleCli("listtransactions", "\"*\" 20 100") +
1471 "\nAs a JSON-RPC call\n" +
1472 HelpExampleRpc("listtransactions", "\"*\", 20, 100")},
1473 [&](const RPCHelpMan &self, const Config &config,
1474 const JSONRPCRequest &request) -> UniValue {
1475 std::shared_ptr<CWallet> const wallet =
1477 if (!wallet) {
1478 return NullUniValue;
1479 }
1480 const CWallet *const pwallet = wallet.get();
1481
1482 // Make sure the results are valid at least up to the most recent
1483 // block the user could have gotten from another RPC command prior
1484 // to now
1485 pwallet->BlockUntilSyncedToCurrentChain();
1486
1487 const std::string *filter_label = nullptr;
1488 if (!request.params[0].isNull() &&
1489 request.params[0].get_str() != "*") {
1490 filter_label = &request.params[0].get_str();
1491 if (filter_label->empty()) {
1492 throw JSONRPCError(
1494 "Label argument must be a valid label name or \"*\".");
1495 }
1496 }
1497 int nCount = 10;
1498 if (!request.params[1].isNull()) {
1499 nCount = request.params[1].getInt<int>();
1500 }
1501
1502 int nFrom = 0;
1503 if (!request.params[2].isNull()) {
1504 nFrom = request.params[2].getInt<int>();
1505 }
1506
1508 if (ParseIncludeWatchonly(request.params[3], *pwallet)) {
1509 filter |= ISMINE_WATCH_ONLY;
1510 }
1511
1512 if (nCount < 0) {
1513 throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
1514 }
1515 if (nFrom < 0) {
1516 throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
1517 }
1518
1519 std::vector<UniValue> ret;
1520 {
1521 LOCK(pwallet->cs_wallet);
1522
1523 const CWallet::TxItems &txOrdered = pwallet->wtxOrdered;
1524
1525 // iterate backwards until we have nCount items to return:
1526 for (CWallet::TxItems::const_reverse_iterator it =
1527 txOrdered.rbegin();
1528 it != txOrdered.rend(); ++it) {
1529 CWalletTx *const pwtx = (*it).second;
1530 ListTransactions(pwallet, *pwtx, 0, true, ret, filter,
1531 filter_label);
1532 if (int(ret.size()) >= (nCount + nFrom)) {
1533 break;
1534 }
1535 }
1536 }
1537
1538 // ret is newest to oldest
1539
1540 if (nFrom > (int)ret.size()) {
1541 nFrom = ret.size();
1542 }
1543 if ((nFrom + nCount) > (int)ret.size()) {
1544 nCount = ret.size() - nFrom;
1545 }
1546
1547 auto txs_rev_it{std::make_move_iterator(ret.rend())};
1548 UniValue result{UniValue::VARR};
1549 // Return oldest to newest
1550 result.push_backV(txs_rev_it - nFrom - nCount, txs_rev_it - nFrom);
1551 return result;
1552 },
1553 };
1554}
1555
1557 const auto &ticker = Currency::get().ticker;
1558 return RPCHelpMan{
1559 "listsinceblock",
1560 "Get all transactions in blocks since block [blockhash], or all "
1561 "transactions if omitted.\n"
1562 "If \"blockhash\" is no longer a part of the main chain, transactions "
1563 "from the fork point onward are included.\n"
1564 "Additionally, if include_removed is set, transactions affecting the "
1565 "wallet which were removed are returned in the \"removed\" array.\n",
1566 {
1568 "If set, the block hash to list transactions since, otherwise "
1569 "list all transactions."},
1570 {"target_confirmations", RPCArg::Type::NUM, RPCArg::Default{1},
1571 "Return the nth block hash from the main chain. e.g. 1 would mean "
1572 "the best block hash. Note: this is not used as a filter, but "
1573 "only affects [lastblock] in the return value"},
1574 {"include_watchonly", RPCArg::Type::BOOL,
1576 "true for watch-only wallets, otherwise false"},
1577 "Include transactions to watch-only addresses (see "
1578 "'importaddress')"},
1579 {"include_removed", RPCArg::Type::BOOL, RPCArg::Default{true},
1580 "Show transactions that were removed due to a reorg in the "
1581 "\"removed\" array\n"
1582 " (not "
1583 "guaranteed to work on pruned nodes)"},
1584 },
1585 RPCResult{
1587 "",
1588 "",
1589 {
1591 "transactions",
1592 "",
1593 {
1594 {RPCResult::Type::OBJ, "", "",
1595 Cat(Cat<std::vector<RPCResult>>(
1596 {
1597 {RPCResult::Type::BOOL, "involvesWatchonly",
1598 "Only returns true if imported addresses "
1599 "were involved in transaction."},
1600 {RPCResult::Type::STR, "address",
1601 "The bitcoin address of the transaction."},
1602 {RPCResult::Type::STR, "category",
1603 "The transaction category.\n"
1604 "\"send\" Transactions "
1605 "sent.\n"
1606 "\"receive\" Non-coinbase "
1607 "transactions received.\n"
1608 "\"generate\" Coinbase "
1609 "transactions received with more than 100 "
1610 "confirmations.\n"
1611 "\"immature\" Coinbase "
1612 "transactions received with 100 or fewer "
1613 "confirmations.\n"
1614 "\"orphan\" Orphaned "
1615 "coinbase transactions received."},
1616 {RPCResult::Type::STR_AMOUNT, "amount",
1617 "The amount in " + ticker +
1618 ". This is negative for the 'send' "
1619 "category, and is positive\n"
1620 "for all other categories"},
1621 {RPCResult::Type::NUM, "vout",
1622 "the vout value"},
1624 "The amount of the fee in " + ticker +
1625 ". This is negative and only available "
1626 "for the\n"
1627 "'send' category of transactions."},
1628 },
1630 {
1631 {RPCResult::Type::BOOL, "abandoned",
1632 "'true' if the transaction has been abandoned "
1633 "(inputs are respendable). Only available for "
1634 "the \n"
1635 "'send' category of transactions."},
1636 {RPCResult::Type::STR, "comment",
1637 "If a comment is associated with the "
1638 "transaction."},
1639 {RPCResult::Type::STR, "label",
1640 "A comment for the address/transaction, if any"},
1641 {RPCResult::Type::STR, "to",
1642 "If a comment to is associated with the "
1643 "transaction."},
1644 })},
1645 }},
1647 "removed",
1648 "<structure is the same as \"transactions\" above, only "
1649 "present if include_removed=true>\n"
1650 "Note: transactions that were re-added in the active chain "
1651 "will appear as-is in this array, and may thus have a "
1652 "positive confirmation count.",
1653 {
1654 {RPCResult::Type::ELISION, "", ""},
1655 }},
1656 {RPCResult::Type::STR_HEX, "lastblock",
1657 "The hash of the block (target_confirmations-1) from the best "
1658 "block on the main chain, or the genesis hash if the "
1659 "referenced block does not exist yet. This is typically used "
1660 "to feed back into listsinceblock the next time you call it. "
1661 "So you would generally use a target_confirmations of say 6, "
1662 "so you will be continually re-notified of transactions until "
1663 "they've reached 6 confirmations plus any new ones"},
1664 }},
1665 RPCExamples{HelpExampleCli("listsinceblock", "") +
1666 HelpExampleCli("listsinceblock",
1667 "\"000000000000000bacf66f7497b7dc45ef753ee9a"
1668 "7d38571037cdb1a57f663ad\" 6") +
1669 HelpExampleRpc("listsinceblock",
1670 "\"000000000000000bacf66f7497b7dc45ef753ee9a"
1671 "7d38571037cdb1a57f663ad\", 6")},
1672 [&](const RPCHelpMan &self, const Config &config,
1673 const JSONRPCRequest &request) -> UniValue {
1674 std::shared_ptr<CWallet> const pwallet =
1676
1677 if (!pwallet) {
1678 return NullUniValue;
1679 }
1680
1681 const CWallet &wallet = *pwallet;
1682 // Make sure the results are valid at least up to the most recent
1683 // block the user could have gotten from another RPC command prior
1684 // to now
1685 wallet.BlockUntilSyncedToCurrentChain();
1686
1687 LOCK(wallet.cs_wallet);
1688
1689 // Height of the specified block or the common ancestor, if the
1690 // block provided was in a deactivated chain.
1691 std::optional<int> height;
1692
1693 // Height of the specified block, even if it's in a deactivated
1694 // chain.
1695 std::optional<int> altheight;
1696 int target_confirms = 1;
1698
1699 BlockHash blockId;
1700 if (!request.params[0].isNull() &&
1701 !request.params[0].get_str().empty()) {
1702 blockId = BlockHash(ParseHashV(request.params[0], "blockhash"));
1703 height = int{};
1704 altheight = int{};
1705 if (!wallet.chain().findCommonAncestor(
1706 blockId, wallet.GetLastBlockHash(),
1707 /* ancestor out */ FoundBlock().height(*height),
1708 /* blockId out */ FoundBlock().height(*altheight))) {
1710 "Block not found");
1711 }
1712 }
1713
1714 if (!request.params[1].isNull()) {
1715 target_confirms = request.params[1].getInt<int>();
1716
1717 if (target_confirms < 1) {
1719 "Invalid parameter");
1720 }
1721 }
1722
1723 if (ParseIncludeWatchonly(request.params[2], wallet)) {
1724 filter |= ISMINE_WATCH_ONLY;
1725 }
1726
1727 bool include_removed =
1728 (request.params[3].isNull() || request.params[3].get_bool());
1729
1730 int depth = height ? wallet.GetLastBlockHeight() + 1 - *height : -1;
1731
1732 UniValue transactions(UniValue::VARR);
1733
1734 for (const std::pair<const TxId, CWalletTx> &pairWtx :
1735 wallet.mapWallet) {
1736 const CWalletTx &tx = pairWtx.second;
1737
1738 if (depth == -1 || wallet.GetTxDepthInMainChain(tx) < depth) {
1739 ListTransactions(&wallet, tx, 0, true, transactions, filter,
1740 nullptr /* filter_label */);
1741 }
1742 }
1743
1744 // when a reorg'd block is requested, we also list any relevant
1745 // transactions in the blocks of the chain that was detached
1746 UniValue removed(UniValue::VARR);
1747 while (include_removed && altheight && *altheight > *height) {
1748 CBlock block;
1749 if (!wallet.chain().findBlock(blockId,
1750 FoundBlock().data(block)) ||
1751 block.IsNull()) {
1753 "Can't read block from disk");
1754 }
1755 for (const CTransactionRef &tx : block.vtx) {
1756 auto it = wallet.mapWallet.find(tx->GetId());
1757 if (it != wallet.mapWallet.end()) {
1758 // We want all transactions regardless of confirmation
1759 // count to appear here, even negative confirmation
1760 // ones, hence the big negative.
1761 ListTransactions(&wallet, it->second, -100000000, true,
1762 removed, filter,
1763 nullptr /* filter_label */);
1764 }
1765 }
1766 blockId = block.hashPrevBlock;
1767 --*altheight;
1768 }
1769
1770 BlockHash lastblock;
1771 target_confirms =
1772 std::min(target_confirms, wallet.GetLastBlockHeight() + 1);
1773 CHECK_NONFATAL(wallet.chain().findAncestorByHeight(
1774 wallet.GetLastBlockHash(),
1775 wallet.GetLastBlockHeight() + 1 - target_confirms,
1776 FoundBlock().hash(lastblock)));
1777
1779 ret.pushKV("transactions", transactions);
1780 if (include_removed) {
1781 ret.pushKV("removed", removed);
1782 }
1783 ret.pushKV("lastblock", lastblock.GetHex());
1784
1785 return ret;
1786 },
1787 };
1788}
1789
1791 const auto &ticker = Currency::get().ticker;
1792 return RPCHelpMan{
1793 "gettransaction",
1794 "Get detailed information about in-wallet transaction <txid>\n",
1795 {
1797 "The transaction id"},
1798 {"include_watchonly", RPCArg::Type::BOOL,
1800 "true for watch-only wallets, otherwise false"},
1801 "Whether to include watch-only addresses in balance calculation "
1802 "and details[]"},
1803 {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false},
1804 "Whether to include a `decoded` field containing the decoded "
1805 "transaction (equivalent to RPC decoderawtransaction)"},
1806 },
1807 RPCResult{
1808 RPCResult::Type::OBJ, "", "",
1809 Cat(Cat<std::vector<RPCResult>>(
1810 {
1811 {RPCResult::Type::STR_AMOUNT, "amount",
1812 "The amount in " + ticker},
1814 "The amount of the fee in " + ticker +
1815 ". This is negative and only available for the\n"
1816 "'send' category of transactions."},
1817 },
1819 {
1821 "details",
1822 "",
1823 {
1825 "",
1826 "",
1827 {
1828 {RPCResult::Type::BOOL, "involvesWatchonly",
1829 "Only returns true if imported addresses were "
1830 "involved in transaction."},
1831 {RPCResult::Type::STR, "address",
1832 "The bitcoin address involved in the "
1833 "transaction."},
1834 {RPCResult::Type::STR, "category",
1835 "The transaction category.\n"
1836 "\"send\" Transactions sent.\n"
1837 "\"receive\" Non-coinbase "
1838 "transactions received.\n"
1839 "\"generate\" Coinbase "
1840 "transactions received with more than 100 "
1841 "confirmations.\n"
1842 "\"immature\" Coinbase "
1843 "transactions received with 100 or fewer "
1844 "confirmations.\n"
1845 "\"orphan\" Orphaned coinbase "
1846 "transactions received."},
1847 {RPCResult::Type::STR_AMOUNT, "amount",
1848 "The amount in " + ticker},
1849 {RPCResult::Type::STR, "label",
1850 "A comment for the address/transaction, if any"},
1851 {RPCResult::Type::NUM, "vout", "the vout value"},
1853 "The amount of the fee in " + ticker +
1854 ". This is negative and only available for "
1855 "the \n"
1856 "'send' category of transactions."},
1857 {RPCResult::Type::BOOL, "abandoned",
1858 "'true' if the transaction has been abandoned "
1859 "(inputs are respendable). Only available for "
1860 "the \n"
1861 "'send' category of transactions."},
1862 }},
1863 }},
1865 "Raw data for transaction"},
1867 "decoded",
1868 "Optional, the decoded transaction (only present when "
1869 "`verbose` is passed)",
1870 {
1872 "Equivalent to the RPC decoderawtransaction method, "
1873 "or the RPC getrawtransaction method when `verbose` "
1874 "is passed."},
1875 }},
1876 })},
1877 RPCExamples{HelpExampleCli("gettransaction",
1878 "\"1075db55d416d3ca199f55b6084e2115b9345e16c"
1879 "5cf302fc80e9d5fbf5d48d\"") +
1880 HelpExampleCli("gettransaction",
1881 "\"1075db55d416d3ca199f55b6084e2115b9345e16c"
1882 "5cf302fc80e9d5fbf5d48d\" true") +
1883 HelpExampleCli("gettransaction",
1884 "\"1075db55d416d3ca199f55b6084e2115b9345e16c"
1885 "5cf302fc80e9d5fbf5d48d\" false true") +
1886 HelpExampleRpc("gettransaction",
1887 "\"1075db55d416d3ca199f55b6084e2115b9345e16c"
1888 "5cf302fc80e9d5fbf5d48d\"")},
1889 [&](const RPCHelpMan &self, const Config &config,
1890 const JSONRPCRequest &request) -> UniValue {
1891 std::shared_ptr<CWallet> const wallet =
1893 if (!wallet) {
1894 return NullUniValue;
1895 }
1896 const CWallet *const pwallet = wallet.get();
1897
1898 // Make sure the results are valid at least up to the most recent
1899 // block the user could have gotten from another RPC command prior
1900 // to now
1901 pwallet->BlockUntilSyncedToCurrentChain();
1902
1903 LOCK(pwallet->cs_wallet);
1904
1905 TxId txid(ParseHashV(request.params[0], "txid"));
1906
1908 if (ParseIncludeWatchonly(request.params[1], *pwallet)) {
1909 filter |= ISMINE_WATCH_ONLY;
1910 }
1911
1912 bool verbose = request.params[2].isNull()
1913 ? false
1914 : request.params[2].get_bool();
1915
1916 UniValue entry(UniValue::VOBJ);
1917 auto it = pwallet->mapWallet.find(txid);
1918 if (it == pwallet->mapWallet.end()) {
1920 "Invalid or non-wallet transaction id");
1921 }
1922 const CWalletTx &wtx = it->second;
1923
1924 Amount nCredit = CachedTxGetCredit(*pwallet, wtx, filter);
1925 Amount nDebit = CachedTxGetDebit(*pwallet, wtx, filter);
1926 Amount nNet = nCredit - nDebit;
1927 Amount nFee = (CachedTxIsFromMe(*pwallet, wtx, filter)
1928 ? wtx.tx->GetValueOut() - nDebit
1929 : Amount::zero());
1930
1931 entry.pushKV("amount", nNet - nFee);
1932 if (CachedTxIsFromMe(*pwallet, wtx, filter)) {
1933 entry.pushKV("fee", nFee);
1934 }
1935
1936 WalletTxToJSON(*pwallet, wtx, entry);
1937
1938 UniValue details(UniValue::VARR);
1939 ListTransactions(pwallet, wtx, 0, false, details, filter,
1940 nullptr /* filter_label */);
1941 entry.pushKV("details", details);
1942
1943 std::string strHex = EncodeHexTx(*wtx.tx);
1944 entry.pushKV("hex", strHex);
1945
1946 if (verbose) {
1947 UniValue decoded(UniValue::VOBJ);
1948 TxToUniv(*wtx.tx, BlockHash(), decoded, false);
1949 entry.pushKV("decoded", decoded);
1950 }
1951
1952 return entry;
1953 },
1954 };
1955}
1956
1958 return RPCHelpMan{
1959 "abandontransaction",
1960 "Mark in-wallet transaction <txid> as abandoned\n"
1961 "This will mark this transaction and all its in-wallet descendants as "
1962 "abandoned which will allow\n"
1963 "for their inputs to be respent. It can be used to replace \"stuck\" "
1964 "or evicted transactions.\n"
1965 "It only works on transactions which are not included in a block and "
1966 "are not currently in the mempool.\n"
1967 "It has no effect on transactions which are already abandoned.\n",
1968 {
1970 "The transaction id"},
1971 },
1973 RPCExamples{HelpExampleCli("abandontransaction",
1974 "\"1075db55d416d3ca199f55b6084e2115b9345e16c"
1975 "5cf302fc80e9d5fbf5d48d\"") +
1976 HelpExampleRpc("abandontransaction",
1977 "\"1075db55d416d3ca199f55b6084e2115b9345e16c"
1978 "5cf302fc80e9d5fbf5d48d\"")},
1979 [&](const RPCHelpMan &self, const Config &config,
1980 const JSONRPCRequest &request) -> UniValue {
1981 std::shared_ptr<CWallet> const wallet =
1983 if (!wallet) {
1984 return NullUniValue;
1985 }
1986 CWallet *const pwallet = wallet.get();
1987
1988 // Make sure the results are valid at least up to the most recent
1989 // block the user could have gotten from another RPC command prior
1990 // to now
1991 pwallet->BlockUntilSyncedToCurrentChain();
1992
1993 LOCK(pwallet->cs_wallet);
1994
1995 TxId txid(ParseHashV(request.params[0], "txid"));
1996
1997 if (!pwallet->mapWallet.count(txid)) {
1999 "Invalid or non-wallet transaction id");
2000 }
2001
2002 if (!pwallet->AbandonTransaction(txid)) {
2004 "Transaction not eligible for abandonment");
2005 }
2006
2007 return NullUniValue;
2008 },
2009 };
2010}
2011
2013 return RPCHelpMan{
2014 "keypoolrefill",
2015 "Fills the keypool." + HELP_REQUIRING_PASSPHRASE,
2016 {
2017 {"newsize", RPCArg::Type::NUM, RPCArg::Default{100},
2018 "The new keypool size"},
2019 },
2021 RPCExamples{HelpExampleCli("keypoolrefill", "") +
2022 HelpExampleRpc("keypoolrefill", "")},
2023 [&](const RPCHelpMan &self, const Config &config,
2024 const JSONRPCRequest &request) -> UniValue {
2025 std::shared_ptr<CWallet> const wallet =
2027 if (!wallet) {
2028 return NullUniValue;
2029 }
2030 CWallet *const pwallet = wallet.get();
2031
2032 if (pwallet->IsLegacy() &&
2034 throw JSONRPCError(
2036 "Error: Private keys are disabled for this wallet");
2037 }
2038
2039 LOCK(pwallet->cs_wallet);
2040
2041 // 0 is interpreted by TopUpKeyPool() as the default keypool size
2042 // given by -keypool
2043 unsigned int kpSize = 0;
2044 if (!request.params[0].isNull()) {
2045 if (request.params[0].getInt<int>() < 0) {
2046 throw JSONRPCError(
2048 "Invalid parameter, expected valid size.");
2049 }
2050 kpSize = (unsigned int)request.params[0].getInt<int>();
2051 }
2052
2053 EnsureWalletIsUnlocked(pwallet);
2054 pwallet->TopUpKeyPool(kpSize);
2055
2056 if (pwallet->GetKeyPoolSize() < kpSize) {
2058 "Error refreshing keypool.");
2059 }
2060
2061 return NullUniValue;
2062 },
2063 };
2064}
2065
2067 return RPCHelpMan{
2068 "lockunspent",
2069 "Updates list of temporarily unspendable outputs.\n"
2070 "Temporarily lock (unlock=false) or unlock (unlock=true) specified "
2071 "transaction outputs.\n"
2072 "If no transaction outputs are specified when unlocking then all "
2073 "current locked transaction outputs are unlocked.\n"
2074 "A locked transaction output will not be chosen by automatic coin "
2075 "selection, when spending bitcoins.\n"
2076 "Manually selected coins are automatically unlocked.\n"
2077 "Locks are stored in memory only. Nodes start with zero locked "
2078 "outputs, and the locked output list\n"
2079 "is always cleared (by virtue of process exit) when a node stops or "
2080 "fails.\n"
2081 "Also see the listunspent call\n",
2082 {
2084 "Whether to unlock (true) or lock (false) the specified "
2085 "transactions"},
2086 {
2087 "transactions",
2090 "The transaction outputs and within each, txid (string) vout "
2091 "(numeric).",
2092 {
2093 {
2094 "",
2097 "",
2098 {
2099 {"txid", RPCArg::Type::STR_HEX,
2100 RPCArg::Optional::NO, "The transaction id"},
2102 "The output number"},
2103 },
2104 },
2105 },
2106 },
2107 },
2109 "Whether the command was successful or not"},
2111 "\nList the unspent transactions\n" +
2112 HelpExampleCli("listunspent", "") +
2113 "\nLock an unspent transaction\n" +
2114 HelpExampleCli("lockunspent", "false "
2115 "\"[{\\\"txid\\\":"
2116 "\\\"a08e6907dbbd3d809776dbfc5d82e371"
2117 "b764ed838b5655e72f463568df1aadf0\\\""
2118 ",\\\"vout\\\":1}]\"") +
2119 "\nList the locked transactions\n" +
2120 HelpExampleCli("listlockunspent", "") +
2121 "\nUnlock the transaction again\n" +
2122 HelpExampleCli("lockunspent", "true "
2123 "\"[{\\\"txid\\\":"
2124 "\\\"a08e6907dbbd3d809776dbfc5d82e371"
2125 "b764ed838b5655e72f463568df1aadf0\\\""
2126 ",\\\"vout\\\":1}]\"") +
2127 "\nAs a JSON-RPC call\n" +
2128 HelpExampleRpc("lockunspent", "false, "
2129 "\"[{\\\"txid\\\":"
2130 "\\\"a08e6907dbbd3d809776dbfc5d82e371"
2131 "b764ed838b5655e72f463568df1aadf0\\\""
2132 ",\\\"vout\\\":1}]\"")},
2133 [&](const RPCHelpMan &self, const Config &config,
2134 const JSONRPCRequest &request) -> UniValue {
2135 std::shared_ptr<CWallet> const wallet =
2137 if (!wallet) {
2138 return NullUniValue;
2139 }
2140 CWallet *const pwallet = wallet.get();
2141
2142 // Make sure the results are valid at least up to the most recent
2143 // block the user could have gotten from another RPC command prior
2144 // to now
2145 pwallet->BlockUntilSyncedToCurrentChain();
2146
2147 LOCK(pwallet->cs_wallet);
2148
2149 bool fUnlock = request.params[0].get_bool();
2150
2151 if (request.params[1].isNull()) {
2152 if (fUnlock) {
2153 pwallet->UnlockAllCoins();
2154 }
2155 return true;
2156 }
2157
2158 const UniValue &output_params = request.params[1].get_array();
2159
2160 // Create and validate the COutPoints first.
2161
2162 std::vector<COutPoint> outputs;
2163 outputs.reserve(output_params.size());
2164
2165 for (size_t idx = 0; idx < output_params.size(); idx++) {
2166 const UniValue &o = output_params[idx].get_obj();
2167
2168 RPCTypeCheckObj(o, {
2169 {"txid", UniValueType(UniValue::VSTR)},
2170 {"vout", UniValueType(UniValue::VNUM)},
2171 });
2172
2173 const int nOutput = o.find_value("vout").getInt<int>();
2174 if (nOutput < 0) {
2175 throw JSONRPCError(
2177 "Invalid parameter, vout cannot be negative");
2178 }
2179
2180 const TxId txid(ParseHashO(o, "txid"));
2181 const auto it = pwallet->mapWallet.find(txid);
2182 if (it == pwallet->mapWallet.end()) {
2183 throw JSONRPCError(
2185 "Invalid parameter, unknown transaction");
2186 }
2187
2188 const COutPoint output(txid, nOutput);
2189 const CWalletTx &trans = it->second;
2190 if (output.GetN() >= trans.tx->vout.size()) {
2191 throw JSONRPCError(
2193 "Invalid parameter, vout index out of bounds");
2194 }
2195
2196 if (pwallet->IsSpent(output)) {
2197 throw JSONRPCError(
2199 "Invalid parameter, expected unspent output");
2200 }
2201
2202 const bool is_locked = pwallet->IsLockedCoin(output);
2203 if (fUnlock && !is_locked) {
2204 throw JSONRPCError(
2206 "Invalid parameter, expected locked output");
2207 }
2208
2209 if (!fUnlock && is_locked) {
2210 throw JSONRPCError(
2212 "Invalid parameter, output already locked");
2213 }
2214
2215 outputs.push_back(output);
2216 }
2217
2218 // Atomically set (un)locked status for the outputs.
2219 for (const COutPoint &output : outputs) {
2220 if (fUnlock) {
2221 pwallet->UnlockCoin(output);
2222 } else {
2223 pwallet->LockCoin(output);
2224 }
2225 }
2226
2227 return true;
2228 },
2229 };
2230}
2231
2233 return RPCHelpMan{
2234 "listlockunspent",
2235 "Returns list of temporarily unspendable outputs.\n"
2236 "See the lockunspent call to lock and unlock transactions for "
2237 "spending.\n",
2238 {},
2240 "",
2241 "",
2242 {
2244 "",
2245 "",
2246 {
2247 {RPCResult::Type::STR_HEX, "txid",
2248 "The transaction id locked"},
2249 {RPCResult::Type::NUM, "vout", "The vout value"},
2250 }},
2251 }},
2253 "\nList the unspent transactions\n" +
2254 HelpExampleCli("listunspent", "") +
2255 "\nLock an unspent transaction\n" +
2256 HelpExampleCli("lockunspent", "false "
2257 "\"[{\\\"txid\\\":"
2258 "\\\"a08e6907dbbd3d809776dbfc5d82e371"
2259 "b764ed838b5655e72f463568df1aadf0\\\""
2260 ",\\\"vout\\\":1}]\"") +
2261 "\nList the locked transactions\n" +
2262 HelpExampleCli("listlockunspent", "") +
2263 "\nUnlock the transaction again\n" +
2264 HelpExampleCli("lockunspent", "true "
2265 "\"[{\\\"txid\\\":"
2266 "\\\"a08e6907dbbd3d809776dbfc5d82e371"
2267 "b764ed838b5655e72f463568df1aadf0\\\""
2268 ",\\\"vout\\\":1}]\"") +
2269 "\nAs a JSON-RPC call\n" + HelpExampleRpc("listlockunspent", "")},
2270 [&](const RPCHelpMan &self, const Config &config,
2271 const JSONRPCRequest &request) -> UniValue {
2272 std::shared_ptr<CWallet> const wallet =
2274 if (!wallet) {
2275 return NullUniValue;
2276 }
2277 const CWallet *const pwallet = wallet.get();
2278
2279 LOCK(pwallet->cs_wallet);
2280
2281 std::vector<COutPoint> vOutpts;
2282 pwallet->ListLockedCoins(vOutpts);
2283
2285
2286 for (const COutPoint &output : vOutpts) {
2288
2289 o.pushKV("txid", output.GetTxId().GetHex());
2290 o.pushKV("vout", int(output.GetN()));
2291 ret.push_back(o);
2292 }
2293
2294 return ret;
2295 },
2296 };
2297}
2298
2300 return RPCHelpMan{
2301 "settxfee",
2302 "Set the transaction fee per kB for this wallet. Overrides the "
2303 "global -paytxfee command line parameter.\n"
2304 "Can be deactivated by passing 0 as the fee. In that case automatic "
2305 "fee selection will be used by default.\n",
2306 {
2308 "The transaction fee in " + Currency::get().ticker + "/kB"},
2309 },
2310 RPCResult{RPCResult::Type::BOOL, "", "Returns true if successful"},
2311 RPCExamples{HelpExampleCli("settxfee", "0.00001") +
2312 HelpExampleRpc("settxfee", "0.00001")},
2313 [&](const RPCHelpMan &self, const Config &config,
2314 const JSONRPCRequest &request) -> UniValue {
2315 std::shared_ptr<CWallet> const wallet =
2317 if (!wallet) {
2318 return NullUniValue;
2319 }
2320 CWallet *const pwallet = wallet.get();
2321
2322 LOCK(pwallet->cs_wallet);
2323
2324 Amount nAmount = AmountFromValue(request.params[0]);
2325 CFeeRate tx_fee_rate(nAmount, 1000);
2326 CFeeRate max_tx_fee_rate(pwallet->m_default_max_tx_fee, 1000);
2327 if (tx_fee_rate == CFeeRate()) {
2328 // automatic selection
2329 } else if (tx_fee_rate < pwallet->chain().relayMinFee()) {
2330 throw JSONRPCError(
2332 strprintf("txfee cannot be less than min relay tx fee (%s)",
2333 pwallet->chain().relayMinFee().ToString()));
2334 } else if (tx_fee_rate < pwallet->m_min_fee) {
2335 throw JSONRPCError(
2337 strprintf("txfee cannot be less than wallet min fee (%s)",
2338 pwallet->m_min_fee.ToString()));
2339 } else if (tx_fee_rate > max_tx_fee_rate) {
2340 throw JSONRPCError(
2342 strprintf(
2343 "txfee cannot be more than wallet max tx fee (%s)",
2344 max_tx_fee_rate.ToString()));
2345 }
2346
2347 pwallet->m_pay_tx_fee = tx_fee_rate;
2348 return true;
2349 },
2350 };
2351}
2352
2354 return RPCHelpMan{
2355 "getbalances",
2356 "Returns an object with all balances in " + Currency::get().ticker +
2357 ".\n",
2358 {},
2360 "",
2361 "",
2362 {
2364 "mine",
2365 "balances from outputs that the wallet can sign",
2366 {
2367 {RPCResult::Type::STR_AMOUNT, "trusted",
2368 "trusted balance (outputs created by the wallet or "
2369 "confirmed outputs)"},
2370 {RPCResult::Type::STR_AMOUNT, "untrusted_pending",
2371 "untrusted pending balance (outputs created by "
2372 "others that are in the mempool)"},
2373 {RPCResult::Type::STR_AMOUNT, "immature",
2374 "balance from immature coinbase outputs"},
2376 "(only present if avoid_reuse is set) balance from "
2377 "coins sent to addresses that were previously "
2378 "spent from (potentially privacy violating)"},
2379 }},
2381 "watchonly",
2382 "watchonly balances (not present if wallet does not "
2383 "watch anything)",
2384 {
2385 {RPCResult::Type::STR_AMOUNT, "trusted",
2386 "trusted balance (outputs created by the wallet or "
2387 "confirmed outputs)"},
2388 {RPCResult::Type::STR_AMOUNT, "untrusted_pending",
2389 "untrusted pending balance (outputs created by "
2390 "others that are in the mempool)"},
2391 {RPCResult::Type::STR_AMOUNT, "immature",
2392 "balance from immature coinbase outputs"},
2393 }},
2394 }},
2395 RPCExamples{HelpExampleCli("getbalances", "") +
2396 HelpExampleRpc("getbalances", "")},
2397 [&](const RPCHelpMan &self, const Config &config,
2398 const JSONRPCRequest &request) -> UniValue {
2399 std::shared_ptr<CWallet> const rpc_wallet =
2401 if (!rpc_wallet) {
2402 return NullUniValue;
2403 }
2404 CWallet &wallet = *rpc_wallet;
2405
2406 // Make sure the results are valid at least up to the most recent
2407 // block the user could have gotten from another RPC command prior
2408 // to now
2409 wallet.BlockUntilSyncedToCurrentChain();
2410
2411 LOCK(wallet.cs_wallet);
2412
2413 const auto bal = GetBalance(wallet);
2414 UniValue balances{UniValue::VOBJ};
2415 {
2416 UniValue balances_mine{UniValue::VOBJ};
2417 balances_mine.pushKV("trusted", bal.m_mine_trusted);
2418 balances_mine.pushKV("untrusted_pending",
2419 bal.m_mine_untrusted_pending);
2420 balances_mine.pushKV("immature", bal.m_mine_immature);
2421 if (wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
2422 // If the AVOID_REUSE flag is set, bal has been set to just
2423 // the un-reused address balance. Get the total balance, and
2424 // then subtract bal to get the reused address balance.
2425 const auto full_bal = GetBalance(wallet, 0, false);
2426 balances_mine.pushKV("used",
2427 full_bal.m_mine_trusted +
2428 full_bal.m_mine_untrusted_pending -
2429 bal.m_mine_trusted -
2430 bal.m_mine_untrusted_pending);
2431 }
2432 balances.pushKV("mine", balances_mine);
2433 }
2434 auto spk_man = wallet.GetLegacyScriptPubKeyMan();
2435 if (spk_man && spk_man->HaveWatchOnly()) {
2436 UniValue balances_watchonly{UniValue::VOBJ};
2437 balances_watchonly.pushKV("trusted", bal.m_watchonly_trusted);
2438 balances_watchonly.pushKV("untrusted_pending",
2439 bal.m_watchonly_untrusted_pending);
2440 balances_watchonly.pushKV("immature", bal.m_watchonly_immature);
2441 balances.pushKV("watchonly", balances_watchonly);
2442 }
2443 return balances;
2444 },
2445 };
2446}
2447
2449 return RPCHelpMan{
2450 "getwalletinfo",
2451 "Returns an object containing various wallet state info.\n",
2452 {},
2453 RPCResult{
2455 "",
2456 "",
2457 {{
2458 {RPCResult::Type::STR, "walletname", "the wallet name"},
2459 {RPCResult::Type::NUM, "walletversion", "the wallet version"},
2460 {RPCResult::Type::STR_AMOUNT, "balance",
2461 "DEPRECATED. Identical to getbalances().mine.trusted"},
2462 {RPCResult::Type::STR_AMOUNT, "unconfirmed_balance",
2463 "DEPRECATED. Identical to "
2464 "getbalances().mine.untrusted_pending"},
2465 {RPCResult::Type::STR_AMOUNT, "immature_balance",
2466 "DEPRECATED. Identical to getbalances().mine.immature"},
2467 {RPCResult::Type::NUM, "txcount",
2468 "the total number of transactions in the wallet"},
2469 {RPCResult::Type::NUM_TIME, "keypoololdest",
2470 "the " + UNIX_EPOCH_TIME +
2471 " of the oldest pre-generated key in the key pool. "
2472 "Legacy wallets only."},
2473 {RPCResult::Type::NUM, "keypoolsize",
2474 "how many new keys are pre-generated (only counts external "
2475 "keys)"},
2476 {RPCResult::Type::NUM, "keypoolsize_hd_internal",
2477 "how many new keys are pre-generated for internal use (used "
2478 "for change outputs, only appears if the wallet is using "
2479 "this feature, otherwise external keys are used)"},
2480 {RPCResult::Type::NUM_TIME, "unlocked_until",
2481 /* optional */ true,
2482 "the " + UNIX_EPOCH_TIME +
2483 " until which the wallet is unlocked for transfers, or 0 "
2484 "if the wallet is locked (only present for "
2485 "passphrase-encrypted wallets)"},
2486 {RPCResult::Type::STR_AMOUNT, "paytxfee",
2487 "the transaction fee configuration, set in " +
2488 Currency::get().ticker + "/kB"},
2489 {RPCResult::Type::STR_HEX, "hdseedid", /* optional */ true,
2490 "the Hash160 of the HD seed (only present when HD is "
2491 "enabled)"},
2492 {RPCResult::Type::BOOL, "private_keys_enabled",
2493 "false if privatekeys are disabled for this wallet (enforced "
2494 "watch-only wallet)"},
2496 "scanning",
2497 "current scanning details, or false if no scan is in "
2498 "progress",
2499 {
2500 {RPCResult::Type::NUM, "duration",
2501 "elapsed seconds since scan start"},
2502 {RPCResult::Type::NUM, "progress",
2503 "scanning progress percentage [0.0, 1.0]"},
2504 },
2505 /*skip_type_check=*/true},
2506 {RPCResult::Type::BOOL, "avoid_reuse",
2507 "whether this wallet tracks clean/dirty coins in terms of "
2508 "reuse"},
2509 {RPCResult::Type::BOOL, "descriptors",
2510 "whether this wallet uses descriptors for scriptPubKey "
2511 "management"},
2512 }},
2513 },
2514 RPCExamples{HelpExampleCli("getwalletinfo", "") +
2515 HelpExampleRpc("getwalletinfo", "")},
2516 [&](const RPCHelpMan &self, const Config &config,
2517 const JSONRPCRequest &request) -> UniValue {
2518 std::shared_ptr<CWallet> const wallet =
2520 if (!wallet) {
2521 return NullUniValue;
2522 }
2523 const CWallet *const pwallet = wallet.get();
2524
2525 // Make sure the results are valid at least up to the most recent
2526 // block the user could have gotten from another RPC command prior
2527 // to now
2528 pwallet->BlockUntilSyncedToCurrentChain();
2529
2530 LOCK(pwallet->cs_wallet);
2531
2533
2534 size_t kpExternalSize = pwallet->KeypoolCountExternalKeys();
2535 const auto bal = GetBalance(*pwallet);
2536 int64_t kp_oldest = pwallet->GetOldestKeyPoolTime();
2537 obj.pushKV("walletname", pwallet->GetName());
2538 obj.pushKV("walletversion", pwallet->GetVersion());
2539 obj.pushKV("balance", bal.m_mine_trusted);
2540 obj.pushKV("unconfirmed_balance", bal.m_mine_untrusted_pending);
2541 obj.pushKV("immature_balance", bal.m_mine_immature);
2542 obj.pushKV("txcount", (int)pwallet->mapWallet.size());
2543 if (kp_oldest > 0) {
2544 obj.pushKV("keypoololdest", kp_oldest);
2545 }
2546 obj.pushKV("keypoolsize", (int64_t)kpExternalSize);
2547
2548 LegacyScriptPubKeyMan *spk_man =
2549 pwallet->GetLegacyScriptPubKeyMan();
2550 if (spk_man) {
2551 CKeyID seed_id = spk_man->GetHDChain().seed_id;
2552 if (!seed_id.IsNull()) {
2553 obj.pushKV("hdseedid", seed_id.GetHex());
2554 }
2555 }
2556
2557 if (pwallet->CanSupportFeature(FEATURE_HD_SPLIT)) {
2558 obj.pushKV("keypoolsize_hd_internal",
2559 int64_t(pwallet->GetKeyPoolSize() - kpExternalSize));
2560 }
2561 if (pwallet->IsCrypted()) {
2562 obj.pushKV("unlocked_until", pwallet->nRelockTime);
2563 }
2564 obj.pushKV("paytxfee", pwallet->m_pay_tx_fee.GetFeePerK());
2565 obj.pushKV(
2566 "private_keys_enabled",
2568 if (pwallet->IsScanning()) {
2569 UniValue scanning(UniValue::VOBJ);
2570 scanning.pushKV("duration", Ticks<std::chrono::seconds>(
2571 pwallet->ScanningDuration()));
2572 scanning.pushKV("progress", pwallet->ScanningProgress());
2573 obj.pushKV("scanning", scanning);
2574 } else {
2575 obj.pushKV("scanning", false);
2576 }
2577 obj.pushKV("avoid_reuse",
2579 obj.pushKV("descriptors",
2581 return obj;
2582 },
2583 };
2584}
2585
2587 return RPCHelpMan{
2588 "listwalletdir",
2589 "Returns a list of wallets in the wallet directory.\n",
2590 {},
2591 RPCResult{
2593 "",
2594 "",
2595 {
2597 "wallets",
2598 "",
2599 {
2601 "",
2602 "",
2603 {
2604 {RPCResult::Type::STR, "name", "The wallet name"},
2605 }},
2606 }},
2607 }},
2608 RPCExamples{HelpExampleCli("listwalletdir", "") +
2609 HelpExampleRpc("listwalletdir", "")},
2610 [&](const RPCHelpMan &self, const Config &config,
2611 const JSONRPCRequest &request) -> UniValue {
2612 UniValue wallets(UniValue::VARR);
2613 for (const auto &path : ListWalletDir()) {
2615 wallet.pushKV("name", path.u8string());
2616 wallets.push_back(wallet);
2617 }
2618
2619 UniValue result(UniValue::VOBJ);
2620 result.pushKV("wallets", wallets);
2621 return result;
2622 },
2623 };
2624}
2625
2627 return RPCHelpMan{
2628 "listwallets",
2629 "Returns a list of currently loaded wallets.\n"
2630 "For full information on the wallet, use \"getwalletinfo\"\n",
2631 {},
2633 "",
2634 "",
2635 {
2636 {RPCResult::Type::STR, "walletname", "the wallet name"},
2637 }},
2638 RPCExamples{HelpExampleCli("listwallets", "") +
2639 HelpExampleRpc("listwallets", "")},
2640 [&](const RPCHelpMan &self, const Config &config,
2641 const JSONRPCRequest &request) -> UniValue {
2643
2644 WalletContext &context = EnsureWalletContext(request.context);
2645 for (const std::shared_ptr<CWallet> &wallet : GetWallets(context)) {
2646 LOCK(wallet->cs_wallet);
2647 obj.push_back(wallet->GetName());
2648 }
2649
2650 return obj;
2651 },
2652 };
2653}
2654
2656 return RPCHelpMan{
2657 "loadwallet",
2658 "Loads a wallet from a wallet file or directory."
2659 "\nNote that all wallet command-line options used when starting "
2660 "bitcoind will be"
2661 "\napplied to the new wallet (eg -rescan, etc).\n",
2662 {
2664 "The wallet directory or .dat file."},
2665 {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED,
2666 "Save wallet name to persistent settings and load on startup. "
2667 "True to add wallet to startup list, false to remove, null to "
2668 "leave unchanged."},
2669 },
2671 "",
2672 "",
2673 {
2674 {RPCResult::Type::STR, "name",
2675 "The wallet name if loaded successfully."},
2676 {RPCResult::Type::STR, "warning",
2677 "Warning message if wallet was not loaded cleanly."},
2678 }},
2679 RPCExamples{HelpExampleCli("loadwallet", "\"test.dat\"") +
2680 HelpExampleRpc("loadwallet", "\"test.dat\"")},
2681 [&](const RPCHelpMan &self, const Config &config,
2682 const JSONRPCRequest &request) -> UniValue {
2683 WalletContext &context = EnsureWalletContext(request.context);
2684 const std::string name(request.params[0].get_str());
2685
2686 DatabaseOptions options;
2687 DatabaseStatus status;
2688 options.require_existing = true;
2689 bilingual_str error;
2690 std::vector<bilingual_str> warnings;
2691 std::optional<bool> load_on_start =
2692 request.params[1].isNull()
2693 ? std::nullopt
2694 : std::optional<bool>(request.params[1].get_bool());
2695 std::shared_ptr<CWallet> const wallet = LoadWallet(
2696 context, name, load_on_start, options, status, error, warnings);
2697
2698 HandleWalletError(wallet, status, error);
2699
2701 obj.pushKV("name", wallet->GetName());
2702 obj.pushKV("warning", Join(warnings, Untranslated("\n")).original);
2703
2704 return obj;
2705 },
2706 };
2707}
2708
2710 std::string flags = "";
2711 for (auto &it : WALLET_FLAG_MAP) {
2712 if (it.second & MUTABLE_WALLET_FLAGS) {
2713 flags += (flags == "" ? "" : ", ") + it.first;
2714 }
2715 }
2716 return RPCHelpMan{
2717 "setwalletflag",
2718 "Change the state of the given wallet flag for a wallet.\n",
2719 {
2721 "The name of the flag to change. Current available flags: " +
2722 flags},
2723 {"value", RPCArg::Type::BOOL, RPCArg::Default{true},
2724 "The new state."},
2725 },
2727 "",
2728 "",
2729 {
2730 {RPCResult::Type::STR, "flag_name",
2731 "The name of the flag that was modified"},
2732 {RPCResult::Type::BOOL, "flag_state",
2733 "The new state of the flag"},
2734 {RPCResult::Type::STR, "warnings",
2735 "Any warnings associated with the change"},
2736 }},
2737 RPCExamples{HelpExampleCli("setwalletflag", "avoid_reuse") +
2738 HelpExampleRpc("setwalletflag", "\"avoid_reuse\"")},
2739 [&](const RPCHelpMan &self, const Config &config,
2740 const JSONRPCRequest &request) -> UniValue {
2741 std::shared_ptr<CWallet> const wallet =
2743 if (!wallet) {
2744 return NullUniValue;
2745 }
2746 CWallet *const pwallet = wallet.get();
2747
2748 std::string flag_str = request.params[0].get_str();
2749 bool value =
2750 request.params[1].isNull() || request.params[1].get_bool();
2751
2752 if (!WALLET_FLAG_MAP.count(flag_str)) {
2753 throw JSONRPCError(
2755 strprintf("Unknown wallet flag: %s", flag_str));
2756 }
2757
2758 auto flag = WALLET_FLAG_MAP.at(flag_str);
2759
2760 if (!(flag & MUTABLE_WALLET_FLAGS)) {
2761 throw JSONRPCError(
2763 strprintf("Wallet flag is immutable: %s", flag_str));
2764 }
2765
2767
2768 if (pwallet->IsWalletFlagSet(flag) == value) {
2769 throw JSONRPCError(
2771 strprintf("Wallet flag is already set to %s: %s",
2772 value ? "true" : "false", flag_str));
2773 }
2774
2775 res.pushKV("flag_name", flag_str);
2776 res.pushKV("flag_state", value);
2777
2778 if (value) {
2779 pwallet->SetWalletFlag(flag);
2780 } else {
2781 pwallet->UnsetWalletFlag(flag);
2782 }
2783
2784 if (flag && value && WALLET_FLAG_CAVEATS.count(flag)) {
2785 res.pushKV("warnings", WALLET_FLAG_CAVEATS.at(flag));
2786 }
2787
2788 return res;
2789 },
2790 };
2791}
2792
2794 return RPCHelpMan{
2795 "createwallet",
2796 "Creates and loads a new wallet.\n",
2797 {
2798 {"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO,
2799 "The name for the new wallet. If this is a path, the wallet will "
2800 "be created at the path location."},
2801 {"disable_private_keys", RPCArg::Type::BOOL, RPCArg::Default{false},
2802 "Disable the possibility of private keys (only watchonlys are "
2803 "possible in this mode)."},
2804 {"blank", RPCArg::Type::BOOL, RPCArg::Default{false},
2805 "Create a blank wallet. A blank wallet has no keys or HD seed. "
2806 "One can be set using sethdseed."},
2808 "Encrypt the wallet with this passphrase."},
2809 {"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{false},
2810 "Keep track of coin reuse, and treat dirty and clean coins "
2811 "differently with privacy considerations in mind."},
2812 {"descriptors", RPCArg::Type::BOOL, RPCArg::Default{false},
2813 "Create a native descriptor wallet. The wallet will use "
2814 "descriptors internally to handle address creation"},
2815 {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED,
2816 "Save wallet name to persistent settings and load on startup. "
2817 "True to add wallet to startup list, false to remove, null to "
2818 "leave unchanged."},
2819 },
2821 "",
2822 "",
2823 {
2824 {RPCResult::Type::STR, "name",
2825 "The wallet name if created successfully. If the wallet "
2826 "was created using a full path, the wallet_name will be "
2827 "the full path."},
2828 {RPCResult::Type::STR, "warning",
2829 "Warning message if wallet was not loaded cleanly."},
2830 }},
2832 HelpExampleCli("createwallet", "\"testwallet\"") +
2833 HelpExampleRpc("createwallet", "\"testwallet\"") +
2834 HelpExampleCliNamed("createwallet", {{"wallet_name", "descriptors"},
2835 {"avoid_reuse", true},
2836 {"descriptors", true},
2837 {"load_on_startup", true}}) +
2838 HelpExampleRpcNamed("createwallet", {{"wallet_name", "descriptors"},
2839 {"avoid_reuse", true},
2840 {"descriptors", true},
2841 {"load_on_startup", true}})},
2842 [&](const RPCHelpMan &self, const Config &config,
2843 const JSONRPCRequest &request) -> UniValue {
2844 WalletContext &context = EnsureWalletContext(request.context);
2845 uint64_t flags = 0;
2846 if (!request.params[1].isNull() && request.params[1].get_bool()) {
2848 }
2849
2850 if (!request.params[2].isNull() && request.params[2].get_bool()) {
2852 }
2853
2854 SecureString passphrase;
2855 passphrase.reserve(100);
2856 std::vector<bilingual_str> warnings;
2857 if (!request.params[3].isNull()) {
2858 passphrase = request.params[3].get_str().c_str();
2859 if (passphrase.empty()) {
2860 // Empty string means unencrypted
2861 warnings.emplace_back(Untranslated(
2862 "Empty string given as passphrase, wallet will "
2863 "not be encrypted."));
2864 }
2865 }
2866
2867 if (!request.params[4].isNull() && request.params[4].get_bool()) {
2869 }
2870 if (!request.params[5].isNull() && request.params[5].get_bool()) {
2872 warnings.emplace_back(Untranslated(
2873 "Wallet is an experimental descriptor wallet"));
2874 }
2875
2876 DatabaseOptions options;
2877 DatabaseStatus status;
2878 options.require_create = true;
2879 options.create_flags = flags;
2880 options.create_passphrase = passphrase;
2881 bilingual_str error;
2882 std::optional<bool> load_on_start =
2883 request.params[6].isNull()
2884 ? std::nullopt
2885 : std::make_optional<bool>(request.params[6].get_bool());
2886 std::shared_ptr<CWallet> wallet =
2887 CreateWallet(context, request.params[0].get_str(),
2888 load_on_start, options, status, error, warnings);
2889 if (!wallet) {
2893 throw JSONRPCError(code, error.original);
2894 }
2895
2897 obj.pushKV("name", wallet->GetName());
2898 obj.pushKV("warning", Join(warnings, Untranslated("\n")).original);
2899
2900 return obj;
2901 },
2902 };
2903}
2904
2906 return RPCHelpMan{
2907 "unloadwallet",
2908 "Unloads the wallet referenced by the request endpoint otherwise "
2909 "unloads the wallet specified in the argument.\n"
2910 "Specifying the wallet name on a wallet endpoint is invalid.",
2911 {
2912 {"wallet_name", RPCArg::Type::STR,
2913 RPCArg::DefaultHint{"the wallet name from the RPC request"},
2914 "The name of the wallet to unload."},
2915 {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED,
2916 "Save wallet name to persistent settings and load on startup. "
2917 "True to add wallet to startup list, false to remove, null to "
2918 "leave unchanged."},
2919 },
2921 "",
2922 "",
2923 {
2924 {RPCResult::Type::STR, "warning",
2925 "Warning message if wallet was not unloaded cleanly."},
2926 }},
2927 RPCExamples{HelpExampleCli("unloadwallet", "wallet_name") +
2928 HelpExampleRpc("unloadwallet", "wallet_name")},
2929 [&](const RPCHelpMan &self, const Config &config,
2930 const JSONRPCRequest &request) -> UniValue {
2931 std::string wallet_name;
2932 if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) {
2933 if (!request.params[0].isNull()) {
2935 "Cannot unload the requested wallet");
2936 }
2937 } else {
2938 wallet_name = request.params[0].get_str();
2939 }
2940
2941 WalletContext &context = EnsureWalletContext(request.context);
2942 std::shared_ptr<CWallet> wallet = GetWallet(context, wallet_name);
2943 if (!wallet) {
2944 throw JSONRPCError(
2946 "Requested wallet does not exist or is not loaded");
2947 }
2948
2949 // Release the "main" shared pointer and prevent further
2950 // notifications. Note that any attempt to load the same wallet
2951 // would fail until the wallet is destroyed (see CheckUniqueFileid).
2952 std::vector<bilingual_str> warnings;
2953 std::optional<bool> load_on_start{self.MaybeArg<bool>(1)};
2954 if (!RemoveWallet(context, wallet, load_on_start, warnings)) {
2956 "Requested wallet already unloaded");
2957 }
2958
2959 UnloadWallet(std::move(wallet));
2960
2961 UniValue result(UniValue::VOBJ);
2962 result.pushKV("warning",
2963 Join(warnings, Untranslated("\n")).original);
2964 return result;
2965 },
2966 };
2967}
2968
2970 const auto &ticker = Currency::get().ticker;
2971 return RPCHelpMan{
2972 "listunspent",
2973 "Returns array of unspent transaction outputs\n"
2974 "with between minconf and maxconf (inclusive) confirmations.\n"
2975 "Optionally filter to only include txouts paid to specified "
2976 "addresses.\n",
2977 {
2978 {"minconf", RPCArg::Type::NUM, RPCArg::Default{1},
2979 "The minimum confirmations to filter"},
2980 {"maxconf", RPCArg::Type::NUM, RPCArg::Default{9999999},
2981 "The maximum confirmations to filter"},
2982 {
2983 "addresses",
2986 "The bitcoin addresses to filter",
2987 {
2989 "bitcoin address"},
2990 },
2991 },
2992 {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{true},
2993 "Include outputs that are not safe to spend\n"
2994 " See description of \"safe\" attribute below."},
2995 {"query_options",
2998 "JSON with query options",
2999 {
3000 {"minimumAmount", RPCArg::Type::AMOUNT,
3002 "Minimum value of each UTXO in " + ticker + ""},
3003 {"maximumAmount", RPCArg::Type::AMOUNT,
3004 RPCArg::DefaultHint{"unlimited"},
3005 "Maximum value of each UTXO in " + ticker + ""},
3006 {"maximumCount", RPCArg::Type::NUM,
3007 RPCArg::DefaultHint{"unlimited"}, "Maximum number of UTXOs"},
3008 {"minimumSumAmount", RPCArg::Type::AMOUNT,
3009 RPCArg::DefaultHint{"unlimited"},
3010 "Minimum sum value of all UTXOs in " + ticker + ""},
3011 },
3012 RPCArgOptions{.oneline_description = "query_options"}},
3013 },
3014 RPCResult{
3016 "",
3017 "",
3018 {
3020 "",
3021 "",
3022 {
3023 {RPCResult::Type::STR_HEX, "txid", "the transaction id"},
3024 {RPCResult::Type::NUM, "vout", "the vout value"},
3025 {RPCResult::Type::STR, "address", "the bitcoin address"},
3026 {RPCResult::Type::STR, "label",
3027 "The associated label, or \"\" for the default label"},
3028 {RPCResult::Type::STR, "scriptPubKey", "the script key"},
3029 {RPCResult::Type::STR_AMOUNT, "amount",
3030 "the transaction output amount in " + ticker},
3031 {RPCResult::Type::NUM, "confirmations",
3032 "The number of confirmations"},
3033 {RPCResult::Type::NUM, "ancestorcount",
3034 /* optional */ true,
3035 "DEPRECATED: The number of in-mempool ancestor "
3036 "transactions, including this one (if transaction is in "
3037 "the mempool). Only displayed if the "
3038 "-deprecatedrpc=mempool_ancestors_descendants option is "
3039 "set"},
3040 {RPCResult::Type::NUM, "ancestorsize", /* optional */ true,
3041 "DEPRECATED: The virtual transaction size of in-mempool "
3042 " ancestors, including this one (if transaction is in "
3043 "the mempool). Only displayed if the "
3044 "-deprecatedrpc=mempool_ancestors_descendants option is "
3045 "set"},
3046 {RPCResult::Type::STR_AMOUNT, "ancestorfees",
3047 /* optional */ true,
3048 "DEPRECATED: The total fees of in-mempool ancestors "
3049 "(including this one) with fee deltas used for mining "
3050 "priority in " +
3051 ticker +
3052 " (if transaction is in the mempool). Only "
3053 "displayed if the "
3054 "-deprecatedrpc=mempool_ancestors_descendants option "
3055 "is "
3056 "set"},
3057 {RPCResult::Type::STR_HEX, "redeemScript",
3058 "The redeemScript if scriptPubKey is P2SH"},
3059 {RPCResult::Type::BOOL, "spendable",
3060 "Whether we have the private keys to spend this output"},
3061 {RPCResult::Type::BOOL, "solvable",
3062 "Whether we know how to spend this output, ignoring the "
3063 "lack of keys"},
3064 {RPCResult::Type::BOOL, "reused",
3065 "(only present if avoid_reuse is set) Whether this "
3066 "output is reused/dirty (sent to an address that was "
3067 "previously spent from)"},
3068 {RPCResult::Type::STR, "desc",
3069 "(only when solvable) A descriptor for spending this "
3070 "output"},
3071 {RPCResult::Type::BOOL, "safe",
3072 "Whether this output is considered safe to spend. "
3073 "Unconfirmed transactions\n"
3074 "from outside keys are considered unsafe\n"
3075 "and are not eligible for spending by fundrawtransaction "
3076 "and sendtoaddress."},
3077 }},
3078 }},
3080 HelpExampleCli("listunspent", "") +
3081 HelpExampleCli("listunspent",
3082 "6 9999999 "
3083 "\"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\","
3084 "\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") +
3085 HelpExampleRpc("listunspent",
3086 "6, 9999999 "
3087 "\"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\","
3088 "\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") +
3090 "listunspent",
3091 "6 9999999 '[]' true '{ \"minimumAmount\": 0.005 }'") +
3093 "listunspent",
3094 "6, 9999999, [] , true, { \"minimumAmount\": 0.005 } ")},
3095 [&](const RPCHelpMan &self, const Config &config,
3096 const JSONRPCRequest &request) -> UniValue {
3097 std::shared_ptr<CWallet> const wallet =
3099 if (!wallet) {
3100 return NullUniValue;
3101 }
3102 const CWallet *const pwallet = wallet.get();
3103
3104 int nMinDepth = 1;
3105 if (!request.params[0].isNull()) {
3106 nMinDepth = request.params[0].getInt<int>();
3107 }
3108
3109 int nMaxDepth = 9999999;
3110 if (!request.params[1].isNull()) {
3111 nMaxDepth = request.params[1].getInt<int>();
3112 }
3113
3114 std::set<CTxDestination> destinations;
3115 if (!request.params[2].isNull()) {
3116 UniValue inputs = request.params[2].get_array();
3117 for (size_t idx = 0; idx < inputs.size(); idx++) {
3118 const UniValue &input = inputs[idx];
3120 input.get_str(), wallet->GetChainParams());
3121 if (!IsValidDestination(dest)) {
3122 throw JSONRPCError(
3124 std::string("Invalid Bitcoin address: ") +
3125 input.get_str());
3126 }
3127 if (!destinations.insert(dest).second) {
3128 throw JSONRPCError(
3130 std::string(
3131 "Invalid parameter, duplicated address: ") +
3132 input.get_str());
3133 }
3134 }
3135 }
3136
3137 bool include_unsafe = true;
3138 if (!request.params[3].isNull()) {
3139 include_unsafe = request.params[3].get_bool();
3140 }
3141
3142 Amount nMinimumAmount = Amount::zero();
3143 Amount nMaximumAmount = MAX_MONEY;
3144 Amount nMinimumSumAmount = MAX_MONEY;
3145 uint64_t nMaximumCount = 0;
3146
3147 if (!request.params[4].isNull()) {
3148 const UniValue &options = request.params[4].get_obj();
3149
3151 options,
3152 {
3153 {"minimumAmount", UniValueType()},
3154 {"maximumAmount", UniValueType()},
3155 {"minimumSumAmount", UniValueType()},
3156 {"maximumCount", UniValueType(UniValue::VNUM)},
3157 },
3158 true, true);
3159
3160 if (options.exists("minimumAmount")) {
3161 nMinimumAmount = AmountFromValue(options["minimumAmount"]);
3162 }
3163
3164 if (options.exists("maximumAmount")) {
3165 nMaximumAmount = AmountFromValue(options["maximumAmount"]);
3166 }
3167
3168 if (options.exists("minimumSumAmount")) {
3169 nMinimumSumAmount =
3170 AmountFromValue(options["minimumSumAmount"]);
3171 }
3172
3173 if (options.exists("maximumCount")) {
3174 nMaximumCount = options["maximumCount"].getInt<int64_t>();
3175 }
3176 }
3177
3178 // Make sure the results are valid at least up to the most recent
3179 // block the user could have gotten from another RPC command prior
3180 // to now
3181 pwallet->BlockUntilSyncedToCurrentChain();
3182
3183 UniValue results(UniValue::VARR);
3184 std::vector<COutput> vecOutputs;
3185 {
3186 CCoinControl cctl;
3187 cctl.m_avoid_address_reuse = false;
3188 cctl.m_min_depth = nMinDepth;
3189 cctl.m_max_depth = nMaxDepth;
3190 cctl.m_include_unsafe_inputs = include_unsafe;
3191 LOCK(pwallet->cs_wallet);
3192 AvailableCoins(*pwallet, vecOutputs, &cctl, nMinimumAmount,
3193 nMaximumAmount, nMinimumSumAmount,
3194 nMaximumCount);
3195 }
3196
3197 LOCK(pwallet->cs_wallet);
3198
3199 const bool avoid_reuse =
3201
3202 for (const COutput &out : vecOutputs) {
3203 CTxDestination address;
3204 const CScript &scriptPubKey =
3205 out.tx->tx->vout[out.i].scriptPubKey;
3206 bool fValidAddress = ExtractDestination(scriptPubKey, address);
3207 bool reused =
3208 avoid_reuse && pwallet->IsSpentKey(out.tx->GetId(), out.i);
3209
3210 if (destinations.size() &&
3211 (!fValidAddress || !destinations.count(address))) {
3212 continue;
3213 }
3214
3215 UniValue entry(UniValue::VOBJ);
3216 entry.pushKV("txid", out.tx->GetId().GetHex());
3217 entry.pushKV("vout", out.i);
3218
3219 if (fValidAddress) {
3220 entry.pushKV("address", EncodeDestination(address, config));
3221
3222 const auto *address_book_entry =
3223 pwallet->FindAddressBookEntry(address);
3224 if (address_book_entry) {
3225 entry.pushKV("label", address_book_entry->GetLabel());
3226 }
3227
3228 std::unique_ptr<SigningProvider> provider =
3229 pwallet->GetSolvingProvider(scriptPubKey);
3230 if (provider) {
3231 if (scriptPubKey.IsPayToScriptHash()) {
3232 const CScriptID &hash =
3233 CScriptID(std::get<ScriptHash>(address));
3234 CScript redeemScript;
3235 if (provider->GetCScript(hash, redeemScript)) {
3236 entry.pushKV("redeemScript",
3238 }
3239 }
3240 }
3241 }
3242
3243 entry.pushKV("scriptPubKey", HexStr(scriptPubKey));
3244 entry.pushKV("amount", out.tx->tx->vout[out.i].nValue);
3245 entry.pushKV("confirmations", out.nDepth);
3246 entry.pushKV("spendable", out.fSpendable);
3247 entry.pushKV("solvable", out.fSolvable);
3248 if (out.fSolvable) {
3249 std::unique_ptr<SigningProvider> provider =
3250 pwallet->GetSolvingProvider(scriptPubKey);
3251 if (provider) {
3252 auto descriptor =
3253 InferDescriptor(scriptPubKey, *provider);
3254 entry.pushKV("desc", descriptor->ToString());
3255 }
3256 }
3257 if (avoid_reuse) {
3258 entry.pushKV("reused", reused);
3259 }
3260 entry.pushKV("safe", out.fSafe);
3261 results.push_back(entry);
3262 }
3263
3264 return results;
3265 },
3266 };
3267}
3268
3270 Amount &fee_out, int &change_position,
3271 const UniValue &options, CCoinControl &coinControl) {
3272 // Make sure the results are valid at least up to the most recent block
3273 // the user could have gotten from another RPC command prior to now
3274 pwallet->BlockUntilSyncedToCurrentChain();
3275
3276 change_position = -1;
3277 bool lockUnspents = false;
3278 UniValue subtractFeeFromOutputs;
3279 std::set<int> setSubtractFeeFromOutputs;
3280
3281 if (!options.isNull()) {
3282 if (options.type() == UniValue::VBOOL) {
3283 // backward compatibility bool only fallback
3284 coinControl.fAllowWatchOnly = options.get_bool();
3285 } else {
3287 options,
3288 {
3289 {"add_inputs", UniValueType(UniValue::VBOOL)},
3290 {"include_unsafe", UniValueType(UniValue::VBOOL)},
3291 {"add_to_wallet", UniValueType(UniValue::VBOOL)},
3292 {"changeAddress", UniValueType(UniValue::VSTR)},
3293 {"change_address", UniValueType(UniValue::VSTR)},
3294 {"changePosition", UniValueType(UniValue::VNUM)},
3295 {"change_position", UniValueType(UniValue::VNUM)},
3296 {"includeWatching", UniValueType(UniValue::VBOOL)},
3297 {"include_watching", UniValueType(UniValue::VBOOL)},
3298 {"inputs", UniValueType(UniValue::VARR)},
3299 {"lockUnspents", UniValueType(UniValue::VBOOL)},
3300 {"lock_unspents", UniValueType(UniValue::VBOOL)},
3301 {"locktime", UniValueType(UniValue::VNUM)},
3302 // will be checked below
3303 {"feeRate", UniValueType()},
3304 {"fee_rate", UniValueType()},
3305 {"psbt", UniValueType(UniValue::VBOOL)},
3306 {"subtractFeeFromOutputs", UniValueType(UniValue::VARR)},
3307 {"subtract_fee_from_outputs", UniValueType(UniValue::VARR)},
3308 },
3309 true, true);
3310
3311 if (options.exists("add_inputs")) {
3312 coinControl.m_add_inputs = options["add_inputs"].get_bool();
3313 }
3314
3315 if (options.exists("changeAddress") ||
3316 options.exists("change_address")) {
3317 const std::string change_address_str =
3318 (options.exists("change_address")
3319 ? options["change_address"]
3320 : options["changeAddress"])
3321 .get_str();
3323 change_address_str, pwallet->GetChainParams());
3324
3325 if (!IsValidDestination(dest)) {
3326 throw JSONRPCError(
3328 "Change address must be a valid bitcoin address");
3329 }
3330
3331 coinControl.destChange = dest;
3332 }
3333
3334 if (options.exists("changePosition") ||
3335 options.exists("change_position")) {
3336 change_position = (options.exists("change_position")
3337 ? options["change_position"]
3338 : options["changePosition"])
3339 .getInt<int>();
3340 }
3341
3342 const UniValue include_watching_option =
3343 options.exists("include_watching") ? options["include_watching"]
3344 : options["includeWatching"];
3345 coinControl.fAllowWatchOnly =
3346 ParseIncludeWatchonly(include_watching_option, *pwallet);
3347
3348 if (options.exists("lockUnspents") ||
3349 options.exists("lock_unspents")) {
3350 lockUnspents =
3351 (options.exists("lock_unspents") ? options["lock_unspents"]
3352 : options["lockUnspents"])
3353 .get_bool();
3354 }
3355
3356 if (options.exists("include_unsafe")) {
3357 coinControl.m_include_unsafe_inputs =
3358 options["include_unsafe"].get_bool();
3359 }
3360
3361 if (options.exists("feeRate") || options.exists("fee_rate")) {
3362 coinControl.m_feerate = CFeeRate(AmountFromValue(
3363 options.exists("fee_rate") ? options["fee_rate"]
3364 : options["feeRate"]));
3365 coinControl.fOverrideFeeRate = true;
3366 }
3367
3368 if (options.exists("subtractFeeFromOutputs") ||
3369 options.exists("subtract_fee_from_outputs")) {
3370 subtractFeeFromOutputs =
3371 (options.exists("subtract_fee_from_outputs")
3372 ? options["subtract_fee_from_outputs"]
3373 : options["subtractFeeFromOutputs"])
3374 .get_array();
3375 }
3376 }
3377 } else {
3378 // if options is null and not a bool
3379 coinControl.fAllowWatchOnly =
3381 }
3382
3383 if (tx.vout.size() == 0) {
3385 "TX must have at least one output");
3386 }
3387
3388 if (change_position != -1 &&
3389 (change_position < 0 ||
3390 (unsigned int)change_position > tx.vout.size())) {
3392 "changePosition out of bounds");
3393 }
3394
3395 for (size_t idx = 0; idx < subtractFeeFromOutputs.size(); idx++) {
3396 int pos = subtractFeeFromOutputs[idx].getInt<int>();
3397 if (setSubtractFeeFromOutputs.count(pos)) {
3398 throw JSONRPCError(
3400 strprintf("Invalid parameter, duplicated position: %d", pos));
3401 }
3402 if (pos < 0) {
3403 throw JSONRPCError(
3405 strprintf("Invalid parameter, negative position: %d", pos));
3406 }
3407 if (pos >= int(tx.vout.size())) {
3408 throw JSONRPCError(
3410 strprintf("Invalid parameter, position too large: %d", pos));
3411 }
3412 setSubtractFeeFromOutputs.insert(pos);
3413 }
3414
3415 bilingual_str error;
3416
3417 if (!FundTransaction(*pwallet, tx, fee_out, change_position, error,
3418 lockUnspents, setSubtractFeeFromOutputs,
3419 coinControl)) {
3421 }
3422}
3423
3425 const auto &ticker = Currency::get().ticker;
3426 return RPCHelpMan{
3427 "fundrawtransaction",
3428 "If the transaction has no inputs, they will be automatically selected "
3429 "to meet its out value.\n"
3430 "It will add at most one change output to the outputs.\n"
3431 "No existing outputs will be modified unless "
3432 "\"subtractFeeFromOutputs\" is specified.\n"
3433 "Note that inputs which were signed may need to be resigned after "
3434 "completion since in/outputs have been added.\n"
3435 "The inputs added will not be signed, use signrawtransactionwithkey or "
3436 "signrawtransactionwithwallet for that.\n"
3437 "Note that all existing inputs must have their previous output "
3438 "transaction be in the wallet.\n"
3439 "Note that all inputs selected must be of standard form and P2SH "
3440 "scripts must be\n"
3441 "in the wallet using importaddress or addmultisigaddress (to calculate "
3442 "fees).\n"
3443 "You can see whether this is the case by checking the \"solvable\" "
3444 "field in the listunspent output.\n"
3445 "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently "
3446 "supported for watch-only\n",
3447 {
3449 "The hex string of the raw transaction"},
3450 {"options",
3453 "For backward compatibility: passing in a true instead of an "
3454 "object will result in {\"includeWatching\":true}",
3455 {
3456 {"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{true},
3457 "For a transaction with existing inputs, automatically "
3458 "include more if they are not enough."},
3459 {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false},
3460 "Include inputs that are not safe to spend (unconfirmed "
3461 "transactions from outside keys).\n"
3462 "Warning: the resulting transaction may become invalid if "
3463 "one of the unsafe inputs disappears.\n"
3464 "If that happens, you will need to fund the transaction with "
3465 "different inputs and republish it."},
3466 {"changeAddress", RPCArg::Type::STR,
3467 RPCArg::DefaultHint{"pool address"},
3468 "The bitcoin address to receive the change"},
3469 {"changePosition", RPCArg::Type::NUM,
3470 RPCArg::DefaultHint{"random"},
3471 "The index of the change output"},
3472 {"includeWatching", RPCArg::Type::BOOL,
3474 "true for watch-only wallets, otherwise false"},
3475 "Also select inputs which are watch only.\n"
3476 "Only solvable inputs can be used. Watch-only destinations "
3477 "are solvable if the public key and/or output script was "
3478 "imported,\n"
3479 "e.g. with 'importpubkey' or 'importmulti' with the "
3480 "'pubkeys' or 'desc' field."},
3481 {"lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false},
3482 "Lock selected unspent outputs"},
3483 {"feeRate", RPCArg::Type::AMOUNT,
3485 "not set: makes wallet determine the fee"},
3486 "Set a specific fee rate in " + ticker + "/kB",
3488 {
3489 "subtractFeeFromOutputs",
3492 "The integers.\n"
3493 " The fee will be equally "
3494 "deducted from the amount of each specified output.\n"
3495 " Those recipients will "
3496 "receive less bitcoins than you enter in their "
3497 "corresponding amount field.\n"
3498 " If no outputs are "
3499 "specified here, the sender pays the fee.",
3500 {
3501 {"vout_index", RPCArg::Type::NUM,
3503 "The zero-based output index, before a change output "
3504 "is added."},
3505 },
3506 },
3507 },
3509 .oneline_description = "options"}},
3510 },
3512 "",
3513 "",
3514 {
3516 "The resulting raw transaction (hex-encoded string)"},
3518 "Fee in " + ticker + " the resulting transaction pays"},
3519 {RPCResult::Type::NUM, "changepos",
3520 "The position of the added change output, or -1"},
3521 }},
3523 "\nCreate a transaction with no inputs\n" +
3524 HelpExampleCli("createrawtransaction",
3525 "\"[]\" \"{\\\"myaddress\\\":10000}\"") +
3526 "\nAdd sufficient unsigned inputs to meet the output value\n" +
3527 HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
3528 "\nSign the transaction\n" +
3529 HelpExampleCli("signrawtransactionwithwallet",
3530 "\"fundedtransactionhex\"") +
3531 "\nSend the transaction\n" +
3532 HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")},
3533 [&](const RPCHelpMan &self, const Config &config,
3534 const JSONRPCRequest &request) -> UniValue {
3535 std::shared_ptr<CWallet> const wallet =
3537 if (!wallet) {
3538 return NullUniValue;
3539 }
3540 CWallet *const pwallet = wallet.get();
3541
3542 // parse hex string from parameter
3544 if (!DecodeHexTx(tx, request.params[0].get_str())) {
3546 "TX decode failed");
3547 }
3548
3549 Amount fee;
3550 int change_position;
3551 CCoinControl coin_control;
3552 // Automatically select (additional) coins. Can be overridden by
3553 // options.add_inputs.
3554 coin_control.m_add_inputs = true;
3555 FundTransaction(pwallet, tx, fee, change_position,
3556 request.params[1], coin_control);
3557
3558 UniValue result(UniValue::VOBJ);
3559 result.pushKV("hex", EncodeHexTx(CTransaction(tx)));
3560 result.pushKV("fee", fee);
3561 result.pushKV("changepos", change_position);
3562
3563 return result;
3564 },
3565 };
3566}
3567
3569 return RPCHelpMan{
3570 "signrawtransactionwithwallet",
3571 "Sign inputs for raw transaction (serialized, hex-encoded).\n"
3572 "The second optional argument (may be null) is an array of previous "
3573 "transaction outputs that\n"
3574 "this transaction depends on but may not yet be in the block chain.\n" +
3576 {
3578 "The transaction hex string"},
3579 {
3580 "prevtxs",
3583 "The previous dependent transaction outputs",
3584 {
3585 {
3586 "",
3589 "",
3590 {
3591 {"txid", RPCArg::Type::STR_HEX,
3592 RPCArg::Optional::NO, "The transaction id"},
3594 "The output number"},
3595 {"scriptPubKey", RPCArg::Type::STR_HEX,
3596 RPCArg::Optional::NO, "script key"},
3597 {"redeemScript", RPCArg::Type::STR_HEX,
3598 RPCArg::Optional::OMITTED, "(required for P2SH)"},
3599 {"amount", RPCArg::Type::AMOUNT,
3600 RPCArg::Optional::NO, "The amount spent"},
3601 },
3602 },
3603 },
3604 },
3605 {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"ALL|FORKID"},
3606 "The signature hash type. Must be one of\n"
3607 " \"ALL|FORKID\"\n"
3608 " \"NONE|FORKID\"\n"
3609 " \"SINGLE|FORKID\"\n"
3610 " \"ALL|FORKID|ANYONECANPAY\"\n"
3611 " \"NONE|FORKID|ANYONECANPAY\"\n"
3612 " \"SINGLE|FORKID|ANYONECANPAY\""},
3613 },
3614 RPCResult{
3616 "",
3617 "",
3618 {
3620 "The hex-encoded raw transaction with signature(s)"},
3621 {RPCResult::Type::BOOL, "complete",
3622 "If the transaction has a complete set of signatures"},
3624 "errors",
3625 /* optional */ true,
3626 "Script verification errors (if there are any)",
3627 {
3629 "",
3630 "",
3631 {
3632 {RPCResult::Type::STR_HEX, "txid",
3633 "The hash of the referenced, previous transaction"},
3634 {RPCResult::Type::NUM, "vout",
3635 "The index of the output to spent and used as "
3636 "input"},
3637 {RPCResult::Type::STR_HEX, "scriptSig",
3638 "The hex-encoded signature script"},
3639 {RPCResult::Type::NUM, "sequence",
3640 "Script sequence number"},
3641 {RPCResult::Type::STR, "error",
3642 "Verification or signing error related to the "
3643 "input"},
3644 }},
3645 }},
3646 }},
3648 HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
3649 HelpExampleRpc("signrawtransactionwithwallet", "\"myhex\"")},
3650 [&](const RPCHelpMan &self, const Config &config,
3651 const JSONRPCRequest &request) -> UniValue {
3652 std::shared_ptr<CWallet> const wallet =
3654 if (!wallet) {
3655 return NullUniValue;
3656 }
3657 const CWallet *const pwallet = wallet.get();
3658
3660 if (!DecodeHexTx(mtx, request.params[0].get_str())) {
3662 "TX decode failed");
3663 }
3664
3665 // Sign the transaction
3666 LOCK(pwallet->cs_wallet);
3667 EnsureWalletIsUnlocked(pwallet);
3668
3669 // Fetch previous transactions (inputs):
3670 std::map<COutPoint, Coin> coins;
3671 for (const CTxIn &txin : mtx.vin) {
3672 // Create empty map entry keyed by prevout.
3673 coins[txin.prevout];
3674 }
3675 pwallet->chain().findCoins(coins);
3676
3677 // Parse the prevtxs array
3678 ParsePrevouts(request.params[1], nullptr, coins);
3679
3680 SigHashType nHashType = ParseSighashString(request.params[2]);
3681 if (!nHashType.hasForkId()) {
3683 "Signature must use SIGHASH_FORKID");
3684 }
3685
3686 // Script verification errors
3687 std::map<int, std::string> input_errors;
3688
3689 bool complete =
3690 pwallet->SignTransaction(mtx, coins, nHashType, input_errors);
3691 UniValue result(UniValue::VOBJ);
3692 SignTransactionResultToJSON(mtx, complete, coins, input_errors,
3693 result);
3694 return result;
3695 },
3696 };
3697}
3698
3700 return RPCHelpMan{
3701 "rescanblockchain",
3702 "Rescan the local blockchain for wallet related transactions.\n"
3703 "Note: Use \"getwalletinfo\" to query the scanning progress.\n",
3704 {
3705 {"start_height", RPCArg::Type::NUM, RPCArg::Default{0},
3706 "block height where the rescan should start"},
3708 "the last block height that should be scanned"},
3709 },
3710 RPCResult{
3712 "",
3713 "",
3714 {
3715 {RPCResult::Type::NUM, "start_height",
3716 "The block height where the rescan started (the requested "
3717 "height or 0)"},
3718 {RPCResult::Type::NUM, "stop_height",
3719 "The height of the last rescanned block. May be null in rare "
3720 "cases if there was a reorg and the call didn't scan any "
3721 "blocks because they were already scanned in the background."},
3722 }},
3723 RPCExamples{HelpExampleCli("rescanblockchain", "100000 120000") +
3724 HelpExampleRpc("rescanblockchain", "100000, 120000")},
3725 [&](const RPCHelpMan &self, const Config &config,
3726 const JSONRPCRequest &request) -> UniValue {
3727 std::shared_ptr<CWallet> const wallet =
3729 if (!wallet) {
3730 return NullUniValue;
3731 }
3732 CWallet *const pwallet = wallet.get();
3733
3734 WalletRescanReserver reserver(*pwallet);
3735 if (!reserver.reserve()) {
3737 "Wallet is currently rescanning. Abort "
3738 "existing rescan or wait.");
3739 }
3740
3741 int start_height = 0;
3742 std::optional<int> stop_height;
3743 BlockHash start_block;
3744 {
3745 LOCK(pwallet->cs_wallet);
3746 int tip_height = pwallet->GetLastBlockHeight();
3747
3748 if (!request.params[0].isNull()) {
3749 start_height = request.params[0].getInt<int>();
3750 if (start_height < 0 || start_height > tip_height) {
3752 "Invalid start_height");
3753 }
3754 }
3755
3756 if (!request.params[1].isNull()) {
3757 stop_height = request.params[1].getInt<int>();
3758 if (*stop_height < 0 || *stop_height > tip_height) {
3760 "Invalid stop_height");
3761 } else if (*stop_height < start_height) {
3762 throw JSONRPCError(
3764 "stop_height must be greater than start_height");
3765 }
3766 }
3767
3768 // We can't rescan unavailable blocks, stop and throw an error
3769 if (!pwallet->chain().hasBlocks(pwallet->GetLastBlockHash(),
3770 start_height, stop_height)) {
3771 if (pwallet->chain().havePruned() &&
3772 pwallet->chain().getPruneHeight() >= start_height) {
3774 "Can't rescan beyond pruned data. "
3775 "Use RPC call getblockchaininfo to "
3776 "determine your pruned height.");
3777 }
3778 if (pwallet->chain().hasAssumedValidChain()) {
3779 throw JSONRPCError(
3781 "Failed to rescan unavailable blocks likely due to "
3782 "an in-progress assumeutxo background sync. Check "
3783 "logs or getchainstates RPC for assumeutxo "
3784 "background sync progress and try again later.");
3785 }
3786 throw JSONRPCError(
3788 "Failed to rescan unavailable blocks, potentially "
3789 "caused by data corruption. If the issue persists you "
3790 "may want to reindex (see -reindex option).");
3791 }
3792
3794 pwallet->GetLastBlockHash(), start_height,
3795 FoundBlock().hash(start_block)));
3796 }
3797
3799 start_block, start_height, stop_height, reserver,
3800 true /* fUpdate */);
3801 switch (result.status) {
3803 break;
3805 throw JSONRPCError(
3807 "Rescan failed. Potentially corrupted data files.");
3809 throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted.");
3810 // no default case, so the compiler can warn about missing
3811 // cases
3812 }
3814 response.pushKV("start_height", start_height);
3815 response.pushKV("stop_height", result.last_scanned_height
3816 ? *result.last_scanned_height
3817 : UniValue());
3818 return response;
3819 },
3820 };
3821}
3822
3824public:
3826
3827 void ProcessSubScript(const CScript &subscript, UniValue &obj) const {
3828 // Always present: script type and redeemscript
3829 std::vector<std::vector<uint8_t>> solutions_data;
3830 TxoutType which_type = Solver(subscript, solutions_data);
3831 obj.pushKV("script", GetTxnOutputType(which_type));
3832 obj.pushKV("hex", HexStr(subscript));
3833
3834 CTxDestination embedded;
3835 if (ExtractDestination(subscript, embedded)) {
3836 // Only when the script corresponds to an address.
3837 UniValue subobj(UniValue::VOBJ);
3838 UniValue detail = DescribeAddress(embedded);
3839 subobj.pushKVs(detail);
3840 UniValue wallet_detail = std::visit(*this, embedded);
3841 subobj.pushKVs(wallet_detail);
3842 subobj.pushKV("address", EncodeDestination(embedded, GetConfig()));
3843 subobj.pushKV("scriptPubKey", HexStr(subscript));
3844 // Always report the pubkey at the top level, so that
3845 // `getnewaddress()['pubkey']` always works.
3846 if (subobj.exists("pubkey")) {
3847 obj.pushKV("pubkey", subobj["pubkey"]);
3848 }
3849 obj.pushKV("embedded", std::move(subobj));
3850 } else if (which_type == TxoutType::MULTISIG) {
3851 // Also report some information on multisig scripts (which do not
3852 // have a corresponding address).
3853 // TODO: abstract out the common functionality between this logic
3854 // and ExtractDestinations.
3855 obj.pushKV("sigsrequired", solutions_data[0][0]);
3856 UniValue pubkeys(UniValue::VARR);
3857 for (size_t i = 1; i < solutions_data.size() - 1; ++i) {
3858 CPubKey key(solutions_data[i].begin(), solutions_data[i].end());
3859 pubkeys.push_back(HexStr(key));
3860 }
3861 obj.pushKV("pubkeys", std::move(pubkeys));
3862 }
3863 }
3864
3866 : provider(_provider) {}
3867
3869 return UniValue(UniValue::VOBJ);
3870 }
3871
3872 UniValue operator()(const PKHash &pkhash) const {
3873 CKeyID keyID(ToKeyID(pkhash));
3875 CPubKey vchPubKey;
3876 if (provider && provider->GetPubKey(keyID, vchPubKey)) {
3877 obj.pushKV("pubkey", HexStr(vchPubKey));
3878 obj.pushKV("iscompressed", vchPubKey.IsCompressed());
3879 }
3880 return obj;
3881 }
3882
3883 UniValue operator()(const ScriptHash &scripthash) const {
3884 CScriptID scriptID(scripthash);
3886 CScript subscript;
3887 if (provider && provider->GetCScript(scriptID, subscript)) {
3888 ProcessSubScript(subscript, obj);
3889 }
3890 return obj;
3891 }
3892};
3893
3894static UniValue DescribeWalletAddress(const CWallet *const pwallet,
3895 const CTxDestination &dest) {
3897 UniValue detail = DescribeAddress(dest);
3898 CScript script = GetScriptForDestination(dest);
3899 std::unique_ptr<SigningProvider> provider = nullptr;
3900 if (pwallet) {
3901 provider = pwallet->GetSolvingProvider(script);
3902 }
3903 ret.pushKVs(detail);
3904 ret.pushKVs(std::visit(DescribeWalletAddressVisitor(provider.get()), dest));
3905 return ret;
3906}
3907
3910 const bool verbose) {
3912 if (verbose) {
3913 ret.pushKV("name", data.GetLabel());
3914 }
3915 ret.pushKV("purpose", data.purpose);
3916 return ret;
3917}
3918
3920 return RPCHelpMan{
3921 "getaddressinfo",
3922 "Return information about the given bitcoin address.\n"
3923 "Some of the information will only be present if the address is in the "
3924 "active wallet.\n",
3925 {
3927 "The bitcoin address for which to get information."},
3928 },
3929 RPCResult{
3931 "",
3932 "",
3933 {
3934 {RPCResult::Type::STR, "address",
3935 "The bitcoin address validated."},
3936 {RPCResult::Type::STR_HEX, "scriptPubKey",
3937 "The hex-encoded scriptPubKey generated by the address."},
3938 {RPCResult::Type::BOOL, "ismine", "If the address is yours."},
3939 {RPCResult::Type::BOOL, "iswatchonly",
3940 "If the address is watchonly."},
3941 {RPCResult::Type::BOOL, "solvable",
3942 "If we know how to spend coins sent to this address, ignoring "
3943 "the possible lack of private keys."},
3944 {RPCResult::Type::STR, "desc", /* optional */ true,
3945 "A descriptor for spending coins sent to this address (only "
3946 "when solvable)."},
3947 {RPCResult::Type::BOOL, "isscript", "If the key is a script."},
3948 {RPCResult::Type::BOOL, "ischange",
3949 "If the address was used for change output."},
3950 {RPCResult::Type::STR, "script", /* optional */ true,
3951 "The output script type. Only if isscript is true and the "
3952 "redeemscript is known. Possible\n"
3953 " "
3954 "types: nonstandard, pubkey, pubkeyhash, scripthash, "
3955 "multisig, nulldata."},
3956 {RPCResult::Type::STR_HEX, "hex", /* optional */ true,
3957 "The redeemscript for the p2sh address."},
3959 "pubkeys",
3960 /* optional */ true,
3961 "Array of pubkeys associated with the known redeemscript "
3962 "(only if script is multisig).",
3963 {
3964 {RPCResult::Type::STR, "pubkey", ""},
3965 }},
3966 {RPCResult::Type::NUM, "sigsrequired", /* optional */ true,
3967 "The number of signatures required to spend multisig output "
3968 "(only if script is multisig)."},
3969 {RPCResult::Type::STR_HEX, "pubkey", /* optional */ true,
3970 "The hex value of the raw public key for single-key addresses "
3971 "(possibly embedded in P2SH)."},
3973 "embedded",
3974 /* optional */ true,
3975 "Information about the address embedded in P2SH, if "
3976 "relevant and known.",
3977 {
3979 "Includes all getaddressinfo output fields for the "
3980 "embedded address excluding metadata (timestamp, "
3981 "hdkeypath, hdseedid)\n"
3982 "and relation to the wallet (ismine, iswatchonly)."},
3983 }},
3984 {RPCResult::Type::BOOL, "iscompressed", /* optional */ true,
3985 "If the pubkey is compressed."},
3986 {RPCResult::Type::NUM_TIME, "timestamp", /* optional */ true,
3987 "The creation time of the key, if available, expressed in " +
3988 UNIX_EPOCH_TIME + "."},
3989 {RPCResult::Type::STR, "hdkeypath", /* optional */ true,
3990 "The HD keypath, if the key is HD and available."},
3991 {RPCResult::Type::STR_HEX, "hdseedid", /* optional */ true,
3992 "The Hash160 of the HD seed."},
3993 {RPCResult::Type::STR_HEX, "hdmasterfingerprint",
3994 /* optional */ true, "The fingerprint of the master key."},
3996 "labels",
3997 "Array of labels associated with the address. Currently "
3998 "limited to one label but returned\n"
3999 "as an array to keep the API stable if multiple labels are "
4000 "enabled in the future.",
4001 {
4002 {RPCResult::Type::STR, "label name",
4003 "Label name (defaults to \"\")."},
4004 }},
4005 }},
4006 RPCExamples{HelpExampleCli("getaddressinfo", EXAMPLE_ADDRESS) +
4007 HelpExampleRpc("getaddressinfo", EXAMPLE_ADDRESS)},
4008 [&](const RPCHelpMan &self, const Config &config,
4009 const JSONRPCRequest &request) -> UniValue {
4010 std::shared_ptr<CWallet> const wallet =
4012 if (!wallet) {
4013 return NullUniValue;
4014 }
4015 const CWallet *const pwallet = wallet.get();
4016
4017 LOCK(pwallet->cs_wallet);
4018
4020 CTxDestination dest = DecodeDestination(request.params[0].get_str(),
4021 wallet->GetChainParams());
4022 // Make sure the destination is valid
4023 if (!IsValidDestination(dest)) {
4025 "Invalid address");
4026 }
4027
4028 std::string currentAddress = EncodeDestination(dest, config);
4029 ret.pushKV("address", currentAddress);
4030
4031 CScript scriptPubKey = GetScriptForDestination(dest);
4032 ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
4033
4034 std::unique_ptr<SigningProvider> provider =
4035 pwallet->GetSolvingProvider(scriptPubKey);
4036
4037 isminetype mine = pwallet->IsMine(dest);
4038 ret.pushKV("ismine", bool(mine & ISMINE_SPENDABLE));
4039
4040 bool solvable = provider && IsSolvable(*provider, scriptPubKey);
4041 ret.pushKV("solvable", solvable);
4042
4043 if (solvable) {
4044 ret.pushKV(
4045 "desc",
4046 InferDescriptor(scriptPubKey, *provider)->ToString());
4047 }
4048
4049 ret.pushKV("iswatchonly", bool(mine & ISMINE_WATCH_ONLY));
4050
4051 UniValue detail = DescribeWalletAddress(pwallet, dest);
4052 ret.pushKVs(detail);
4053
4054 ret.pushKV("ischange", ScriptIsChange(*pwallet, scriptPubKey));
4055
4056 ScriptPubKeyMan *spk_man =
4057 pwallet->GetScriptPubKeyMan(scriptPubKey);
4058 if (spk_man) {
4059 if (const std::unique_ptr<CKeyMetadata> meta =
4060 spk_man->GetMetadata(dest)) {
4061 ret.pushKV("timestamp", meta->nCreateTime);
4062 if (meta->has_key_origin) {
4063 ret.pushKV("hdkeypath",
4064 WriteHDKeypath(meta->key_origin.path));
4065 ret.pushKV("hdseedid", meta->hd_seed_id.GetHex());
4066 ret.pushKV("hdmasterfingerprint",
4067 HexStr(meta->key_origin.fingerprint));
4068 }
4069 }
4070 }
4071
4072 // Return a `labels` array containing the label associated with the
4073 // address, equivalent to the `label` field above. Currently only
4074 // one label can be associated with an address, but we return an
4075 // array so the API remains stable if we allow multiple labels to be
4076 // associated with an address in the future.
4077 UniValue labels(UniValue::VARR);
4078 const auto *address_book_entry =
4079 pwallet->FindAddressBookEntry(dest);
4080 if (address_book_entry) {
4081 labels.push_back(address_book_entry->GetLabel());
4082 }
4083 ret.pushKV("labels", std::move(labels));
4084
4085 return ret;
4086 },
4087 };
4088}
4089
4091 return RPCHelpMan{
4092 "getaddressesbylabel",
4093 "Returns the list of addresses assigned the specified label.\n",
4094 {
4095 {"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The label."},
4096 },
4098 "",
4099 "json object with addresses as keys",
4100 {
4102 "address",
4103 "Information about address",
4104 {
4105 {RPCResult::Type::STR, "purpose",
4106 "Purpose of address (\"send\" for sending address, "
4107 "\"receive\" for receiving address)"},
4108 }},
4109 }},
4110 RPCExamples{HelpExampleCli("getaddressesbylabel", "\"tabby\"") +
4111 HelpExampleRpc("getaddressesbylabel", "\"tabby\"")},
4112 [&](const RPCHelpMan &self, const Config &config,
4113 const JSONRPCRequest &request) -> UniValue {
4114 std::shared_ptr<CWallet> const wallet =
4116 if (!wallet) {
4117 return NullUniValue;
4118 }
4119 const CWallet *const pwallet = wallet.get();
4120
4121 LOCK(pwallet->cs_wallet);
4122
4123 std::string label = LabelFromValue(request.params[0]);
4124
4125 // Find all addresses that have the given label
4127 std::set<std::string> addresses;
4128 for (const std::pair<const CTxDestination, CAddressBookData> &item :
4129 pwallet->m_address_book) {
4130 if (item.second.IsChange()) {
4131 continue;
4132 }
4133 if (item.second.GetLabel() == label) {
4134 std::string address = EncodeDestination(item.first, config);
4135 // CWallet::m_address_book is not expected to contain
4136 // duplicate address strings, but build a separate set as a
4137 // precaution just in case it does.
4138 CHECK_NONFATAL(addresses.emplace(address).second);
4139 // UniValue::pushKV checks if the key exists in O(N)
4140 // and since duplicate addresses are unexpected (checked
4141 // with std::set in O(log(N))), UniValue::pushKVEnd is used
4142 // instead, which currently is O(1).
4143 ret.pushKVEnd(address,
4144 AddressBookDataToJSON(item.second, false));
4145 }
4146 }
4147
4148 if (ret.empty()) {
4149 throw JSONRPCError(
4151 std::string("No addresses with label " + label));
4152 }
4153
4154 return ret;
4155 },
4156 };
4157}
4158
4160 return RPCHelpMan{
4161 "listlabels",
4162 "Returns the list of all labels, or labels that are assigned to "
4163 "addresses with a specific purpose.\n",
4164 {
4166 "Address purpose to list labels for ('send','receive'). An empty "
4167 "string is the same as not providing this argument."},
4168 },
4170 "",
4171 "",
4172 {
4173 {RPCResult::Type::STR, "label", "Label name"},
4174 }},
4175 RPCExamples{"\nList all labels\n" + HelpExampleCli("listlabels", "") +
4176 "\nList labels that have receiving addresses\n" +
4177 HelpExampleCli("listlabels", "receive") +
4178 "\nList labels that have sending addresses\n" +
4179 HelpExampleCli("listlabels", "send") +
4180 "\nAs a JSON-RPC call\n" +
4181 HelpExampleRpc("listlabels", "receive")},
4182 [&](const RPCHelpMan &self, const Config &config,
4183 const JSONRPCRequest &request) -> UniValue {
4184 std::shared_ptr<CWallet> const wallet =
4186 if (!wallet) {
4187 return NullUniValue;
4188 }
4189 const CWallet *const pwallet = wallet.get();
4190
4191 LOCK(pwallet->cs_wallet);
4192
4193 std::string purpose;
4194 if (!request.params[0].isNull()) {
4195 purpose = request.params[0].get_str();
4196 }
4197
4198 // Add to a set to sort by label name, then insert into Univalue
4199 // array
4200 std::set<std::string> label_set;
4201 for (const std::pair<const CTxDestination, CAddressBookData>
4202 &entry : pwallet->m_address_book) {
4203 if (entry.second.IsChange()) {
4204 continue;
4205 }
4206 if (purpose.empty() || entry.second.purpose == purpose) {
4207 label_set.insert(entry.second.GetLabel());
4208 }
4209 }
4210
4212 for (const std::string &name : label_set) {
4213 ret.push_back(name);
4214 }
4215
4216 return ret;
4217 },
4218 };
4219}
4220
4222 return RPCHelpMan{
4223 "send",
4224 "EXPERIMENTAL warning: this call may be changed in future releases.\n"
4225 "\nSend a transaction.\n",
4226 {
4227 {"outputs",
4230 "A JSON array with outputs (key-value pairs), where none of "
4231 "the keys are duplicated.\n"
4232 "That is, each address can only appear once and there can only "
4233 "be one 'data' object.\n"
4234 "For convenience, a dictionary, which holds the key-value "
4235 "pairs directly, is also accepted.",
4236 {
4237 {
4238 "",
4241 "",
4242 {
4244 "A key-value pair. The key (string) is the "
4245 "bitcoin address, the value (float or string) is "
4246 "the amount in " +
4247 Currency::get().ticker + ""},
4248 },
4249 },
4250 {
4251 "",
4254 "",
4255 {
4257 "A key-value pair. The key must be \"data\", the "
4258 "value is hex-encoded data"},
4259 },
4260 },
4261 },
4263 {"options",
4266 "",
4267 {
4268 {"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{false},
4269 "If inputs are specified, automatically include more if they "
4270 "are not enough."},
4271 {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false},
4272 "Include inputs that are not safe to spend (unconfirmed "
4273 "transactions from outside keys).\n"
4274 "Warning: the resulting transaction may become invalid if "
4275 "one of the unsafe inputs disappears.\n"
4276 "If that happens, you will need to fund the transaction with "
4277 "different inputs and republish it."},
4278 {"add_to_wallet", RPCArg::Type::BOOL, RPCArg::Default{true},
4279 "When false, returns a serialized transaction which will not "
4280 "be added to the wallet or broadcast"},
4281 {"change_address", RPCArg::Type::STR,
4282 RPCArg::DefaultHint{"pool address"},
4283 "The bitcoin address to receive the change"},
4284 {"change_position", RPCArg::Type::NUM,
4285 RPCArg::DefaultHint{"random"},
4286 "The index of the change output"},
4287 {"fee_rate", RPCArg::Type::AMOUNT,
4289 "not set: makes wallet determine the fee"},
4290 "Set a specific fee rate in " + Currency::get().ticker +
4291 "/kB",
4293 {"include_watching", RPCArg::Type::BOOL,
4295 "true for watch-only wallets, otherwise false"},
4296 "Also select inputs which are watch only.\n"
4297 "Only solvable inputs can be used. Watch-only destinations "
4298 "are solvable if the public key and/or output script was "
4299 "imported,\n"
4300 "e.g. with 'importpubkey' or 'importmulti' with the "
4301 "'pubkeys' or 'desc' field."},
4302 {
4303 "inputs",
4306 "Specify inputs instead of adding them automatically. A "
4307 "JSON array of JSON objects",
4308 {
4310 "The transaction id"},
4312 "The output number"},
4314 "The sequence number"},
4315 },
4316 },
4317 {"locktime", RPCArg::Type::NUM, RPCArg::Default{0},
4318 "Raw locktime. Non-0 value also locktime-activates inputs"},
4319 {"lock_unspents", RPCArg::Type::BOOL, RPCArg::Default{false},
4320 "Lock selected unspent outputs"},
4321 {"psbt", RPCArg::Type::BOOL, RPCArg::DefaultHint{"automatic"},
4322 "Always return a PSBT, implies add_to_wallet=false."},
4323 {
4324 "subtract_fee_from_outputs",
4327 "Outputs to subtract the fee from, specified as integer "
4328 "indices.\n"
4329 "The fee will be equally deducted from the amount of each "
4330 "specified output.\n"
4331 "Those recipients will receive less bitcoins than you "
4332 "enter in their corresponding amount field.\n"
4333 "If no outputs are specified here, the sender pays the "
4334 "fee.",
4335 {
4336 {"vout_index", RPCArg::Type::NUM,
4338 "The zero-based output index, before a change output "
4339 "is added."},
4340 },
4341 },
4342 },
4343 RPCArgOptions{.oneline_description = "options"}},
4344 },
4345 RPCResult{
4347 "",
4348 "",
4349 {{RPCResult::Type::BOOL, "complete",
4350 "If the transaction has a complete set of signatures"},
4351 {RPCResult::Type::STR_HEX, "txid",
4352 "The transaction id for the send. Only 1 transaction is created "
4353 "regardless of the number of addresses."},
4355 "If add_to_wallet is false, the hex-encoded raw transaction with "
4356 "signature(s)"},
4357 {RPCResult::Type::STR, "psbt",
4358 "If more signatures are needed, or if add_to_wallet is false, "
4359 "the base64-encoded (partially) signed transaction"}}},
4361 ""
4362 "\nSend with a fee rate of 10 XEC/kB\n" +
4363 HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS +
4364 "\": 100000}' '{\"fee_rate\": 10}'\n") +
4365 "\nCreate a transaction with a specific input, and return "
4366 "result without adding to wallet or broadcasting to the "
4367 "network\n" +
4368 HelpExampleCli("send",
4369 "'{\"" + EXAMPLE_ADDRESS +
4370 "\": 100000}' '{\"add_to_wallet\": "
4371 "false, \"inputs\": "
4372 "[{\"txid\":"
4373 "\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b565"
4374 "5e72f463568df1aadf0\", \"vout\":1}]}'")},
4375 [&](const RPCHelpMan &self, const Config &config,
4376 const JSONRPCRequest &request) -> UniValue {
4377 std::shared_ptr<CWallet> const wallet =
4379 if (!wallet) {
4380 return NullUniValue;
4381 }
4382 CWallet *const pwallet = wallet.get();
4383
4384 UniValue options = request.params[1];
4385 if (options.exists("changeAddress")) {
4386 throw JSONRPCError(RPC_INVALID_PARAMETER, "Use change_address");
4387 }
4388 if (options.exists("changePosition")) {
4390 "Use change_position");
4391 }
4392 if (options.exists("includeWatching")) {
4394 "Use include_watching");
4395 }
4396 if (options.exists("lockUnspents")) {
4397 throw JSONRPCError(RPC_INVALID_PARAMETER, "Use lock_unspents");
4398 }
4399 if (options.exists("subtractFeeFromOutputs")) {
4401 "Use subtract_fee_from_outputs");
4402 }
4403 if (options.exists("feeRate")) {
4404 throw JSONRPCError(RPC_INVALID_PARAMETER, "Use fee_rate");
4405 }
4406
4407 const bool psbt_opt_in =
4408 options.exists("psbt") && options["psbt"].get_bool();
4409
4410 Amount fee;
4411 int change_position;
4413 wallet->GetChainParams(), options["inputs"], request.params[0],
4414 options["locktime"]);
4415 CCoinControl coin_control;
4416 // Automatically select coins, unless at least one is manually
4417 // selected. Can be overridden by options.add_inputs.
4418 coin_control.m_add_inputs = rawTx.vin.size() == 0;
4419 FundTransaction(pwallet, rawTx, fee, change_position, options,
4420 coin_control);
4421
4422 bool add_to_wallet = true;
4423 if (options.exists("add_to_wallet")) {
4424 add_to_wallet = options["add_to_wallet"].get_bool();
4425 }
4426
4427 // Make a blank psbt
4428 PartiallySignedTransaction psbtx(rawTx);
4429
4430 // Fill transaction with our data and sign
4431 bool complete = true;
4432 const TransactionError err = pwallet->FillPSBT(
4433 psbtx, complete, SigHashType().withForkId(), true, false);
4434 if (err != TransactionError::OK) {
4435 throw JSONRPCTransactionError(err);
4436 }
4437
4439 complete = FinalizeAndExtractPSBT(psbtx, mtx);
4440
4441 UniValue result(UniValue::VOBJ);
4442
4443 if (psbt_opt_in || !complete || !add_to_wallet) {
4444 // Serialize the PSBT
4446 ssTx << psbtx;
4447 result.pushKV("psbt", EncodeBase64(ssTx.str()));
4448 }
4449
4450 if (complete) {
4451 std::string err_string;
4452 std::string hex = EncodeHexTx(CTransaction(mtx));
4453 CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
4454 result.pushKV("txid", tx->GetHash().GetHex());
4455 if (add_to_wallet && !psbt_opt_in) {
4456 pwallet->CommitTransaction(tx, {}, {} /* orderForm */);
4457 } else {
4458 result.pushKV("hex", hex);
4459 }
4460 }
4461 result.pushKV("complete", complete);
4462
4463 return result;
4464 }};
4465}
4466
4468 return RPCHelpMan{
4469 "sethdseed",
4470 "Set or generate a new HD wallet seed. Non-HD wallets will not be "
4471 "upgraded to being a HD wallet. Wallets that are already\n"
4472 "HD will have a new HD seed set so that new keys added to the keypool "
4473 "will be derived from this new seed.\n"
4474 "\nNote that you will need to MAKE A NEW BACKUP of your wallet after "
4475 "setting the HD wallet seed.\n" +
4477 "Note: This command is only compatible with legacy wallets.\n",
4478 {
4479 {"newkeypool", RPCArg::Type::BOOL, RPCArg::Default{true},
4480 "Whether to flush old unused addresses, including change "
4481 "addresses, from the keypool and regenerate it.\n"
4482 " If true, the next address from "
4483 "getnewaddress and change address from getrawchangeaddress will "
4484 "be from this new seed.\n"
4485 " If false, addresses (including "
4486 "change addresses if the wallet already had HD Chain Split "
4487 "enabled) from the existing\n"
4488 " keypool will be used until it has "
4489 "been depleted."},
4490 {"seed", RPCArg::Type::STR, RPCArg::DefaultHint{"random seed"},
4491 "The WIF private key to use as the new HD seed.\n"
4492 " The seed value can be retrieved "
4493 "using the dumpwallet command. It is the private key marked "
4494 "hdseed=1"},
4495 },
4497 RPCExamples{HelpExampleCli("sethdseed", "") +
4498 HelpExampleCli("sethdseed", "false") +
4499 HelpExampleCli("sethdseed", "true \"wifkey\"") +
4500 HelpExampleRpc("sethdseed", "true, \"wifkey\"")},
4501 [&](const RPCHelpMan &self, const Config &config,
4502 const JSONRPCRequest &request) -> UniValue {
4503 std::shared_ptr<CWallet> const wallet =
4505 if (!wallet) {
4506 return NullUniValue;
4507 }
4508 CWallet *const pwallet = wallet.get();
4509
4510 LegacyScriptPubKeyMan &spk_man =
4511 EnsureLegacyScriptPubKeyMan(*pwallet, true);
4512
4515 "Cannot set a HD seed to a wallet with "
4516 "private keys disabled");
4517 }
4518
4519 LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);
4520
4521 // Do not do anything to non-HD wallets
4522 if (!pwallet->CanSupportFeature(FEATURE_HD)) {
4523 throw JSONRPCError(
4525 "Cannot set a HD seed on a non-HD wallet. Use the "
4526 "upgradewallet RPC in order to upgrade a non-HD wallet "
4527 "to HD");
4528 }
4529
4530 EnsureWalletIsUnlocked(pwallet);
4531
4532 bool flush_key_pool = true;
4533 if (!request.params[0].isNull()) {
4534 flush_key_pool = request.params[0].get_bool();
4535 }
4536
4537 CPubKey master_pub_key;
4538 if (request.params[1].isNull()) {
4539 master_pub_key = spk_man.GenerateNewSeed();
4540 } else {
4541 CKey key = DecodeSecret(request.params[1].get_str());
4542 if (!key.IsValid()) {
4544 "Invalid private key");
4545 }
4546
4547 if (HaveKey(spk_man, key)) {
4548 throw JSONRPCError(
4550 "Already have this key (either as an HD seed or "
4551 "as a loose private key)");
4552 }
4553
4554 master_pub_key = spk_man.DeriveNewSeed(key);
4555 }
4556
4557 spk_man.SetHDSeed(master_pub_key);
4558 if (flush_key_pool) {
4559 spk_man.NewKeyPool();
4560 }
4561
4562 return NullUniValue;
4563 },
4564 };
4565}
4566
4568 return RPCHelpMan{
4569 "walletprocesspsbt",
4570 "Update a PSBT with input information from our wallet and then sign "
4571 "inputs that we can sign for." +
4573 {
4575 "The transaction base64 string"},
4576 {"sign", RPCArg::Type::BOOL, RPCArg::Default{true},
4577 "Also sign the transaction when updating"},
4578 {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"ALL|FORKID"},
4579 "The signature hash type to sign with if not specified by "
4580 "the PSBT. Must be one of\n"
4581 " \"ALL|FORKID\"\n"
4582 " \"NONE|FORKID\"\n"
4583 " \"SINGLE|FORKID\"\n"
4584 " \"ALL|FORKID|ANYONECANPAY\"\n"
4585 " \"NONE|FORKID|ANYONECANPAY\"\n"
4586 " \"SINGLE|FORKID|ANYONECANPAY\""},
4587 {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true},
4588 "Includes the BIP 32 derivation paths for public keys if we know "
4589 "them"},
4590 },
4592 "",
4593 "",
4594 {
4595 {RPCResult::Type::STR, "psbt",
4596 "The base64-encoded partially signed transaction"},
4597 {RPCResult::Type::BOOL, "complete",
4598 "If the transaction has a complete set of signatures"},
4599 }},
4600 RPCExamples{HelpExampleCli("walletprocesspsbt", "\"psbt\"")},
4601 [&](const RPCHelpMan &self, const Config &config,
4602 const JSONRPCRequest &request) -> UniValue {
4603 std::shared_ptr<CWallet> const wallet =
4605 if (!wallet) {
4606 return NullUniValue;
4607 }
4608 const CWallet *const pwallet = wallet.get();
4609
4610 // Unserialize the transaction
4612 std::string error;
4613 if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
4615 strprintf("TX decode failed %s", error));
4616 }
4617
4618 // Get the sighash type
4619 SigHashType nHashType = ParseSighashString(request.params[2]);
4620 if (!nHashType.hasForkId()) {
4622 "Signature must use SIGHASH_FORKID");
4623 }
4624
4625 // Fill transaction with our data and also sign
4626 bool sign = request.params[1].isNull()
4627 ? true
4628 : request.params[1].get_bool();
4629 bool bip32derivs = request.params[3].isNull()
4630 ? true
4631 : request.params[3].get_bool();
4632 bool complete = true;
4633 const TransactionError err = pwallet->FillPSBT(
4634 psbtx, complete, nHashType, sign, bip32derivs);
4635 if (err != TransactionError::OK) {
4636 throw JSONRPCTransactionError(err);
4637 }
4638
4639 UniValue result(UniValue::VOBJ);
4641 ssTx << psbtx;
4642 result.pushKV("psbt", EncodeBase64(ssTx.str()));
4643 result.pushKV("complete", complete);
4644
4645 return result;
4646 },
4647 };
4648}
4649
4651 const auto &ticker = Currency::get().ticker;
4652 return RPCHelpMan{
4653 "walletcreatefundedpsbt",
4654 "Creates and funds a transaction in the Partially Signed Transaction "
4655 "format.\n"
4656 "Implements the Creator and Updater roles.\n",
4657 {
4658 {
4659 "inputs",
4662 "Leave empty to add inputs automatically. See add_inputs "
4663 "option.",
4664 {
4665 {
4666 "",
4669 "",
4670 {
4671 {"txid", RPCArg::Type::STR_HEX,
4672 RPCArg::Optional::NO, "The transaction id"},
4674 "The output number"},
4675 {"sequence", RPCArg::Type::NUM,
4677 "depends on the value of the 'locktime' and "
4678 "'options.replaceable' arguments"},
4679 "The sequence number"},
4680 },
4681 },
4682 },
4683 },
4684 {"outputs",
4687 "The outputs (key-value pairs), where none of "
4688 "the keys are duplicated.\n"
4689 "That is, each address can only appear once and there can only "
4690 "be one 'data' object.\n"
4691 "For compatibility reasons, a dictionary, which holds the "
4692 "key-value pairs directly, is also\n"
4693 " accepted as second parameter.",
4694 {
4695 {
4696 "",
4699 "",
4700 {
4702 "A key-value pair. The key (string) is the "
4703 "bitcoin address, the value (float or string) is "
4704 "the amount in " +
4705 ticker + ""},
4706 },
4707 },
4708 {
4709 "",
4712 "",
4713 {
4715 "A key-value pair. The key must be \"data\", the "
4716 "value is hex-encoded data"},
4717 },
4718 },
4719 },
4721 {"locktime", RPCArg::Type::NUM, RPCArg::Default{0},
4722 "Raw locktime. Non-0 value also locktime-activates inputs\n"
4723 " Allows this transaction to be "
4724 "replaced by a transaction with higher fees. If provided, it is "
4725 "an error if explicit sequence numbers are incompatible."},
4726 {"options",
4729 "",
4730 {
4731 {"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{false},
4732 "If inputs are specified, automatically include more if they "
4733 "are not enough."},
4734 {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false},
4735 "Include inputs that are not safe to spend (unconfirmed "
4736 "transactions from outside keys).\n"
4737 "Warning: the resulting transaction may become invalid if "
4738 "one of the unsafe inputs disappears.\n"
4739 "If that happens, you will need to fund the transaction with "
4740 "different inputs and republish it."},
4741 {"changeAddress", RPCArg::Type::STR,
4742 RPCArg::DefaultHint{"pool address"},
4743 "The bitcoin address to receive the change"},
4744 {"changePosition", RPCArg::Type::NUM,
4745 RPCArg::DefaultHint{"random"},
4746 "The index of the change output"},
4747 {"includeWatching", RPCArg::Type::BOOL,
4749 "true for watch-only wallets, otherwise false"},
4750 "Also select inputs which are watch only"},
4751 {"lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false},
4752 "Lock selected unspent outputs"},
4753 {"feeRate", RPCArg::Type::AMOUNT,
4755 "not set: makes wallet determine the fee"},
4756 "Set a specific fee rate in " + ticker + "/kB",
4758 {
4759 "subtractFeeFromOutputs",
4762 "The outputs to subtract the fee from.\n"
4763 " The fee will be equally "
4764 "deducted from the amount of each specified output.\n"
4765 " Those recipients will "
4766 "receive less bitcoins than you enter in their "
4767 "corresponding amount field.\n"
4768 " If no outputs are "
4769 "specified here, the sender pays the fee.",
4770 {
4771 {"vout_index", RPCArg::Type::NUM,
4773 "The zero-based output index, before a change output "
4774 "is added."},
4775 },
4776 },
4777 },
4778 RPCArgOptions{.oneline_description = "options"}},
4779 {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true},
4780 "Includes the BIP 32 derivation paths for public keys if we know "
4781 "them"},
4782 },
4784 "",
4785 "",
4786 {
4787 {RPCResult::Type::STR, "psbt",
4788 "The resulting raw transaction (base64-encoded string)"},
4790 "Fee in " + ticker + " the resulting transaction pays"},
4791 {RPCResult::Type::NUM, "changepos",
4792 "The position of the added change output, or -1"},
4793 }},
4795 "\nCreate a transaction with no inputs\n" +
4796 HelpExampleCli("walletcreatefundedpsbt",
4797 "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" "
4798 "\"[{\\\"data\\\":\\\"00010203\\\"}]\"")},
4799 [&](const RPCHelpMan &self, const Config &config,
4800 const JSONRPCRequest &request) -> UniValue {
4801 std::shared_ptr<CWallet> const wallet =
4803 if (!wallet) {
4804 return NullUniValue;
4805 }
4806 CWallet *const pwallet = wallet.get();
4807
4808 Amount fee;
4809 int change_position;
4811 wallet->GetChainParams(), request.params[0], request.params[1],
4812 request.params[2]);
4813 CCoinControl coin_control;
4814 // Automatically select coins, unless at least one is manually
4815 // selected. Can be overridden by options.add_inputs.
4816 coin_control.m_add_inputs = rawTx.vin.size() == 0;
4817 FundTransaction(pwallet, rawTx, fee, change_position,
4818 request.params[3], coin_control);
4819
4820 // Make a blank psbt
4821 PartiallySignedTransaction psbtx(rawTx);
4822
4823 // Fill transaction with out data but don't sign
4824 bool bip32derivs = request.params[4].isNull()
4825 ? true
4826 : request.params[4].get_bool();
4827 bool complete = true;
4828 const TransactionError err =
4829 pwallet->FillPSBT(psbtx, complete, SigHashType().withForkId(),
4830 false, bip32derivs);
4831 if (err != TransactionError::OK) {
4832 throw JSONRPCTransactionError(err);
4833 }
4834
4835 // Serialize the PSBT
4837 ssTx << psbtx;
4838
4839 UniValue result(UniValue::VOBJ);
4840 result.pushKV("psbt", EncodeBase64(ssTx.str()));
4841 result.pushKV("fee", fee);
4842 result.pushKV("changepos", change_position);
4843 return result;
4844 },
4845 };
4846}
4847
4849 return RPCHelpMan{
4850 "upgradewallet",
4851 "Upgrade the wallet. Upgrades to the latest version if no "
4852 "version number is specified\n"
4853 "New keys may be generated and a new wallet backup will need to "
4854 "be made.",
4856 "The version number to upgrade to. Default is the latest "
4857 "wallet version"}},
4859 RPCExamples{HelpExampleCli("upgradewallet", "200300") +
4860 HelpExampleRpc("upgradewallet", "200300")},
4861 [&](const RPCHelpMan &self, const Config &config,
4862 const JSONRPCRequest &request) -> UniValue {
4863 std::shared_ptr<CWallet> const wallet =
4865 if (!wallet) {
4866 return NullUniValue;
4867 }
4868 CWallet *const pwallet = wallet.get();
4869
4870 EnsureWalletIsUnlocked(pwallet);
4871
4872 int version = 0;
4873 if (!request.params[0].isNull()) {
4874 version = request.params[0].getInt<int>();
4875 }
4876 bilingual_str error;
4877 if (!pwallet->UpgradeWallet(version, error)) {
4879 }
4880 return error.original;
4881 },
4882 };
4883}
4884
4886
4888 return RPCHelpMan{
4889 "createwallettransaction",
4890 "Create a transaction sending an amount to a given address.\n" +
4892 {
4894 "The bitcoin address to send to."},
4896 "The amount in " + Currency::get().ticker + " to send. eg 0.1"},
4897 },
4898 RPCResult{RPCResult::Type::STR_HEX, "txid", "The transaction id."},
4900 HelpExampleCli("createwallettransaction",
4901 "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 100000") +
4902 HelpExampleRpc("createwallettransaction",
4903 "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 100000")},
4904 [&](const RPCHelpMan &self, const Config &config,
4905 const JSONRPCRequest &request) -> UniValue {
4906 std::shared_ptr<CWallet> const wallet =
4908 if (!wallet) {
4909 return NullUniValue;
4910 }
4911 CWallet *const pwallet = wallet.get();
4912
4913 // Make sure the results are valid at least up to the most recent
4914 // block the user could have gotten from another RPC command prior
4915 // to now
4916 pwallet->BlockUntilSyncedToCurrentChain();
4917
4918 LOCK(pwallet->cs_wallet);
4919
4920 EnsureWalletIsUnlocked(pwallet);
4921
4922 UniValue address_amounts(UniValue::VOBJ);
4923 const std::string address = request.params[0].get_str();
4924 address_amounts.pushKV(address, request.params[1]);
4925 UniValue subtractFeeFromAmount(UniValue::VARR);
4926
4927 std::vector<CRecipient> recipients;
4928 ParseRecipients(address_amounts, subtractFeeFromAmount, recipients,
4929 wallet->GetChainParams());
4930
4931 CCoinControl coin_control;
4932 return SendMoney(pwallet, coin_control, recipients, {}, false);
4933 },
4934 };
4935}
4936
4938 // clang-format off
4939 static const CRPCCommand commands[] = {
4940 // category actor (function)
4941 // ------------------ ----------------------
4942 { "rawtransactions", fundrawtransaction, },
4943 { "wallet", abandontransaction, },
4944 { "wallet", addmultisigaddress, },
4945 { "wallet", createwallet, },
4946 { "wallet", getaddressesbylabel, },
4947 { "wallet", getaddressinfo, },
4948 { "wallet", getbalance, },
4949 { "wallet", getnewaddress, },
4950 { "wallet", getrawchangeaddress, },
4951 { "wallet", getreceivedbyaddress, },
4952 { "wallet", getreceivedbylabel, },
4953 { "wallet", gettransaction, },
4954 { "wallet", getunconfirmedbalance, },
4955 { "wallet", getbalances, },
4956 { "wallet", getwalletinfo, },
4957 { "wallet", keypoolrefill, },
4958 { "wallet", listaddressgroupings, },
4959 { "wallet", listlabels, },
4960 { "wallet", listlockunspent, },
4961 { "wallet", listreceivedbyaddress, },
4962 { "wallet", listreceivedbylabel, },
4963 { "wallet", listsinceblock, },
4964 { "wallet", listtransactions, },
4965 { "wallet", listunspent, },
4966 { "wallet", listwalletdir, },
4967 { "wallet", listwallets, },
4968 { "wallet", loadwallet, },
4969 { "wallet", lockunspent, },
4970 { "wallet", rescanblockchain, },
4971 { "wallet", send, },
4972 { "wallet", sendmany, },
4973 { "wallet", sendtoaddress, },
4974 { "wallet", sethdseed, },
4975 { "wallet", setlabel, },
4976 { "wallet", settxfee, },
4977 { "wallet", setwalletflag, },
4978 { "wallet", signmessage, },
4979 { "wallet", signrawtransactionwithwallet, },
4980 { "wallet", unloadwallet, },
4981 { "wallet", upgradewallet, },
4982 { "wallet", walletcreatefundedpsbt, },
4983 { "wallet", walletprocesspsbt, },
4984 // For testing purpose
4985 { "hidden", createwallettransaction, },
4986 };
4987 // clang-format on
4988
4989 return commands;
4990}
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:165
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:66
int flags
Definition: bitcoin-tx.cpp:542
const CScript redeemScript
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:53
Address book data.
Definition: wallet.h:214
const std::string & GetLabel() const
Definition: wallet.h:228
std::string purpose
Definition: wallet.h:220
BlockHash hashPrevBlock
Definition: block.h:27
bool IsNull() const
Definition: block.h:49
Definition: block.h:60
std::vector< CTransactionRef > vtx
Definition: block.h:63
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:86
Coin Control Features.
Definition: coincontrol.h:21
int m_max_depth
Maximum chain depth value for coin availability.
Definition: coincontrol.h:48
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:34
int m_min_depth
Minimum chain depth value for coin availability.
Definition: coincontrol.h:46
std::optional< CFeeRate > m_feerate
Override the wallet's m_pay_tx_fee if set.
Definition: coincontrol.h:38
bool fOverrideFeeRate
Override automatic min/max checks on fee, m_feerate must be set if true.
Definition: coincontrol.h:36
bool m_add_inputs
If false, only selected inputs are used.
Definition: coincontrol.h:27
CTxDestination destChange
Definition: coincontrol.h:23
bool m_avoid_address_reuse
Forbids inclusion of dirty (previously used) addresses.
Definition: coincontrol.h:44
bool m_include_unsafe_inputs
If false, only safe inputs will be used (confirmed or self transfers)
Definition: coincontrol.h:29
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
Definition: coincontrol.h:42
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
std::string ToString() const
Definition: feerate.cpp:57
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
CKeyID seed_id
seed hash160
Definition: walletdb.h:93
An encapsulated secp256k1 private key.
Definition: key.h:28
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:97
const uint8_t * begin() const
Definition: key.h:93
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:101
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:210
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:76
const uint8_t * end() const
Definition: key.h:94
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
A mutable version of CTransaction.
Definition: transaction.h:274
std::vector< CTxOut > vout
Definition: transaction.h:277
std::vector< CTxIn > vin
Definition: transaction.h:276
Definition: spend.h:22
An encapsulated public key.
Definition: pubkey.h:31
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:154
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:137
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:24
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
Amount nValue
Definition: transaction.h:130
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:269
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:3370
BlockHash GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:1056
double ScanningProgress() const
Definition: wallet.h:547
TxItems wtxOrdered
Definition: wallet.h:456
RecursiveMutex cs_wallet
Definition: wallet.h:415
SteadyClock::duration ScanningDuration() const
Definition: wallet.h:543
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:474
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:3544
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:1051
OutputType m_default_address_type
Definition: wallet.h:767
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:3386
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:427
CFeeRate m_pay_tx_fee
Definition: wallet.h:753
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we are allowed to upgrade (or already support) to the named feature
Definition: wallet.h:512
bool IsScanning() const
Definition: wallet.h:542
CFeeRate m_min_fee
Definition: wallet.h:758
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet)
Definition: wallet.h:843
Amount m_default_max_tx_fee
Absolute maximum transaction fee (in satoshis) used by default for the wallet.
Definition: wallet.h:779
bool UpgradeWallet(int version, bilingual_str &error)
Upgrade the wallet.
Definition: wallet.cpp:3149
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:3325
bool IsCrypted() const
Definition: wallet.cpp:3258
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:455
std::optional< OutputType > m_default_change_type
Default output type for change outputs.
Definition: wallet.h:774
const CAddressBookData * FindAddressBookEntry(const CTxDestination &, bool allow_change=false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3137
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:65
CTransactionRef tx
Definition: transaction.h:160
TxId GetId() const
Definition: transaction.h:301
bool IsCoinBase() const
Definition: transaction.h:302
Definition: config.h:19
std::string str() const
Definition: streams.h:195
const SigningProvider *const provider
Definition: rpcwallet.cpp:3825
UniValue operator()(const PKHash &pkhash) const
Definition: rpcwallet.cpp:3872
UniValue operator()(const ScriptHash &scripthash) const
Definition: rpcwallet.cpp:3883
void ProcessSubScript(const CScript &subscript, UniValue &obj) const
Definition: rpcwallet.cpp:3827
DescribeWalletAddressVisitor(const SigningProvider *_provider)
Definition: rpcwallet.cpp:3865
UniValue operator()(const CNoDestination &dest) const
Definition: rpcwallet.cpp:3868
Fast randomness source.
Definition: random.h:156
RecursiveMutex cs_KeyStore
const CHDChain & GetHDChain() const
void SetHDSeed(const CPubKey &key)
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
CPubKey DeriveNewSeed(const CKey &key)
auto Arg(size_t i) const
Helper to get a required or default-valued request argument.
Definition: util.h:410
auto MaybeArg(size_t i) const
Helper to get an optional request argument.
Definition: util.h:450
A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet.
virtual std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const
Signature hash type wrapper class.
Definition: sighashtype.h:37
bool hasForkId() const
Definition: sighashtype.h:77
An interface to be implemented by keystores that support signing.
virtual bool GetCScript(const CScriptID &scriptid, CScript &script) const
virtual bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:94
void push_back(UniValue val)
Definition: univalue.cpp:96
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:229
@ VOBJ
Definition: univalue.h:31
@ VSTR
Definition: univalue.h:33
@ VARR
Definition: univalue.h:32
@ VNUM
Definition: univalue.h:34
@ VBOOL
Definition: univalue.h:35
bool isNull() const
Definition: univalue.h:104
const UniValue & get_obj() const
size_t size() const
Definition: univalue.h:92
enum VType type() const
Definition: univalue.h:147
void pushKVs(UniValue obj)
Definition: univalue.cpp:126
const std::vector< std::string > & getKeys() const
bool empty() const
Definition: univalue.h:90
void pushKVEnd(std::string key, UniValue val)
Definition: univalue.cpp:108
Int getInt() const
Definition: univalue.h:157
const UniValue & get_array() const
bool exists(const std::string &key) const
Definition: univalue.h:99
void reserve(size_t n)
Definition: univalue.h:68
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:115
bool get_bool() const
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1129
bool IsNull() const
Definition: uint256.h:32
std::string GetHex() const
Definition: uint256.cpp:16
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:136
virtual bool findBlock(const BlockHash &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
virtual bool havePruned()=0
Check if any block has been pruned.
virtual void findCoins(std::map< COutPoint, Coin > &coins)=0
Look up unspent output information.
virtual bool hasAssumedValidChain()=0
Return true if an assumed-valid chain is in use.
virtual bool hasBlocks(const BlockHash &block_hash, int min_height=0, std::optional< int > max_height={})=0
Return true if data is available for all blocks in the specified range of blocks.
virtual bool findAncestorByHeight(const BlockHash &block_hash, int ancestor_height, const FoundBlock &ancestor_out={})=0
Find ancestor of block at specified height and optionally return ancestor information.
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee settings).
virtual std::optional< int > getPruneHeight()=0
Get the current prune height.
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:55
256-bit opaque blob.
Definition: uint256.h:129
const Config & GetConfig()
Definition: config.cpp:40
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, const CTxUndo *txundo=nullptr)
Definition: core_write.cpp:221
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:173
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:199
SigHashType ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:273
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
TransactionError
Definition: error.h:22
void LockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2516
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2367
util::Result< CTxDestination > GetNewDestination(const OutputType type, const std::string &label)
Definition: wallet.cpp:2398
util::Result< CTxDestination > GetNewChangeDestination(const OutputType type)
Definition: wallet.cpp:2415
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2537
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2378
bool IsLockedCoin(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2531
void UnlockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2521
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:2326
bool SignTransaction(CMutableTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2075
void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2526
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:2388
TransactionError FillPSBT(PartiallySignedTransaction &psbtx, bool &complete, SigHashType sighash_type=SigHashType().withForkId(), bool sign=true, bool bip32derivs=true) const
Fills out a PSBT with information from the wallet.
Definition: wallet.cpp:2122
int64_t GetOldestKeyPoolTime() const
Definition: wallet.cpp:2429
void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string > > orderForm, bool broadcast=true)
Add the transaction to the wallet and maybe attempt to broadcast it.
Definition: wallet.cpp:2196
void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(void SetWalletFlag(uint64_t flags)
Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function...
Definition: wallet.cpp:1562
isminetype IsMine(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1496
bool CanGetAddresses(bool internal=false) const
Returns true if the wallet can give out new addresses.
Definition: wallet.cpp:1548
ScanResult ScanForWalletTransactions(const BlockHash &start_block, int start_height, std::optional< int > max_height, const WalletRescanReserver &reserver, bool fUpdate)
Scan the block chain (starting in start_block) for transactions from or to us.
Definition: wallet.cpp:1779
bool IsSpentKey(const TxId &txid, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:993
const CChainParams & GetChainParams() const override
Definition: wallet.cpp:447
bool IsSpent(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Outpoint is spent if any non-conflicted transaction, spends it:
Definition: wallet.cpp:728
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1571
bool IsWalletFlagSet(uint64_t flag) const override
Check if a certain wallet flag is set.
Definition: wallet.cpp:1589
bool AbandonTransaction(const TxId &txid)
Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent.
Definition: wallet.cpp:1238
uint8_t isminefilter
Definition: wallet.h:43
isminetype
IsMine() return codes.
Definition: ismine.h:18
@ ISMINE_SPENDABLE
Definition: ismine.h:21
@ ISMINE_WATCH_ONLY
Definition: ismine.h:20
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:167
bool IsValidDestinationString(const std::string &str, const CChainParams &params)
Definition: key_io.cpp:183
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition: key_io.cpp:174
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:77
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
Definition: moneystr.cpp:13
static bool isNull(const AnyVoteItem &item)
Definition: processor.cpp:417
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:90
bool ParseOutputType(const std::string &type, OutputType &output_type)
Definition: outputtype.cpp:19
OutputType
Definition: outputtype.h:16
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:316
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
Response response
Definition: processor.cpp:522
bool DecodeBase64PSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:296
bool FinalizeAndExtractPSBT(PartiallySignedTransaction &psbtx, CMutableTransaction &result)
Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized.
Definition: psbt.cpp:247
void SignTransactionResultToJSON(CMutableTransaction &mtx, bool complete, const std::map< COutPoint, Coin > &coins, const std::map< int, std::string > &input_errors, UniValue &result)
CMutableTransaction ConstructTransaction(const CChainParams &params, const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime)
Create a transaction from univalue parameters.
void ParsePrevouts(const UniValue &prevTxsUnival, FillableSigningProvider *keystore, std::map< COutPoint, Coin > &coins)
Parse a prevtxs UniValue array and get the map of coins from it.
bool CachedTxIsFromMe(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Definition: receive.cpp:321
std::set< std::set< CTxDestination > > GetAddressGroupings(const CWallet &wallet)
Definition: receive.cpp:453
Amount CachedTxGetDebit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
filter decides which addresses will count towards the debit
Definition: receive.cpp:164
bool ScriptIsChange(const CWallet &wallet, const CScript &script)
Definition: receive.cpp:75
void CachedTxGetAmounts(const CWallet &wallet, const CWalletTx &wtx, std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, Amount &nFee, const isminefilter &filter)
Definition: receive.cpp:262
std::map< CTxDestination, Amount > GetAddressBalances(const CWallet &wallet)
Definition: receive.cpp:413
Amount CachedTxGetCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Definition: receive.cpp:139
bool CachedTxIsTrusted(const CWallet &wallet, const CWalletTx &wtx, std::set< TxId > &trusted_parents)
Definition: receive.cpp:326
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:384
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:58
const char * name
Definition: rest.cpp:47
RPCErrorCode
Bitcoin RPC error codes.
Definition: protocol.h:22
@ RPC_WALLET_INVALID_LABEL_NAME
Invalid label name.
Definition: protocol.h:94
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
Definition: protocol.h:38
@ RPC_WALLET_INSUFFICIENT_FUNDS
Not enough funds in wallet or account.
Definition: protocol.h:92
@ RPC_WALLET_ENCRYPTION_FAILED
Failed to encrypt the wallet.
Definition: protocol.h:105
@ RPC_METHOD_DEPRECATED
RPC method is deprecated.
Definition: protocol.h:60
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
@ RPC_WALLET_ERROR
Wallet errors Unspecified problem with wallet (key not found etc.)
Definition: protocol.h:90
@ RPC_WALLET_NOT_FOUND
Invalid wallet specified.
Definition: protocol.h:109
@ RPC_INTERNAL_ERROR
Definition: protocol.h:33
@ RPC_WALLET_KEYPOOL_RAN_OUT
Keypool ran out, call keypoolrefill first.
Definition: protocol.h:96
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:50
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:42
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:153
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:236
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:179
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:336
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:58
const std::string EXAMPLE_ADDRESS
Example CashAddr address used in multiple RPCExamples.
Definition: util.cpp:26
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:170
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition: util.cpp:25
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:194
CPubKey AddrToPubKey(const CChainParams &chainparams, const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:208
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:93
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:76
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Check for expected keys/value types in an Object.
Definition: util.cpp:29
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:158
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:304
static RPCHelpMan createwallet()
Definition: rpcwallet.cpp:2793
static RPCHelpMan getnewaddress()
Definition: rpcwallet.cpp:96
static RPCHelpMan sethdseed()
Definition: rpcwallet.cpp:4467
static RPCHelpMan listreceivedbylabel()
Definition: rpcwallet.cpp:1199
static RPCHelpMan sendtoaddress()
Definition: rpcwallet.cpp:303
Span< const CRPCCommand > GetWalletRPCCommands()
Definition: rpcwallet.cpp:4937
static RPCHelpMan listunspent()
Definition: rpcwallet.cpp:2969
static RPCHelpMan getrawchangeaddress()
Definition: rpcwallet.cpp:148
RPCHelpMan listlabels()
Definition: rpcwallet.cpp:4159
static RPCHelpMan walletprocesspsbt()
Definition: rpcwallet.cpp:4567
static void ListTransactions(const CWallet *const pwallet, const CWalletTx &wtx, int nMinDepth, bool fLong, Vec &ret, const isminefilter &filter_ismine, const std::string *filter_label) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
List transactions based on the given criteria.
Definition: rpcwallet.cpp:1279
static RPCHelpMan fundrawtransaction()
Definition: rpcwallet.cpp:3424
static RPCHelpMan gettransaction()
Definition: rpcwallet.cpp:1790
static UniValue ListReceived(const Config &config, const CWallet *const pwallet, const UniValue &params, bool by_label) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: rpcwallet.cpp:968
static UniValue AddressBookDataToJSON(const CAddressBookData &data, const bool verbose)
Convert CAddressBookData to JSON record.
Definition: rpcwallet.cpp:3909
static RPCHelpMan listaddressgroupings()
Definition: rpcwallet.cpp:404
static void WalletTxToJSON(const CWallet &wallet, const CWalletTx &wtx, UniValue &entry) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
Definition: rpcwallet.cpp:61
static RPCHelpMan addmultisigaddress()
Definition: rpcwallet.cpp:853
RPCHelpMan getaddressesbylabel()
Definition: rpcwallet.cpp:4090
static RPCHelpMan listlockunspent()
Definition: rpcwallet.cpp:2232
static RPCHelpMan send()
Definition: rpcwallet.cpp:4221
static Amount GetReceived(const CWallet &wallet, const UniValue &params, bool by_label) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
Definition: rpcwallet.cpp:476
static RPCHelpMan getunconfirmedbalance()
Definition: rpcwallet.cpp:694
static RPCHelpMan listwallets()
Definition: rpcwallet.cpp:2626
RPCHelpMan rescanblockchain()
Definition: rpcwallet.cpp:3699
static RPCHelpMan upgradewallet()
Definition: rpcwallet.cpp:4848
static RPCHelpMan unloadwallet()
Definition: rpcwallet.cpp:2905
static RPCHelpMan walletcreatefundedpsbt()
Definition: rpcwallet.cpp:4650
static RPCHelpMan getbalances()
Definition: rpcwallet.cpp:2353
static RPCHelpMan listwalletdir()
Definition: rpcwallet.cpp:2586
static RPCHelpMan keypoolrefill()
Definition: rpcwallet.cpp:2012
bool HaveKey(const SigningProvider &wallet, const CKey &key)
Checks if a CKey is in the given CWallet compressed or otherwise.
Definition: rpcwallet.cpp:54
RPCHelpMan getaddressinfo()
Definition: rpcwallet.cpp:3919
static std::vector< RPCResult > TransactionDescriptionString()
Definition: rpcwallet.cpp:1362
static RPCHelpMan getwalletinfo()
Definition: rpcwallet.cpp:2448
static RPCHelpMan lockunspent()
Definition: rpcwallet.cpp:2066
UniValue SendMoney(CWallet *const pwallet, const CCoinControl &coin_control, std::vector< CRecipient > &recipients, mapValue_t map_value, bool broadcast=true)
Definition: rpcwallet.cpp:280
static RPCHelpMan setwalletflag()
Definition: rpcwallet.cpp:2709
RPCHelpMan signrawtransactionwithwallet()
Definition: rpcwallet.cpp:3568
static RPCHelpMan createwallettransaction()
Definition: rpcwallet.cpp:4887
static RPCHelpMan setlabel()
Definition: rpcwallet.cpp:194
RPCHelpMan signmessage()
Definition: signmessage.cpp:13
static RPCHelpMan getreceivedbyaddress()
Definition: rpcwallet.cpp:526
static RPCHelpMan getreceivedbylabel()
Definition: rpcwallet.cpp:576
static void MaybePushAddress(UniValue &entry, const CTxDestination &dest)
Definition: rpcwallet.cpp:1260
static RPCHelpMan getbalance()
Definition: rpcwallet.cpp:622
static RPCHelpMan loadwallet()
Definition: rpcwallet.cpp:2655
static RPCHelpMan listsinceblock()
Definition: rpcwallet.cpp:1556
static RPCHelpMan settxfee()
Definition: rpcwallet.cpp:2299
static RPCHelpMan listreceivedbyaddress()
Definition: rpcwallet.cpp:1122
static RPCHelpMan sendmany()
Definition: rpcwallet.cpp:722
RPCHelpMan listtransactions()
Definition: rpcwallet.cpp:1398
static UniValue DescribeWalletAddress(const CWallet *const pwallet, const CTxDestination &dest)
Definition: rpcwallet.cpp:3894
void ParseRecipients(const UniValue &address_amounts, const UniValue &subtract_fee_outputs, std::vector< CRecipient > &recipients, const CChainParams &chainParams)
Definition: rpcwallet.cpp:242
void FundTransaction(CWallet *const pwallet, CMutableTransaction &tx, Amount &fee_out, int &change_position, const UniValue &options, CCoinControl &coinControl)
Definition: rpcwallet.cpp:3269
static RPCHelpMan abandontransaction()
Definition: rpcwallet.cpp:1957
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:55
@ SER_NETWORK
Definition: serialize.h:154
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Check whether we know how to sign for an output like this, assuming we have all private keys.
Definition: sign.cpp:424
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, int change_pos, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:989
void AvailableCoins(const CWallet &wallet, std::vector< COutput > &vCoins, const CCoinControl *coinControl, const Amount nMinimumAmount, const Amount nMaximumAmount, const Amount nMinimumSumAmount, const uint64_t nMaximumCount)
populate vCoins with vector of available COutputs.
Definition: spend.cpp:71
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< uint8_t > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:108
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
Definition: standard.cpp:29
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:260
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
CKeyID ToKeyID(const PKHash &key_hash)
Definition: standard.cpp:25
TxoutType
Definition: standard.h:38
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:63
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:108
Definition: amount.h:19
static constexpr Amount zero() noexcept
Definition: amount.h:32
Amount m_mine_untrusted_pending
Untrusted, but in mempool (pending)
Definition: receive.h:73
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Definition: receive.h:53
std::optional< int > last_scanned_height
Definition: wallet.h:646
enum CWallet::ScanResult::@20 status
static const Currency & get()
Definition: amount.cpp:18
std::string ticker
Definition: amount.h:150
bool require_create
Definition: db.h:221
uint64_t create_flags
Definition: db.h:222
bool require_existing
Definition: db.h:220
SecureString create_passphrase
Definition: db.h:223
A version of CTransaction with the PSBT format.
Definition: psbt.h:334
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g.
@ STR_HEX
Special type that is a STR with only hex chars.
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
@ OBJ_NAMED_PARAMS
Special type that behaves almost exactly like OBJ, defining an options object with a list of pre-defi...
std::string DefaultHint
Hint for default value.
Definition: util.h:206
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:143
bool also_positional
If set allows a named-parameter field in an OBJ_NAMED_PARAM options object to have the same name as a...
Definition: util.h:162
bool skip_type_check
Definition: util.h:140
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ ARR_FIXED
Special array that has a fixed number of entries.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
A TxId is the identifier of a transaction.
Definition: txid.h:14
Wrapper for UniValue::VType, which includes typeAny: used to denote don't care type.
Definition: util.h:61
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:35
Bilingual messages:
Definition: translation.h:17
std::string original
Definition: translation.h:18
std::vector< uint256 > txids
Definition: rpcwallet.cpp:963
tallyitem()=default
Amount nAmount
Definition: rpcwallet.cpp:961
bool fIsWatchonly
Definition: rpcwallet.cpp:964
#define LOCK2(cs1, cs2)
Definition: sync.h:309
#define LOCK(cs)
Definition: sync.h:306
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
const UniValue NullUniValue
Definition: univalue.cpp:16
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string EncodeBase64(Span< const uint8_t > input)
bool IsHex(std::string_view str)
Returns true if each character in str is a hex character, and has an even number of hex digits.
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
Definition: vector.h:34
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11
DatabaseStatus
Definition: db.h:227
void EnsureWalletIsUnlocked(const CWallet *pwallet)
Definition: util.cpp:96
std::shared_ptr< CWallet > GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
Definition: util.cpp:63
LegacyScriptPubKeyMan & EnsureLegacyScriptPubKeyMan(CWallet &wallet, bool also_create)
Definition: util.cpp:114
bool GetAvoidReuseFlag(const CWallet *const pwallet, const UniValue &param)
Definition: util.cpp:21
void HandleWalletError(const std::shared_ptr< CWallet > wallet, DatabaseStatus &status, bilingual_str &error)
Definition: util.cpp:135
bool ParseIncludeWatchonly(const UniValue &include_watchonly, const CWallet &pwallet)
Used by RPC commands that have an include_watchonly parameter.
Definition: util.cpp:38
WalletContext & EnsureWalletContext(const std::any &context)
Definition: util.cpp:104
const std::string HELP_REQUIRING_PASSPHRASE
Definition: util.cpp:17
std::string LabelFromValue(const UniValue &value)
Definition: util.cpp:127
bool GetWalletNameFromJSONRPCRequest(const JSONRPCRequest &request, std::string &wallet_name)
Definition: util.cpp:50
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:21
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:148
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:150
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:46
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:119
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:211
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:151
std::shared_ptr< CWallet > GetWallet(WalletContext &context, const std::string &name)
Definition: wallet.cpp:156
std::shared_ptr< CWallet > CreateWallet(WalletContext &context, const std::string &name, std::optional< bool > load_on_start, DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:295
std::shared_ptr< CWallet > LoadWallet(WalletContext &context, const std::string &name, std::optional< bool > load_on_start, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:277
std::vector< fs::path > ListWalletDir()
Get wallets in wallet directory.
Definition: walletutil.cpp:70
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:55
@ WALLET_FLAG_AVOID_REUSE
Definition: walletutil.h:47
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:70
@ WALLET_FLAG_BLANK_WALLET
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses,...
Definition: walletutil.h:67
@ FEATURE_HD_SPLIT
Definition: walletutil.h:28
@ FEATURE_HD
Definition: walletutil.h:25
@ FEATURE_LATEST
Definition: walletutil.h:36