44 "Imports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n",
57 if (!
DecodeHexTx(tx, request.params[0].get_str())) {
65 std::vector<Txid> vMatch;
66 std::vector<unsigned int> vIndex;
71 LOCK(pwallet->cs_wallet);
73 if (!pwallet->chain().findAncestorByHash(pwallet->GetLastBlockHash(), merkleBlock.
header.
GetHash(),
FoundBlock().height(height))) {
77 std::vector<Txid>::const_iterator it;
78 if ((it = std::find(vMatch.begin(), vMatch.end(), tx.
GetHash())) == vMatch.end()) {
82 unsigned int txnIndex = vIndex[it - vMatch.begin()];
85 if (pwallet->IsMine(*tx_ref)) {
99 "(DEPRECATED) This feature will be removed in the next major release. Start bitcoind with the `-deprecatedrpc=removeprunedfunds` option in order to use this.\n"
100 "Deletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will affect wallet balances.\n",
106 HelpExampleCli(
"removeprunedfunds",
"\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") +
107 "\nAs a JSON-RPC call\n"
108 +
HelpExampleRpc(
"removeprunedfunds",
"\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"")
115 if (!pwallet->chain().rpcEnableDeprecated(
"removeprunedfunds")) {
116 throw JSONRPCError(
RPC_METHOD_DEPRECATED,
"DEPRECATION WARNING: This feature will be removed in the next major release. Start bitcoind with the `-deprecatedrpc=removeprunedfunds` option in order to use this.");
119 LOCK(pwallet->cs_wallet);
122 std::vector<Txid> vHash;
123 vHash.push_back(hash);
124 if (
auto res = pwallet->RemoveTxs(vHash); !res) {
135 if (
data.exists(
"timestamp")) {
137 if (timestamp.
isNum()) {
138 return timestamp.
getInt<int64_t>();
139 }
else if (timestamp.
isStr() && timestamp.
get_str() ==
"now") {
153 if (!
data.exists(
"desc")) {
157 const std::string& descriptor =
data[
"desc"].get_str();
158 const bool active =
data.exists(
"active") ?
data[
"active"].get_bool() :
false;
164 auto parsed_descs =
Parse(descriptor,
keys, error,
true);
165 if (parsed_descs.empty()) {
168 std::optional<bool> internal;
169 if (
data.exists(
"internal")) {
170 if (parsed_descs.size() > 1) {
173 internal =
data[
"internal"].get_bool();
177 std::optional<bool> is_ranged;
178 int64_t range_start = 0, range_end = 1, next_index = 0;
179 if (!parsed_descs.at(0)->IsRange() &&
data.exists(
"range")) {
181 }
else if (parsed_descs.at(0)->IsRange()) {
182 if (
data.exists(
"range")) {
184 range_start = range.first;
185 range_end = range.second + 1;
187 warnings.
push_back(
"Range not given, using default keypool range");
189 range_end =
wallet.m_keypool_size;
191 next_index = range_start;
194 if (
data.exists(
"next_index")) {
195 next_index =
data[
"next_index"].getInt<int64_t>();
197 if (next_index < range_start || next_index >= range_end) {
204 if (active && !parsed_descs.at(0)->IsRange()) {
209 if (parsed_descs.size() > 1 &&
data.exists(
"label")) {
214 if (is_ranged.has_value() && is_ranged.value() &&
data.exists(
"label")) {
218 bool desc_internal = internal.has_value() && internal.value();
220 if (desc_internal &&
data.exists(
"label")) {
225 if (active && !parsed_descs.at(0)->IsSingleType()) {
234 for (
size_t j = 0; j < parsed_descs.size(); ++j) {
235 auto parsed_desc = std::move(parsed_descs[j]);
236 if (parsed_descs.size() == 2) {
237 desc_internal = j == 1;
238 }
else if (parsed_descs.size() > 2) {
243 std::vector<CScript> scripts;
244 if (!parsed_desc->Expand(0,
keys, scripts, expand_keys)) {
245 throw JSONRPCError(
RPC_WALLET_ERROR,
"Cannot expand descriptor. Probably because of hardened derivations without private keys provided");
248 for (
const auto& w : parsed_desc->Warnings()) {
254 if (
keys.keys.empty()) {
257 if (!parsed_desc->HavePrivateKeys(
keys)) {
258 warnings.
push_back(
"Not all private keys provided. Some wallet functionality may return unexpected errors");
263 if (!parsed_desc->HasScripts()) {
272 std::set<CPubKey> pubkeys;
273 std::set<CExtPubKey> extpubs;
274 parsed_desc->GetPubKeys(pubkeys, extpubs);
275 std::transform(extpubs.begin(), extpubs.end(), std::inserter(pubkeys, pubkeys.begin()), [](
const CExtPubKey& xpub) { return xpub.pubkey; });
277 if (
wallet.GetKey(pubkeys.begin()->GetID())) {
282 WalletDescriptor w_desc(std::move(parsed_desc), timestamp, range_start, range_end, next_index);
285 auto spk_manager_res =
wallet.AddWalletDescriptor(w_desc,
keys, label, desc_internal);
287 if (!spk_manager_res) {
291 auto& spk_manager = spk_manager_res.value().get();
296 warnings.
push_back(
"Unknown output type, cannot set descriptor to active.");
298 wallet.AddActiveScriptPubKeyMan(spk_manager.GetID(), *w_desc.
descriptor->GetOutputType(), desc_internal);
302 wallet.DeactivateScriptPubKeyMan(spk_manager.GetID(), *w_desc.
descriptor->GetOutputType(), desc_internal);
310 result.
pushKV(
"error", e);
320 "Import descriptors. This will trigger a rescan of the blockchain based on the earliest timestamp of all descriptors being imported. Requires a new wallet backup.\n"
321 "When importing descriptors with multipath key expressions, if the multipath specifier contains exactly two elements, the descriptor produced from the second element will be imported as an internal descriptor.\n"
322 "\nNote: This call can take over an hour to complete if using an early timestamp; during that time, other rpc calls\n"
323 "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n"
324 "The rescan is significantly faster if block filters are available (using startup option \"-blockfilterindex=1\").\n",
335 "Use the string \"now\" to substitute the current synced blockchain time.\n"
336 "\"now\" can be specified to bypass scanning, for outputs which are known to never have been used, and\n"
337 "0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest timestamp\n"
338 "of all descriptors being imported will be scanned as well as the mempool.",
349 RPCResult::Type::ARR,
"",
"Response is an array with the same size as the input that has the execution result",
367 HelpExampleCli(
"importdescriptors",
"'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"internal\": true }, "
368 "{ \"desc\": \"<my descriptor 2>\", \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
369 HelpExampleCli(
"importdescriptors",
"'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"active\": true, \"range\": [0,100], \"label\": \"<my bech32 wallet>\" }]'")
384 wallet.BlockUntilSyncedToCurrentChain();
388 LOCK(pwallet->m_relock_mutex);
390 const UniValue& requests = main_request.params[0];
391 const int64_t minimum_timestamp = 1;
393 int64_t lowest_timestamp = 0;
397 LOCK(pwallet->cs_wallet);
400 CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(),
FoundBlock().time(lowest_timestamp).mtpTime(now)));
405 const int64_t timestamp = std::max(
GetImportTimestamp(request, now), minimum_timestamp);
409 if (lowest_timestamp > timestamp ) {
410 lowest_timestamp = timestamp;
414 if (!rescan && result[
"success"].get_bool()) {
418 pwallet->ConnectScriptPubKeyManNotifiers();
419 pwallet->RefreshAllTXOs();
424 int64_t scanned_time = pwallet->RescanFromTime(lowest_timestamp, reserver);
427 if (pwallet->IsAbortingRescan()) {
431 if (scanned_time > lowest_timestamp) {
432 std::vector<UniValue> results = response.
getValues();
437 for (
unsigned int i = 0; i < requests.
size(); ++i) {
444 if (scanned_time <=
GetImportTimestamp(request, now) || results.at(i).exists(
"error")) {
447 std::string error_msg{
strprintf(
"Rescan failed for descriptor with timestamp %d. There "
448 "was an error reading a block from time %d, which is after or within %d seconds "
449 "of key creation, and could contain transactions pertaining to the desc. As a "
450 "result, transactions and coins using this desc may not appear in the wallet.",
452 if (pwallet->chain().havePruned()) {
453 error_msg +=
strprintf(
" This error could be caused by pruning or data corruption "
454 "(see bitcoind log for details) and could be dealt with by downloading and "
455 "rescanning the relevant blocks (see -reindex option and rescanblockchain RPC).");
456 }
else if (pwallet->chain().hasAssumedValidChain()) {
457 error_msg +=
strprintf(
" This error is likely caused by an in-progress assumeutxo "
458 "background sync. Check logs or getchainstates RPC for assumeutxo background "
459 "sync progress and try again later.");
461 error_msg +=
strprintf(
" This error could potentially caused by data corruption. If "
462 "the issue persists you may want to reindex (see -reindex option).");
483 "List all descriptors present in a wallet.\n",
489 {
RPCResult::Type::ARR,
"descriptors",
"Array of descriptor objects (sorted by descriptor string representation)",
494 {
RPCResult::Type::BOOL,
"active",
"Whether this descriptor is currently used to generate new addresses"},
495 {
RPCResult::Type::BOOL,
"internal",
true,
"True if this descriptor is used to generate change addresses. False if this descriptor is used to generate receiving addresses; defined only for active descriptors"},
500 {
RPCResult::Type::NUM,
"next",
true,
"Same as next_index field. Kept for compatibility reason."},
501 {
RPCResult::Type::NUM,
"next_index",
true,
"The next index to generate addresses from; defined only for ranged descriptors"},
514 const bool priv = !request.params[0].isNull() && request.params[0].get_bool();
527 std::vector<WalletDescInfo> wallet_descriptors = *exported;
529 std::sort(wallet_descriptors.begin(), wallet_descriptors.end(), [](
const auto& a,
const auto& b) {
530 return a.descriptor < b.descriptor;
536 spk.
pushKV(
"desc", info.descriptor);
537 spk.
pushKV(
"timestamp", info.creation_time);
538 spk.
pushKV(
"active", info.active);
539 if (info.internal.has_value()) {
540 spk.
pushKV(
"internal", info.internal.value());
542 if (info.range.has_value()) {
546 spk.
pushKV(
"range", std::move(range));
547 spk.
pushKV(
"next", info.next_index);
548 spk.
pushKV(
"next_index", info.next_index);
555 response.
pushKV(
"descriptors", std::move(descriptors));
566 "Safely copies the current wallet file to the specified destination, which can either be a directory or a path with a filename.\n",
582 pwallet->BlockUntilSyncedToCurrentChain();
584 LOCK(pwallet->cs_wallet);
586 std::string strDest = request.params[0].get_str();
587 if (!pwallet->BackupWallet(strDest)) {
601 "Restores and loads a wallet from backup.\n"
602 "\nThe rescan is significantly faster if block filters are available"
603 "\n(using startup option \"-blockfilterindex=1\").\n",
613 {
RPCResult::Type::ARR,
"warnings",
true,
"Warning messages, if any, related to restoring and loading the wallet.",
620 HelpExampleCli(
"restorewallet",
"\"testwallet\" \"home\\backups\\backup-file.bak\"")
621 +
HelpExampleRpc(
"restorewallet",
"\"testwallet\" \"home\\backups\\backup-file.bak\"")
622 +
HelpExampleCliNamed(
"restorewallet", {{
"wallet_name",
"testwallet"}, {
"backup_file",
"home\\backups\\backup-file.bak\""}, {
"load_on_startup",
true}})
623 +
HelpExampleRpcNamed(
"restorewallet", {{
"wallet_name",
"testwallet"}, {
"backup_file",
"home\\backups\\backup-file.bak\""}, {
"load_on_startup",
true}})
630 auto backup_file =
fs::u8path(request.params[1].get_str());
632 std::string wallet_name = request.params[0].get_str();
634 std::optional<bool> load_on_start = request.params[2].isNull() ? std::nullopt : std::optional<bool>(request.params[2].get_bool());
638 std::vector<bilingual_str> warnings;
640 const std::shared_ptr<CWallet>
wallet =
RestoreWallet(context, backup_file, wallet_name, load_on_start, status, error, warnings);
constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
#define CHECK_NONFATAL(condition)
Identity function.
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
CBlockHeader header
Public only for unit testing.
uint256 ExtractMatches(std::vector< Txid > &vMatch, std::vector< unsigned int > &vnIndex)
extract the matching txid's represented by this partial merkle tree and their respective indices with...
Minimal stream for reading from an existing byte array by std::span.
void push_back(UniValue val)
const std::string & get_str() const
const std::vector< UniValue > & getValues() const
void pushKV(std::string key, UniValue val)
Helper for findBlock to selectively return pieces of block data.
static transaction_identifier FromUint256(const uint256 &id)
The util::Expected class provides a standard way for low-level functions to return either error value...
constexpr const E & error() const &noexcept LIFETIMEBOUND
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Descriptor with some wallet metadata.
std::shared_ptr< Descriptor > descriptor
RAII object to check and reserve a wallet rescan.
bool reserve(bool with_passphrase=false)
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness, bool try_witness)
static path u8path(std::string_view utf8_str)
@ MEMPOOL_NO_BROADCAST
Add the transaction to the mempool, but don't broadcast to anybody.
bilingual_str ErrorString(const Result< T > &result)
static UniValue ProcessDescriptorImport(CWallet &wallet, const UniValue &data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
std::shared_ptr< CWallet > GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
void HandleWalletError(const std::shared_ptr< CWallet > &wallet, DatabaseStatus &status, bilingual_str &error)
RPCMethod importdescriptors()
void EnsureWalletIsUnlocked(const CWallet &wallet)
WalletContext & EnsureWalletContext(const std::any &context)
RPCMethod removeprunedfunds()
RPCMethod importprunedfunds()
std::string LabelFromValue(const UniValue &value)
std::shared_ptr< CWallet > RestoreWallet(WalletContext &context, const fs::path &backup_file, const std::string &wallet_name, std::optional< bool > load_on_start, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings, bool load_after_restore, bool allow_unnamed)
RPCMethod listdescriptors()
static int64_t GetImportTimestamp(const UniValue &data, int64_t now)
util::Expected< std::vector< WalletDescInfo >, std::string > ExportDescriptors(const CWallet &wallet, bool export_private)
Export the descriptors from a wallet so that they can be imported elsewhere.
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
RPCMethod restorewallet()
is a home for public enum and struct type definitions that are used internally by node code,...
static CTransactionRef MakeTransactionRef(Tx &&txIn)
std::shared_ptr< const CTransaction > CTransactionRef
UniValue JSONRPCError(int code, const std::string &message)
@ RPC_MISC_ERROR
General application defined errors.
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
@ RPC_METHOD_DEPRECATED
RPC method is deprecated.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_WALLET_ERROR
Wallet errors.
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string_view name)
void PushWarnings(const UniValue &warnings, UniValue &obj)
Push warning messages to an RPC "warnings" field as a JSON array of strings.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
A mutable version of CTransaction.
Txid GetHash() const
Compute the hash of this CMutableTransaction.
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings....
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
@ ARR_FIXED
Special array that has a fixed number of entries.
State of transaction confirmed in a block.
WalletContext struct containing references to state shared between CWallet instances,...
std::vector< uint16_t > keys
#define EXCLUSIVE_LOCKS_REQUIRED(...)
const char * uvTypeName(UniValue::VType t)