Bitcoin Core 32.99.0
P2P Digital Currency
interfaces.cpp
Go to the documentation of this file.
1// Copyright (c) 2018-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <interfaces/wallet.h>
6
7#include <common/args.h>
8#include <consensus/amount.h>
9#include <interfaces/chain.h>
10#include <interfaces/handler.h>
11#include <node/types.h>
13#include <pubkey.h>
14#include <rpc/server.h>
15#include <scheduler.h>
17#include <sync.h>
18#include <uint256.h>
19#include <util/check.h>
20#include <util/translation.h>
21#include <util/ui_change_type.h>
22#include <wallet/coincontrol.h>
23#include <wallet/context.h>
24#include <wallet/export.h>
25#include <wallet/feebumper.h>
26#include <wallet/fees.h>
27#include <wallet/imports.h>
28#include <wallet/load.h>
29#include <wallet/receive.h>
30#include <wallet/rpc/wallet.h>
31#include <wallet/spend.h>
32#include <wallet/scan.h>
33#include <wallet/wallet.h>
34
35#include <memory>
36#include <optional>
37#include <string>
38#include <utility>
39#include <vector>
40
54
55namespace wallet {
56// All members of the classes in this namespace are intentionally public, as the
57// classes themselves are private.
58namespace {
60WalletTx MakeWalletTx(CWallet& wallet, const CWalletTx& wtx)
61{
62 LOCK(wallet.cs_wallet);
63 WalletTx result;
64 result.tx = wtx.GetTx();
65 result.txin_is_mine.reserve(result.tx->vin.size());
66 for (const auto& txin : result.tx->vin) {
67 result.txin_is_mine.emplace_back(InputIsMine(wallet, txin));
68 }
69 result.txout_is_mine.reserve(result.tx->vout.size());
70 result.txout_address.reserve(result.tx->vout.size());
71 result.txout_address_is_mine.reserve(result.tx->vout.size());
72 for (const auto& txout : result.tx->vout) {
73 result.txout_is_mine.emplace_back(wallet.IsMine(txout));
74 result.txout_is_change.push_back(OutputIsChange(wallet, txout));
75 result.txout_address.emplace_back();
76 result.txout_address_is_mine.emplace_back(ExtractDestination(txout.scriptPubKey, result.txout_address.back()) ?
77 wallet.IsMine(result.txout_address.back()) :
78 false);
79 }
80 result.credit = CachedTxGetCredit(wallet, wtx, /*avoid_reuse=*/true);
81 result.debit = CachedTxGetDebit(wallet, wtx, /*avoid_reuse=*/true);
82 result.change = CachedTxGetChange(wallet, wtx);
83 result.time = wtx.GetTxTime();
84 result.from = wtx.m_from;
85 result.message = wtx.m_message;
86 result.comment = wtx.m_comment;
87 result.comment_to = wtx.m_comment_to;
88 result.is_coinbase = wtx.IsCoinBase();
89 return result;
90}
91
93WalletTxStatus MakeWalletTxStatus(const CWallet& wallet, const CWalletTx& wtx)
95{
96 AssertLockHeld(wallet.cs_wallet);
97
98 WalletTxStatus result;
99 result.block_height =
100 wtx.state<TxStateConfirmed>() ? wtx.state<TxStateConfirmed>()->confirmed_block_height :
101 wtx.state<TxStateBlockConflicted>() ? wtx.state<TxStateBlockConflicted>()->conflicting_block_height :
102 std::numeric_limits<int>::max();
103 result.blocks_to_maturity = wallet.GetTxBlocksToMaturity(wtx);
104 result.depth_in_main_chain = wallet.GetTxDepthInMainChain(wtx);
105 result.time_received = wtx.nTimeReceived;
106 result.lock_time = wtx.GetTx()->nLockTime;
107 result.is_trusted = CachedTxIsTrusted(wallet, wtx);
108 result.is_abandoned = wtx.isAbandoned();
109 result.is_coinbase = wtx.IsCoinBase();
110 result.is_in_main_chain = wtx.isConfirmed();
111 return result;
112}
113
115WalletTxOut MakeWalletTxOut(const CWallet& wallet,
116 const CWalletTx& wtx,
117 int n,
118 int depth) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
119{
120 WalletTxOut result;
121 result.txout = wtx.GetTx()->vout[n];
122 result.time = wtx.GetTxTime();
123 result.depth_in_main_chain = depth;
124 result.is_spent = wallet.IsSpent(COutPoint(wtx.GetHash(), n));
125 return result;
126}
127
128WalletTxOut MakeWalletTxOut(const CWallet& wallet,
129 const COutput& output) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
130{
131 WalletTxOut result;
132 result.txout = output.txout;
133 result.time = output.time;
134 result.depth_in_main_chain = output.depth;
135 result.is_spent = wallet.IsSpent(output.outpoint);
136 return result;
137}
138
139class WalletImpl : public Wallet
140{
141public:
142 explicit WalletImpl(WalletContext& context, const std::shared_ptr<CWallet>& wallet) : m_context(context), m_wallet(wallet) {}
143
144 bool encryptWallet(const SecureString& wallet_passphrase) override
145 {
146 return m_wallet->EncryptWallet(wallet_passphrase);
147 }
148 bool isCrypted() override { return m_wallet->HasEncryptionKeys(); }
149 bool lock() override { return m_wallet->Lock(); }
150 util::Expected<void, WalletError> unlock(const SecureString& wallet_passphrase) override { return m_wallet->Unlock(wallet_passphrase); }
151 bool isLocked() override { return m_wallet->IsLocked(); }
152 util::Expected<void, WalletError> changeWalletPassphrase(const SecureString& old_wallet_passphrase,
153 const SecureString& new_wallet_passphrase) override
154 {
155 return m_wallet->ChangeWalletPassphrase(old_wallet_passphrase, new_wallet_passphrase);
156 }
157 void abortRescan() override { m_wallet->Scanner().Abort(); }
158 bool backupWallet(const std::string& filename) override { return m_wallet->BackupWallet(filename); }
159 std::string getWalletName() override { return m_wallet->GetName(); }
160 util::Result<CTxDestination> getNewDestination(const OutputType type, const std::string& label) override
161 {
162 LOCK(m_wallet->cs_wallet);
163 return m_wallet->GetNewDestination(type, label);
164 }
165 bool getPubKey(const CScript& script, const CKeyID& address, CPubKey& pub_key) override
166 {
167 std::unique_ptr<SigningProvider> provider = m_wallet->GetSolvingProvider(script);
168 if (provider) {
169 return provider->GetPubKey(address, pub_key);
170 }
171 return false;
172 }
173 util::Expected<CExtPubKey, wallet::WalletError> addHDKey(const std::optional<CExtKey>& key) override
174 {
175 return m_wallet->AddHDKey(key);
176 }
177
178 SigningResult signMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) override
179 {
180 return m_wallet->SignMessage(message, pkhash, str_sig);
181 }
182 bool isSpendable(const CTxDestination& dest) override
183 {
184 LOCK(m_wallet->cs_wallet);
185 return m_wallet->IsMine(dest);
186 }
187 bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::optional<AddressPurpose>& purpose) override
188 {
189 return m_wallet->SetAddressBook(dest, name, purpose);
190 }
191 bool delAddressBook(const CTxDestination& dest) override
192 {
193 return m_wallet->DelAddressBook(dest);
194 }
195 bool getAddress(const CTxDestination& dest,
196 std::string* name,
197 AddressPurpose* purpose) override
198 {
199 LOCK(m_wallet->cs_wallet);
200 const auto& entry = m_wallet->FindAddressBookEntry(dest, /*allow_change=*/false);
201 if (!entry) return false; // addr not found
202 if (name) {
203 *name = entry->GetLabel();
204 }
205 if (purpose) {
206 // In very old wallets, address purpose may not be recorded so we derive it from IsMine
207 *purpose = entry->purpose.value_or(m_wallet->IsMine(dest) ? AddressPurpose::RECEIVE : AddressPurpose::SEND);
208 }
209 return true;
210 }
211 std::vector<WalletAddress> getAddresses() override
212 {
213 LOCK(m_wallet->cs_wallet);
214 std::vector<WalletAddress> result;
215 m_wallet->ForEachAddrBookEntry([&](const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose>& purpose) EXCLUSIVE_LOCKS_REQUIRED(m_wallet->cs_wallet) {
216 if (is_change) return;
217 bool is_mine = m_wallet->IsMine(dest);
218 // In very old wallets, address purpose may not be recorded so we derive it from IsMine
219 result.emplace_back(dest, is_mine, purpose.value_or(is_mine ? AddressPurpose::RECEIVE : AddressPurpose::SEND), label);
220 });
221 return result;
222 }
223 std::vector<std::string> getAddressReceiveRequests() override {
224 LOCK(m_wallet->cs_wallet);
225 return m_wallet->GetAddressReceiveRequests();
226 }
227 bool setAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& value) override {
228 // Note: The setAddressReceiveRequest interface used by the GUI to store
229 // receive requests is a little awkward and could be improved in the
230 // future:
231 //
232 // - The same method is used to save requests and erase them, but
233 // having separate methods could be clearer and prevent bugs.
234 //
235 // - Request ids are passed as strings even though they are generated as
236 // integers.
237 //
238 // - Multiple requests can be stored for the same address, but it might
239 // be better to only allow one request or only keep the current one.
240 LOCK(m_wallet->cs_wallet);
241 WalletBatch batch{m_wallet->GetDatabase()};
242 return value.empty() ? m_wallet->EraseAddressReceiveRequest(batch, dest, id)
243 : m_wallet->SetAddressReceiveRequest(batch, dest, id, value);
244 }
245 util::Result<void> displayAddress(const CTxDestination& dest) override
246 {
247 LOCK(m_wallet->cs_wallet);
248 return m_wallet->DisplayAddress(dest);
249 }
250 bool lockCoin(const COutPoint& output, const bool write_to_db) override
251 {
252 LOCK(m_wallet->cs_wallet);
253 return m_wallet->LockCoin(output, write_to_db);
254 }
255 bool unlockCoin(const COutPoint& output) override
256 {
257 LOCK(m_wallet->cs_wallet);
258 return m_wallet->UnlockCoin(output);
259 }
260 bool isLockedCoin(const COutPoint& output) override
261 {
262 LOCK(m_wallet->cs_wallet);
263 return m_wallet->IsLockedCoin(output);
264 }
265 void listLockedCoins(std::vector<COutPoint>& outputs) override
266 {
267 LOCK(m_wallet->cs_wallet);
268 return m_wallet->ListLockedCoins(outputs);
269 }
270 util::Result<wallet::CreatedTransactionResult> createTransaction(const std::vector<CRecipient>& recipients,
271 const CCoinControl& coin_control,
272 bool sign,
273 std::optional<unsigned int> change_pos) override
274 {
275 LOCK(m_wallet->cs_wallet);
276 return CreateTransaction(*m_wallet, recipients, change_pos, coin_control, sign);
277 }
278 void commitTransaction(CTransactionRef tx, const std::vector<std::string>& messages) override
279 {
280 LOCK(m_wallet->cs_wallet);
281 m_wallet->CommitTransaction(std::move(tx), /*replaces_txid=*/std::nullopt, /*comment=*/std::nullopt, /*comment_to=*/std::nullopt, messages);
282 }
283 bool transactionCanBeAbandoned(const Txid& txid) override { return m_wallet->TransactionCanBeAbandoned(txid); }
284 bool abandonTransaction(const Txid& txid) override
285 {
286 LOCK(m_wallet->cs_wallet);
287 return m_wallet->AbandonTransaction(txid);
288 }
289 bool transactionCanBeBumped(const Txid& txid) override
290 {
291 return feebumper::TransactionCanBeBumped(*m_wallet.get(), txid);
292 }
293 bool createBumpTransaction(const Txid& txid,
294 const CCoinControl& coin_control,
295 std::vector<bilingual_str>& errors,
296 CAmount& old_fee,
297 CAmount& new_fee,
298 CMutableTransaction& mtx) override
299 {
300 std::vector<CTxOut> outputs; // just an empty list of new recipients for now
301 return feebumper::CreateRateBumpTransaction(*m_wallet.get(), txid, coin_control, errors, old_fee, new_fee, mtx, /* require_mine= */ true, outputs) == feebumper::Result::OK;
302 }
303 bool signBumpTransaction(CMutableTransaction& mtx) override { return feebumper::SignTransaction(*m_wallet.get(), mtx); }
304 bool commitBumpTransaction(const Txid& txid,
306 std::vector<bilingual_str>& errors,
307 Txid& bumped_txid) override
308 {
309 return feebumper::CommitTransaction(*m_wallet.get(), txid, std::move(mtx), errors, bumped_txid) ==
311 }
312 CTransactionRef getTx(const Txid& txid) override
313 {
314 LOCK(m_wallet->cs_wallet);
315 auto mi = m_wallet->mapWallet.find(txid);
316 if (mi != m_wallet->mapWallet.end()) {
317 return mi->second.GetTx();
318 }
319 return {};
320 }
321 WalletTx getWalletTx(const Txid& txid) override
322 {
323 LOCK(m_wallet->cs_wallet);
324 auto mi = m_wallet->mapWallet.find(txid);
325 if (mi != m_wallet->mapWallet.end()) {
326 return MakeWalletTx(*m_wallet, mi->second);
327 }
328 return {};
329 }
330 std::set<WalletTx> getWalletTxs() override
331 {
332 LOCK(m_wallet->cs_wallet);
333 std::set<WalletTx> result;
334 for (const auto& entry : m_wallet->mapWallet) {
335 result.emplace(MakeWalletTx(*m_wallet, entry.second));
336 }
337 return result;
338 }
339 bool tryGetTxStatus(const Txid& txid,
341 int& num_blocks,
342 int64_t& block_time) override
343 {
344 TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
345 if (!locked_wallet) {
346 return false;
347 }
348 auto mi = m_wallet->mapWallet.find(txid);
349 if (mi == m_wallet->mapWallet.end()) {
350 return false;
351 }
352 num_blocks = m_wallet->GetLastBlockHeight();
353 block_time = -1;
354 CHECK_NONFATAL(m_wallet->chain().findBlock(m_wallet->GetLastBlockHash(), FoundBlock().time(block_time)));
355 tx_status = MakeWalletTxStatus(*m_wallet, mi->second);
356 return true;
357 }
358 WalletTx getWalletTxDetails(const Txid& txid,
359 WalletTxStatus& tx_status,
360 std::vector<std::string>& messages,
361 std::vector<std::string>& payment_requests,
362 bool& in_mempool,
363 int& num_blocks) override
364 {
365 LOCK(m_wallet->cs_wallet);
366 auto mi = m_wallet->mapWallet.find(txid);
367 if (mi != m_wallet->mapWallet.end()) {
368 num_blocks = m_wallet->GetLastBlockHeight();
369 in_mempool = mi->second.InMempool();
370 messages = mi->second.m_messages;
371 payment_requests = mi->second.m_payment_requests;
372 tx_status = MakeWalletTxStatus(*m_wallet, mi->second);
373 return MakeWalletTx(*m_wallet, mi->second);
374 }
375 return {};
376 }
377 std::optional<PSBTError> fillPSBT(const common::PSBTFillOptions& options,
378 size_t* n_signed,
380 bool& complete) override
381 {
382 return m_wallet->FillPSBT(psbtx, options, complete, n_signed);
383 }
384 std::vector<wallet::ImportResult> importDescriptors(std::vector<wallet::ImportDescriptorRequest>& requests) override
385 {
387 }
388 WalletBalances getBalances() override
389 {
390 const auto bal = GetBalance(*m_wallet);
391 WalletBalances result;
392 result.balance = bal.m_mine_trusted;
393 result.unconfirmed_balance = bal.m_mine_untrusted_pending;
394 result.immature_balance = bal.m_mine_immature;
395 result.used_balance = bal.m_mine_used;
396 result.nonmempool_balance = bal.m_mine_nonmempool;
397 return result;
398 }
399 bool tryGetBalances(WalletBalances& balances, uint256& block_hash) override
400 {
401 TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
402 if (!locked_wallet) {
403 return false;
404 }
405 block_hash = m_wallet->GetLastBlockHash();
406 balances = getBalances();
407 return true;
408 }
409 CAmount getBalance() override { return GetBalance(*m_wallet).m_mine_trusted; }
410 CAmount getAvailableBalance(const CCoinControl& coin_control) override
411 {
412 LOCK(m_wallet->cs_wallet);
413 CAmount total_amount = 0;
414 // Fetch selected coins total amount
415 if (coin_control.HasSelected()) {
417 CoinSelectionParams params(rng);
418 // Note: for now, swallow any error.
419 if (auto res = FetchSelectedInputs(*m_wallet, coin_control, params)) {
420 total_amount += res->GetTotalAmount();
421 }
422 }
423
424 // And fetch the wallet available coins
425 if (coin_control.m_allow_other_inputs) {
426 total_amount += AvailableCoins(*m_wallet, &coin_control).GetTotalAmount();
427 }
428
429 return total_amount;
430 }
431 bool txinIsMine(const CTxIn& txin) override
432 {
433 LOCK(m_wallet->cs_wallet);
434 return InputIsMine(*m_wallet, txin);
435 }
436 bool txoutIsMine(const CTxOut& txout) override
437 {
438 LOCK(m_wallet->cs_wallet);
439 return m_wallet->IsMine(txout);
440 }
441 CAmount getDebit(const CTxIn& txin) override
442 {
443 LOCK(m_wallet->cs_wallet);
444 return m_wallet->GetDebit(txin);
445 }
446 CAmount getCredit(const CTxOut& txout) override
447 {
448 LOCK(m_wallet->cs_wallet);
449 return OutputGetCredit(*m_wallet, txout);
450 }
451 CoinsList listCoins() override
452 {
453 LOCK(m_wallet->cs_wallet);
454 CoinsList result;
455 for (const auto& entry : ListCoins(*m_wallet)) {
456 auto& group = result[entry.first];
457 for (const auto& coin : entry.second) {
458 group.emplace_back(coin.outpoint,
459 MakeWalletTxOut(*m_wallet, coin));
460 }
461 }
462 return result;
463 }
464 std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) override
465 {
466 LOCK(m_wallet->cs_wallet);
467 std::vector<WalletTxOut> result;
468 result.reserve(outputs.size());
469 for (const auto& output : outputs) {
470 result.emplace_back();
471 auto it = m_wallet->mapWallet.find(output.hash);
472 if (it != m_wallet->mapWallet.end()) {
473 int depth = m_wallet->GetTxDepthInMainChain(it->second);
474 if (depth >= 0) {
475 result.back() = MakeWalletTxOut(*m_wallet, it->second, output.n, depth);
476 }
477 }
478 }
479 return result;
480 }
481 CAmount getRequiredFee(unsigned int tx_bytes) override { return GetRequiredFee(*m_wallet, tx_bytes); }
482 CAmount getMinimumFee(unsigned int tx_bytes,
483 const CCoinControl& coin_control,
484 std::optional<int>* returned_target,
485 FeeReason* reason) override
486 {
487 auto min_fee_rate{GetMinimumFeeRate(*m_wallet, coin_control)};
488 auto result = GetMinimumFee(min_fee_rate, tx_bytes);
489 if (returned_target) *returned_target = min_fee_rate.returned_target;
490 if (reason) *reason = min_fee_rate.fee_reason;
491 return result;
492 }
493 unsigned int getConfirmTarget() override { return m_wallet->m_confirm_target; }
494 bool hdEnabled() override { return m_wallet->IsHDEnabled(); }
495 bool canGetAddresses() override { return m_wallet->CanGetAddresses(); }
496 bool hasExternalSigner() override { return m_wallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER); }
497 bool privateKeysDisabled() override { return m_wallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS); }
498 bool taprootEnabled() override {
499 auto spk_man = m_wallet->GetScriptPubKeyMan(OutputType::BECH32M, /*internal=*/false);
500 return spk_man != nullptr;
501 }
502 OutputType getDefaultAddressType() override { return m_wallet->m_default_address_type; }
503 CAmount getMaxTxFee() override { return m_wallet->m_max_tx_fee; }
504 void remove() override
505 {
506 RemoveWallet(m_context, m_wallet, /*load_on_start=*/false);
507 }
508 std::unique_ptr<Handler> handleUnload(UnloadFn fn) override
509 {
510 return MakeSignalHandler(m_wallet->NotifyUnload.connect(fn));
511 }
512 std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
513 {
514 return MakeSignalHandler(m_wallet->ShowProgress.connect(fn));
515 }
516 std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override
517 {
518 return MakeSignalHandler(m_wallet->NotifyStatusChanged.connect([fn](CWallet*) { fn(); }));
519 }
520 std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override
521 {
522 return MakeSignalHandler(m_wallet->NotifyAddressBookChanged.connect(
523 [fn](const CTxDestination& address, const std::string& label, bool is_mine,
524 AddressPurpose purpose, ChangeType status) { fn(address, label, is_mine, purpose, status); }));
525 }
526 std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override
527 {
528 return MakeSignalHandler(m_wallet->NotifyTransactionChanged.connect(
529 [fn](const Txid& txid, ChangeType status) { fn(txid, status); }));
530 }
531 std::unique_ptr<Handler> handleCanGetAddressesChanged(CanGetAddressesChangedFn fn) override
532 {
533 return MakeSignalHandler(m_wallet->NotifyCanGetAddressesChanged.connect(fn));
534 }
535 CWallet* wallet() override { return m_wallet.get(); }
536
537 util::Result<std::string> exportWatchOnlyWallet(const fs::path& destination) override {
538 LOCK(m_wallet->cs_wallet);
539 m_wallet->TopUpKeyPool();
540 return ExportWatchOnlyWallet(*m_wallet, destination, m_context);
541 }
542
543 WalletContext& m_context;
544 std::shared_ptr<CWallet> m_wallet;
545};
546
547class WalletLoaderImpl : public WalletLoader
548{
549public:
550 WalletLoaderImpl(Chain& chain, ArgsManager& args)
551 {
552 m_context.chain = &chain;
553 m_context.args = &args;
554 }
555 ~WalletLoaderImpl() override { stop(); }
556
558 void registerRpcs() override
559 {
560 for (const CRPCCommand& command : GetWalletRPCCommands()) {
561 m_rpc_commands.emplace_back(command.category, command.name, [this, &command](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
562 JSONRPCRequest wallet_request = request;
563 wallet_request.context = &m_context;
564 return command.actor(wallet_request, result, last_handler);
565 }, command.argNames, command.unique_id);
566 m_rpc_commands.back().metadata_fn = command.metadata_fn;
567 m_rpc_handlers.emplace_back(m_context.chain->handleRpc(m_rpc_commands.back()));
568 }
569 }
570 bool verify() override { return VerifyWallets(m_context); }
571 bool load() override { return LoadWallets(m_context); }
572 void start(CScheduler& scheduler) override
573 {
574 m_context.scheduler = &scheduler;
575 return StartWallets(m_context);
576 }
577 void stop() override { return UnloadWallets(m_context); }
578 void setMockTime(int64_t time) override { return SetMockTime(std::chrono::seconds{time}); }
579 void schedulerMockForward(std::chrono::seconds delta) override { Assert(m_context.scheduler)->MockForward(delta); }
580
582 util::Result<std::unique_ptr<Wallet>> createWallet(const std::string& name, const SecureString& passphrase, uint64_t wallet_creation_flags, std::vector<bilingual_str>& warnings) override
583 {
584 DatabaseOptions options;
585 DatabaseStatus status;
586 ReadDatabaseArgs(*m_context.args, options);
587 options.require_create = true;
588 options.create_flags = wallet_creation_flags;
589 options.create_passphrase = passphrase;
590 bilingual_str error;
591 std::unique_ptr<Wallet> wallet{MakeWallet(m_context, CreateWallet(m_context, name, /*load_on_start=*/true, options, status, error, warnings))};
592 if (wallet) {
593 return wallet;
594 } else {
595 return util::Error{error};
596 }
597 }
598 util::Result<std::unique_ptr<Wallet>> loadWallet(const std::string& name, std::vector<bilingual_str>& warnings) override
599 {
600 DatabaseOptions options;
601 DatabaseStatus status;
602 ReadDatabaseArgs(*m_context.args, options);
603 options.require_existing = true;
604 bilingual_str error;
605 std::unique_ptr<Wallet> wallet{MakeWallet(m_context, LoadWallet(m_context, name, /*load_on_start=*/true, options, status, error, warnings))};
606 if (wallet) {
607 return wallet;
608 } else {
609 return util::Error{error};
610 }
611 }
612 util::Result<std::unique_ptr<Wallet>> restoreWallet(const fs::path& backup_file, const std::string& wallet_name, std::vector<bilingual_str>& warnings, bool load_after_restore) override
613 {
614 DatabaseStatus status;
615 bilingual_str error;
616 std::unique_ptr<Wallet> wallet{MakeWallet(m_context, RestoreWallet(m_context, backup_file, wallet_name, /*load_on_start=*/true, status, error, warnings, load_after_restore))};
617 if (!error.empty()) {
618 return util::Error{error};
619 }
620 return wallet;
621 }
622 util::Result<WalletMigrationResult> migrateWallet(const std::string& name, const SecureString& passphrase, bool load_wallet) override
623 {
624 auto res = wallet::MigrateLegacyToDescriptor(name, passphrase, m_context, load_wallet);
625 if (!res) return util::Error{util::ErrorString(res)};
627 .wallet = MakeWallet(m_context, res->wallet),
628 .watchonly_wallet_name = res->watchonly_wallet_name,
629 .solvables_wallet_name = res->solvables_wallet_name,
630 .backup_path = res->backup_path,
631 };
632 return out;
633 }
634 bool isEncrypted(const std::string& wallet_name) override
635 {
636 auto wallets{GetWallets(m_context)};
637 auto it = std::find_if(wallets.begin(), wallets.end(), [&](std::shared_ptr<CWallet> w){ return w->GetName() == wallet_name; });
638 if (it != wallets.end()) return (*it)->HasEncryptionKeys();
639
640 // Unloaded wallet, read db
641 DatabaseOptions options;
642 options.require_existing = true;
643 DatabaseStatus status;
644 bilingual_str error;
645 auto db = MakeWalletDatabase(wallet_name, options, status, error);
647 options.require_format = wallet::DatabaseFormat::BERKELEY_RO;
648 db = MakeWalletDatabase(wallet_name, options, status, error);
649 }
650 if (!db) return false;
651 return WalletBatch(*db).IsEncrypted();
652 }
653 std::string getWalletDir() override
654 {
656 }
657 std::vector<std::pair<std::string, std::string>> listWalletDir() override
658 {
659 std::vector<std::pair<std::string, std::string>> paths;
660 for (auto& [path, format] : ListDatabases(GetWalletDir())) {
661 paths.emplace_back(fs::PathToString(path), format);
662 }
663 return paths;
664 }
665 std::vector<std::unique_ptr<Wallet>> getWallets() override
666 {
667 std::vector<std::unique_ptr<Wallet>> wallets;
668 for (const auto& wallet : GetWallets(m_context)) {
669 wallets.emplace_back(MakeWallet(m_context, wallet));
670 }
671 return wallets;
672 }
673 std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
674 {
675 return HandleLoadWallet(m_context, std::move(fn));
676 }
677 WalletContext* context() override { return &m_context; }
678
679 WalletContext m_context;
680 const std::vector<std::string> m_wallet_filenames;
681 std::vector<std::unique_ptr<Handler>> m_rpc_handlers;
682 std::list<CRPCCommand> m_rpc_commands;
683};
684} // namespace
685} // namespace wallet
686
687namespace interfaces {
688std::unique_ptr<Wallet> MakeWallet(wallet::WalletContext& context, const std::shared_ptr<wallet::CWallet>& wallet) { return wallet ? std::make_unique<wallet::WalletImpl>(context, wallet) : nullptr; }
689
690std::unique_ptr<WalletLoader> MakeWalletLoader(Chain& chain, ArgsManager& args)
691{
692 return std::make_unique<wallet::WalletLoaderImpl>(chain, args);
693}
694} // namespace interfaces
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
Definition: addresstype.cpp:49
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
const auto command
ArgsManager & args
Definition: bitcoind.cpp:280
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:112
#define Assert(val)
Identity function.
Definition: check.h:116
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:29
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:30
uint32_t n
Definition: transaction.h:33
Txid hash
Definition: transaction.h:32
An encapsulated public key.
Definition: pubkey.h:43
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:39
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
An input of a transaction.
Definition: transaction.h:63
An output of a transaction.
Definition: transaction.h:141
Fast randomness source.
Definition: random.h:386
A version of CTransaction with the PSBT format.
Definition: psbt.h:1239
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:117
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:52
Generic interface for managing an event handler or callback function registered with another interfac...
Definition: handler.h:21
Interface for accessing a wallet.
Definition: wallet.h:65
Wallet chain client that in addition to having chain client methods for starting up,...
Definition: wallet.h:325
256-bit opaque blob.
Definition: uint256.h:196
The util::Expected class provides a standard way for low-level functions to return either error value...
Definition: expected.h:44
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:160
static int sign(const secp256k1_context *ctx, struct signer_secrets *signer_secrets, struct signer *signer, const secp256k1_musig_keyagg_cache *cache, const unsigned char *msg32, unsigned char *sig64)
Definition: musig.c:106
PSBTError
Definition: types.h:19
std::unique_ptr< WalletLoader > MakeWalletLoader(Chain &chain, ArgsManager &args)
Return implementation of ChainClient interface for a wallet loader.
Definition: dummywallet.cpp:60
std::unique_ptr< Handler > MakeSignalHandler(btcsignals::connection connection)
Return handler wrapping a btcsignals connection.
Definition: interfaces.cpp:48
std::unique_ptr< Wallet > MakeWallet(wallet::WalletContext &context, const std::shared_ptr< wallet::CWallet > &wallet)
Return implementation of Wallet interface.
Definition: interfaces.cpp:688
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
Result CreateRateBumpTransaction(CWallet &wallet, const Txid &txid, const CCoinControl &coin_control, std::vector< bilingual_str > &errors, CAmount &old_fee, CAmount &new_fee, CMutableTransaction &mtx, bool require_mine, const std::vector< CTxOut > &outputs, std::optional< uint32_t > original_change_index)
Create bumpfee transaction based on feerate estimates.
Definition: feebumper.cpp:167
bool TransactionCanBeBumped(const CWallet &wallet, const Txid &txid)
Return whether transaction can be bumped.
Definition: feebumper.cpp:156
bool SignTransaction(CWallet &wallet, CMutableTransaction &mtx)
Sign the new transaction,.
Definition: feebumper.cpp:339
Result CommitTransaction(CWallet &wallet, const Txid &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, Txid &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:359
void StartWallets(WalletContext &context)
Complete startup of wallets.
Definition: load.cpp:167
bool OutputIsChange(const CWallet &wallet, const CTxOut &txout)
Definition: receive.cpp:74
void ReadDatabaseArgs(const ArgsManager &args, DatabaseOptions &options)
Definition: db.cpp:153
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:321
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, std::optional< unsigned 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:1448
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:206
util::Result< MigrationResult > MigrateLegacyToDescriptor(const std::string &wallet_name, const SecureString &passphrase, WalletContext &context, bool load_wallet)
Do all steps to migrate a legacy wallet to a descriptor wallet.
Definition: wallet.cpp:4174
util::Result< CoinsResult > FetchSelectedInputs(const CWallet &wallet, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params)
Fetch and validate coin control selected inputs.
Definition: spend.cpp:265
bool CachedTxIsTrusted(const CWallet &wallet, const CWalletTx &wtx, std::set< Txid > &trusted_parents)
Definition: receive.cpp:205
MinimumFeeRateResult GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control)
Estimate the minimum fee rate considering user set parameters and the required fee.
Definition: fees.cpp:32
std::vector< ImportResult > ProcessDescriptorsImport(CWallet &wallet, std::vector< ImportDescriptorRequest > &requests)
Definition: imports.cpp:222
CAmount GetMinimumFee(const MinimumFeeRateResult &min_fee_rate, unsigned int nTxBytes)
Return the minimum fee for this size given a fee rate result.
Definition: fees.cpp:22
bool VerifyWallets(WalletContext &context)
Responsible for reading and validating the -wallet arguments and verifying the wallet database.
Definition: load.cpp:27
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:228
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:13
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2766
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
Definition: spend.cpp:544
CAmount CachedTxGetDebit(const CWallet &wallet, const CWalletTx &wtx, bool avoid_reuse)
Definition: receive.cpp:122
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)
Definition: wallet.cpp:406
CAmount CachedTxGetChange(const CWallet &wallet, const CWalletTx &wtx)
Definition: receive.cpp:130
CAmount CachedTxGetCredit(const CWallet &wallet, const CWalletTx &wtx, bool avoid_reuse)
Definition: receive.cpp:110
AddressPurpose
Address purpose field that has been been stored with wallet sending and receiving addresses since BIP...
Definition: types.h:44
util::Result< std::string > ExportWatchOnlyWallet(const CWallet &wallet, const fs::path &destination, WalletContext &context)
Make a new watchonly wallet file containing the public descriptors from this wallet The exported watc...
Definition: export.cpp:47
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse, bool include_nonmempool)
Definition: receive.cpp:245
void UnloadWallets(WalletContext &context)
Definition: load.cpp:176
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:334
bool LoadWallets(WalletContext &context)
Load wallet databases.
Definition: load.cpp:118
@ WALLET_FLAG_EXTERNAL_SIGNER
Indicates that the wallet needs an external signer.
Definition: walletutil.h:56
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:30
CAmount GetRequiredFee(const CWallet &wallet, unsigned int nTxBytes)
Return the minimum required absolute fee for this size based on the required fee rate.
Definition: fees.cpp:16
std::span< const CRPCCommand > GetWalletRPCCommands()
Definition: wallet.cpp:1119
bool InputIsMine(const CWallet &wallet, const CTxIn &txin)
Definition: receive.cpp:13
CTxDestination getNewDestination(CWallet &w, OutputType output_type)
Returns a new destination, of an specific type, from the wallet.
Definition: util.cpp:112
CAmount OutputGetCredit(const CWallet &wallet, const CTxOut &txout)
Definition: receive.cpp:32
std::vector< std::pair< fs::path, std::string > > ListDatabases(const fs::path &wallet_dir)
Recursively list database paths in directory.
Definition: db.cpp:23
DatabaseStatus
Definition: db.h:180
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:175
CoinsResult AvailableCoins(const CWallet &wallet, const CCoinControl *coinControl, std::optional< CFeeRate > feerate, const CoinFilterParams &params)
Populate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
Definition: spend.cpp:316
NodeContext * m_context
Definition: interfaces.cpp:439
is a home for public enum and struct type definitions that are used internally by node code,...
OutputType
Definition: outputtype.h:18
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:417
const char * name
Definition: rest.cpp:71
static bool verify(const CScriptNum10 &bignum, const CScriptNum &scriptnum)
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:53
static RPCMethod stop()
Definition: server.cpp:156
SigningResult
Definition: signmessage.h:43
A mutable version of CTransaction.
Definition: transaction.h:372
Bilingual messages:
Definition: translation.h:24
bool empty() const
Definition: translation.h:35
Instructions for how a PSBT should be signed or filled with information.
Definition: types.h:31
Information about one wallet address.
Definition: wallet.h:363
Collection of wallet balances.
Definition: wallet.h:377
Migrated wallet info.
Definition: wallet.h:439
std::vector< bool > txin_is_mine
Definition: wallet.h:396
std::optional< std::string > comment
Definition: wallet.h:407
std::vector< CTxDestination > txout_address
Definition: wallet.h:399
std::vector< bool > txout_address_is_mine
Definition: wallet.h:400
CTransactionRef tx
Definition: wallet.h:395
std::optional< std::string > comment_to
Definition: wallet.h:408
std::vector< bool > txout_is_change
Definition: wallet.h:398
std::vector< bool > txout_is_mine
Definition: wallet.h:397
std::optional< std::string > message
Definition: wallet.h:406
std::optional< std::string > from
Definition: wallet.h:405
Wallet transaction output.
Definition: wallet.h:430
Updated transaction status.
Definition: wallet.h:416
unsigned int time_received
Definition: wallet.h:420
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: receive.h:47
CAmount GetTotalAmount() const
Definition: spend.h:60
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:36
#define LOCK(cs)
Definition: sync.h:268
#define TRY_LOCK(cs, name)
Definition: sync.h:273
CDBWrapper db
Definition: dbwrapper.cpp:371
FastRandomContext rng
Definition: dbwrapper.cpp:413
FuzzedDataProvider provider
Definition: dbwrapper.cpp:366
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
ChangeType
General change type (added, updated, removed).
Definition: ui_change_type.h:9
FeeReason
Definition: fees.h:24
void SetMockTime(std::chrono::time_point< NodeClock, std::chrono::seconds > mock)
Definition: time.cpp:52
AssertLockHeld(pool.cs)
std::list< CRPCCommand > m_rpc_commands
Definition: interfaces.cpp:682
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:544
std::vector< std::unique_ptr< Handler > > m_rpc_handlers
Definition: interfaces.cpp:681
const std::vector< std::string > m_wallet_filenames
Definition: interfaces.cpp:680
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:83
std::shared_ptr< CWallet > wallet
WalletContext context