Repository navigation
Expand file tree
/
Copy pathimports.cpp
More file actions
338 lines (302 loc) · 13.7 KB
/
Copy pathimports.cpp
File metadata and controls
338 lines (302 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Copyright (c) 2026-present The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <wallet/imports.h>
#include <wallet/scan.h>
#include <cstdint>
#include <limits>
namespace wallet {
ImportResult ImportDescriptor(CWallet& wallet, const ImportDescriptorRequest& request) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
{
AssertLockHeld(wallet.cs_wallet);
std::vector<std::string> warnings;
// Parse descriptor string
FlatSigningProvider keys;
std::string error;
auto parsed_descs = Parse(request.descriptor, keys, error, /*require_checksum=*/true);
if (parsed_descs.empty()) {
return ImportResult(WalletErrorCode::InvalidDescriptor, error, warnings);
}
if (request.internal.has_value() && parsed_descs.size() > 1) {
return ImportResult(
WalletErrorCode::InvalidDescriptor,
"Cannot have multipath descriptor while also specifying 'internal'",
warnings
);
}
// Range check
bool is_ranged{false};
int64_t range_start = 0, range_end = 1, next_index = 0;
if (!parsed_descs.at(0)->IsRange() && request.range.has_value()) {
return ImportResult(
WalletErrorCode::InvalidParameter,
"Range should not be specified for an un-ranged descriptor",
warnings
);
} else if (parsed_descs.at(0)->IsRange()) {
if (request.range.has_value()) {
int64_t low = request.range->first;
int64_t high = request.range->second;
if (auto res = CheckDescriptorRangeBounds(low, high); !res) {
return ImportResult(WalletErrorCode::InvalidParameter,
res.error());
}
range_start = low;
range_end = high + 1; // Specified range end is inclusive, but we need range end as exclusive
} else {
warnings.emplace_back("Range not given, using default keypool range");
range_start = 0;
range_end = wallet.m_keypool_size;
}
// WalletDescriptor stores the range as int32_t with an exclusive end, so an
// end past the maximum index would be truncated to a negative range.
if (range_end > std::numeric_limits<int32_t>::max()) {
return ImportResult(WalletErrorCode::InvalidParameter, "End of range is too high", warnings);
}
next_index = request.next_index.value_or(range_start);
is_ranged = true;
if (next_index < range_start || next_index >= range_end) {
return ImportResult(
WalletErrorCode::InvalidParameter,
"next_index is out of range",
warnings
);
}
}
// Active descriptors must be ranged
if (request.active && !parsed_descs.at(0)->IsRange()) {
return ImportResult(
WalletErrorCode::InvalidParameter,
"Active descriptors must be ranged",
warnings
);
}
// Multipath descriptors should not have a label
if (parsed_descs.size() > 1 && !request.label.empty()) {
return ImportResult(
WalletErrorCode::InvalidParameter,
"Multipath descriptors should not have a label",
warnings
);
}
// Ranged descriptors should not have a label
if (is_ranged && !request.label.empty()) {
return ImportResult(
WalletErrorCode::InvalidParameter,
"Ranged descriptors should not have a label",
warnings
);
}
bool desc_internal = request.internal.value_or(false);
// Internal addresses should not have a label either
if (desc_internal && !request.label.empty()) {
return ImportResult(
WalletErrorCode::InvalidParameter,
"Internal addresses should not have a label",
warnings
);
}
// Combo descriptor check
if (request.active && !parsed_descs.at(0)->IsSingleType()) {
return ImportResult(
WalletErrorCode::GenericError,
"Combo descriptors cannot be set to active",
warnings
);
}
// If the wallet disabled private keys, abort if private keys exist
if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !keys.keys.empty()) {
return ImportResult(
WalletErrorCode::GenericError,
"Cannot import private keys to a wallet with private keys disabled",
warnings
);
}
for (size_t j = 0; j < parsed_descs.size(); ++j) {
auto parsed_desc = std::move(parsed_descs[j]);
if (parsed_descs.size() == 2) {
desc_internal = j == 1;
} else if (parsed_descs.size() > 2) {
CHECK_NONFATAL(!desc_internal);
}
// ExpandPrivate to whether the descriptor can be derived at the first index.
FlatSigningProvider expand_keys;
std::vector<CScript> scripts;
if (!parsed_desc->Expand(0, keys, scripts, expand_keys)) {
return ImportResult(
WalletErrorCode::GenericError,
"Cannot expand descriptor. Probably because of hardened derivations without private keys provided",
warnings
);
}
for (const auto& w : parsed_desc->Warnings()) {
warnings.push_back(w);
}
// If private keys are enabled, check some things.
if (!wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
if (keys.keys.empty()) {
return ImportResult(
WalletErrorCode::GenericError,
"Cannot import descriptor without private keys to a wallet with private keys enabled",
warnings
);
}
if (!parsed_desc->HavePrivateKeys(keys)) {
warnings.emplace_back("Not all private keys provided. Some wallet functionality may return unexpected errors");
}
}
// If this is an unused(KEY) descriptor, check that the wallet doesn't already have other descriptors with this key
if (!parsed_desc->HasScripts()) {
if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
return ImportResult(
WalletErrorCode::GenericError,
"Cannot import unused() to wallet without private keys enabled",
warnings
);
}
// Unused descriptors must contain a single key.
// Earlier checks will have enforced that this key is either a private key when private keys are enabled,
// or that this key is a public key when private keys are disabled.
// If we can retrieve the corresponding private key from the wallet, then this key is already in the wallet
// and we should not import it.
std::set<CPubKey> pubkeys;
std::set<CExtPubKey> extpubs;
parsed_desc->GetPubKeys(pubkeys, extpubs);
std::transform(extpubs.begin(), extpubs.end(), std::inserter(pubkeys, pubkeys.begin()), [](const CExtPubKey& xpub) { return xpub.pubkey; });
CHECK_NONFATAL(pubkeys.size() == 1);
if (wallet.GetKey(pubkeys.begin()->GetID())) {
return ImportResult(
WalletErrorCode::GenericError,
"Cannot import an unused() descriptor when its private key is already in the wallet",
warnings
);
}
}
Assume(request.timestamp.has_value());
WalletDescriptor w_desc(std::move(parsed_desc), request.timestamp.value(), range_start, range_end, next_index);
// Add descriptor to the wallet
auto spk_manager_res = wallet.AddWalletDescriptor(w_desc, keys, request.label, desc_internal);
if (!spk_manager_res) {
return ImportResult(
WalletErrorCode::GenericError,
strprintf("Could not add descriptor '%s': %s", request.descriptor, util::ErrorString(spk_manager_res).original),
warnings
);
}
auto& spk_manager = spk_manager_res.value().get();
// Set descriptor as active if necessary
if (request.active) {
if (!w_desc.descriptor->GetOutputType()) {
warnings.emplace_back("Unknown output type, cannot set descriptor to active.");
} else {
wallet.AddActiveScriptPubKeyMan(spk_manager.GetID(), *w_desc.descriptor->GetOutputType(), desc_internal);
}
} else {
if (w_desc.descriptor->GetOutputType()) {
wallet.DeactivateScriptPubKeyMan(spk_manager.GetID(), *w_desc.descriptor->GetOutputType(), desc_internal);
}
}
}
ImportResult result;
result.warnings = warnings;
return result;
}
std::vector<ImportResult> ProcessDescriptorsImport(CWallet& wallet,
std::vector<ImportDescriptorRequest>& requests)
{
std::vector<ImportResult> response;
WalletRescanReserver reserver(wallet);
if (!reserver.reserve(/*with_passphrase=*/true)) {
return {ImportResult{
WalletErrorCode::GenericError,
"Wallet is currently rescanning. Abort existing rescan or wait.",
/*warnings=*/{},
/*general_error=*/true
}};
}
// Make sure the results are valid at least up to the most recent block
// the user could have gotten from another RPC command prior to now
wallet.BlockUntilSyncedToCurrentChain();
// Ensure that the wallet is not locked for the remainder of this call,
// as the passphrase is used to top up the keypool.
LOCK(wallet.m_relock_mutex);
int64_t now = 0;
int64_t lowest_timestamp = 0;
bool rescan = false;
{
LOCK(wallet.cs_wallet);
if (wallet.IsLocked()) {
return {ImportResult{
WalletErrorCode::UnlockNeeded,
"Error: Please enter the wallet passphrase with walletpassphrase first.",
/*warnings=*/{},
/*general_error=*/true
}};
}
CHECK_NONFATAL(wallet.chain().findBlock(wallet.GetLastBlockHash(), interfaces::FoundBlock().time(lowest_timestamp).mtpTime(now)));
for (ImportDescriptorRequest& request : requests) {
request.timestamp = request.timestamp.value_or(now);
const ImportResult& import_result = ImportDescriptor(wallet, request);
if (lowest_timestamp > request.timestamp.value()) {
lowest_timestamp = request.timestamp.value();
}
if (!import_result.has_error()) {
// At least one request succeeded, so we need to rescan
rescan = true;
}
response.push_back(import_result);
}
wallet.ConnectScriptPubKeyManNotifiers();
wallet.RefreshAllTXOs();
}
if (rescan) {
const int64_t scanned_time = wallet.Scanner().ScanFromTime(lowest_timestamp, reserver);
wallet.ResubmitWalletTransactions(node::TxBroadcast::MEMPOOL_NO_BROADCAST, /*force=*/true);
if (wallet.Scanner().IsAborting()) {
return {ImportResult{
WalletErrorCode::MiscError,
"Rescan aborted by user.",
/*warnings=*/{},
/*general_error=*/true
}};
}
if (scanned_time > lowest_timestamp) {
// Compose the response
for (size_t i = 0; i < requests.size(); ++i) {
ImportResult& result = response.at(i);
// If the descriptor timestamp is within the successfully scanned
// range, or if the import result already has an error set, let
// the result stand unmodified. Otherwise replace the result
// with an error message.
const int64_t timestamp{requests.at(i).timestamp.value()};
if (scanned_time > timestamp && !result.has_error()) {
std::string error_msg = strprintf("Rescan failed for descriptor with timestamp %d. There "
"was an error reading a block from time %d, which is after or within %d seconds "
"of key creation, and could contain transactions pertaining to the desc. As a "
"result, transactions and coins using this desc may not appear in the wallet.",
timestamp, scanned_time - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW);
if (wallet.chain().havePruned()) {
error_msg += strprintf(" This error could be caused by pruning or data corruption "
"(see bitcoind log for details) and could be dealt with by downloading and "
"rescanning the relevant blocks (see -reindex option and rescanblockchain RPC).");
} else if (wallet.chain().hasAssumedValidChain()) {
error_msg += strprintf(" This error is likely caused by an in-progress assumeutxo "
"background sync. Check logs or getchainstates RPC for assumeutxo background "
"sync progress and try again later.");
} else {
error_msg += strprintf(" This error could potentially caused by data corruption. If "
"the issue persists you may want to reindex (see -reindex option).");
}
result.error = ImportError{
WalletErrorCode::MiscError,
Untranslated(error_msg),
/*is_wallet_error=*/false
};
}
}
}
}
return response;
}
} // namespace wallet