Bitcoin Core 31.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>
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/load.h>
28#include <wallet/receive.h>
29#include <wallet/rpc/wallet.h>
30#include <wallet/spend.h>
31#include <wallet/wallet.h>
32
33#include <memory>
34#include <string>
35#include <utility>
36#include <vector>
37
51
52namespace wallet {
53// All members of the classes in this namespace are intentionally public, as the
54// classes themselves are private.
55namespace {
57WalletTx MakeWalletTx(CWallet& wallet, const CWalletTx& wtx)
58{
59 LOCK(wallet.cs_wallet);
60 WalletTx result;
61 result.tx = wtx.GetTx();
62 result.txin_is_mine.reserve(result.tx->vin.size());
63 for (const auto& txin : result.tx->vin) {
64 result.txin_is_mine.emplace_back(InputIsMine(wallet, txin));
65 }
66 result.txout_is_mine.reserve(result.tx->vout.size());
67 result.txout_address.reserve(result.tx->vout.size());
68 result.txout_address_is_mine.reserve(result.tx->vout.size());
69 for (const auto& txout : result.tx->vout) {
70 result.txout_is_mine.emplace_back(wallet.IsMine(txout));
71 result.txout_is_change.push_back(OutputIsChange(wallet, txout));
72 result.txout_address.emplace_back();
73 result.txout_address_is_mine.emplace_back(ExtractDestination(txout.scriptPubKey, result.txout_address.back()) ?
74 wallet.IsMine(result.txout_address.back()) :
75 false);
76 }
77 result.credit = CachedTxGetCredit(wallet, wtx, /*avoid_reuse=*/true);
78 result.debit = CachedTxGetDebit(wallet, wtx, /*avoid_reuse=*/true);
79 result.change = CachedTxGetChange(wallet, wtx);
80 result.time = wtx.GetTxTime();
81 result.from = wtx.m_from;
82 result.message = wtx.m_message;
83 result.comment = wtx.m_comment;
84 result.comment_to = wtx.m_comment_to;
85 result.is_coinbase = wtx.IsCoinBase();
86 return result;
87}
88
90WalletTxStatus MakeWalletTxStatus(const CWallet& wallet, const CWalletTx& wtx)
92{
93 AssertLockHeld(wallet.cs_wallet);
94
95 WalletTxStatus result;
96 result.block_height =
97 wtx.state<TxStateConfirmed>() ? wtx.state<TxStateConfirmed>()->confirmed_block_height :
98 wtx.state<TxStateBlockConflicted>() ? wtx.state<TxStateBlockConflicted>()->conflicting_block_height :
99 std::numeric_limits<int>::max();
100 result.blocks_to_maturity = wallet.GetTxBlocksToMaturity(wtx);
101 result.depth_in_main_chain = wallet.GetTxDepthInMainChain(wtx);
102 result.time_received = wtx.nTimeReceived;
103 result.lock_time = wtx.GetTx()->nLockTime;
104 result.is_trusted = CachedTxIsTrusted(wallet, wtx);
105 result.is_abandoned = wtx.isAbandoned();
106 result.is_coinbase = wtx.IsCoinBase();
107 result.is_in_main_chain = wtx.isConfirmed();
108 return result;
109}
110
112WalletTxOut MakeWalletTxOut(const CWallet& wallet,
113 const CWalletTx& wtx,
114 int n,
115 int depth) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
116{
117 WalletTxOut result;
118 result.txout = wtx.GetTx()->vout[n];
119 result.time = wtx.GetTxTime();
120 result.depth_in_main_chain = depth;
121 result.is_spent = wallet.IsSpent(COutPoint(wtx.GetHash(), n));
122 return result;
123}
124
125WalletTxOut MakeWalletTxOut(const CWallet& wallet,
126 const COutput& output) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
127{
128 WalletTxOut result;
129 result.txout = output.txout;
130 result.time = output.time;
131 result.depth_in_main_chain = output.depth;
132 result.is_spent = wallet.IsSpent(output.outpoint);
133 return result;
134}
135
136class WalletImpl : public Wallet
137{
138public:
139 explicit WalletImpl(WalletContext& context, const std::shared_ptr<CWallet>& wallet) : m_context(context), m_wallet(wallet) {}
140
141 bool encryptWallet(const SecureString& wallet_passphrase) override
142 {
143 return m_wallet->EncryptWallet(wallet_passphrase);
144 }
145 bool isCrypted() override { return m_wallet->HasEncryptionKeys(); }
146 bool lock() override { return m_wallet->Lock(); }
147 bool unlock(const SecureString& wallet_passphrase) override { return m_wallet->Unlock(wallet_passphrase); }
148 bool isLocked() override { return m_wallet->IsLocked(); }
149 bool changeWalletPassphrase(const SecureString& old_wallet_passphrase,
150 const SecureString& new_wallet_passphrase) override
151 {
152 return m_wallet->ChangeWalletPassphrase(old_wallet_passphrase, new_wallet_passphrase);
153 }
154 void abortRescan() override { m_wallet->AbortRescan(); }
155 bool backupWallet(const std::string& filename) override { return m_wallet->BackupWallet(filename); }
156 std::string getWalletName() override { return m_wallet->GetName(); }
157 util::Result<CTxDestination> getNewDestination(const OutputType type, const std::string& label) override
158 {
159 LOCK(m_wallet->cs_wallet);
160 return m_wallet->GetNewDestination(type, label);
161 }
162 bool getPubKey(const CScript& script, const CKeyID& address, CPubKey& pub_key) override
163 {
164 std::unique_ptr<SigningProvider> provider = m_wallet->GetSolvingProvider(script);
165 if (provider) {
166 return provider->GetPubKey(address, pub_key);
167 }
168 return false;
169 }
170 SigningResult signMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) override
171 {
172 return m_wallet->SignMessage(message, pkhash, str_sig);
173 }
174 bool isSpendable(const CTxDestination& dest) override
175 {
176 LOCK(m_wallet->cs_wallet);
177 return m_wallet->IsMine(dest);
178 }
179 bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::optional<AddressPurpose>& purpose) override
180 {
181 return m_wallet->SetAddressBook(dest, name, purpose);
182 }
183 bool delAddressBook(const CTxDestination& dest) override
184 {
185 return m_wallet->DelAddressBook(dest);
186 }
187 bool getAddress(const CTxDestination& dest,
188 std::string* name,
189 AddressPurpose* purpose) override
190 {
191 LOCK(m_wallet->cs_wallet);
192 const auto& entry = m_wallet->FindAddressBookEntry(dest, /*allow_change=*/false);
193 if (!entry) return false; // addr not found
194 if (name) {
195 *name = entry->GetLabel();
196 }
197 if (purpose) {
198 // In very old wallets, address purpose may not be recorded so we derive it from IsMine
199 *purpose = entry->purpose.value_or(m_wallet->IsMine(dest) ? AddressPurpose::RECEIVE : AddressPurpose::SEND);
200 }
201 return true;
202 }
203 std::vector<WalletAddress> getAddresses() override
204 {
205 LOCK(m_wallet->cs_wallet);
206 std::vector<WalletAddress> result;
207 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) {
208 if (is_change) return;
209 bool is_mine = m_wallet->IsMine(dest);
210 // In very old wallets, address purpose may not be recorded so we derive it from IsMine
211 result.emplace_back(dest, is_mine, purpose.value_or(is_mine ? AddressPurpose::RECEIVE : AddressPurpose::SEND), label);
212 });
213 return result;
214 }
215 std::vector<std::string> getAddressReceiveRequests() override {
216 LOCK(m_wallet->cs_wallet);
217 return m_wallet->GetAddressReceiveRequests();
218 }
219 bool setAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& value) override {
220 // Note: The setAddressReceiveRequest interface used by the GUI to store
221 // receive requests is a little awkward and could be improved in the
222 // future:
223 //
224 // - The same method is used to save requests and erase them, but
225 // having separate methods could be clearer and prevent bugs.
226 //
227 // - Request ids are passed as strings even though they are generated as
228 // integers.
229 //
230 // - Multiple requests can be stored for the same address, but it might
231 // be better to only allow one request or only keep the current one.
232 LOCK(m_wallet->cs_wallet);
233 WalletBatch batch{m_wallet->GetDatabase()};
234 return value.empty() ? m_wallet->EraseAddressReceiveRequest(batch, dest, id)
235 : m_wallet->SetAddressReceiveRequest(batch, dest, id, value);
236 }
237 util::Result<void> displayAddress(const CTxDestination& dest) override
238 {
239 LOCK(m_wallet->cs_wallet);
240 return m_wallet->DisplayAddress(dest);
241 }
242 bool lockCoin(const COutPoint& output, const bool write_to_db) override
243 {
244 LOCK(m_wallet->cs_wallet);
245 return m_wallet->LockCoin(output, write_to_db);
246 }
247 bool unlockCoin(const COutPoint& output) override
248 {
249 LOCK(m_wallet->cs_wallet);
250 return m_wallet->UnlockCoin(output);
251 }
252 bool isLockedCoin(const COutPoint& output) override
253 {
254 LOCK(m_wallet->cs_wallet);
255 return m_wallet->IsLockedCoin(output);
256 }
257 void listLockedCoins(std::vector<COutPoint>& outputs) override
258 {
259 LOCK(m_wallet->cs_wallet);
260 return m_wallet->ListLockedCoins(outputs);
261 }
262 util::Result<wallet::CreatedTransactionResult> createTransaction(const std::vector<CRecipient>& recipients,
263 const CCoinControl& coin_control,
264 bool sign,
265 std::optional<unsigned int> change_pos) override
266 {
267 LOCK(m_wallet->cs_wallet);
268 return CreateTransaction(*m_wallet, recipients, change_pos, coin_control, sign);
269 }
270 void commitTransaction(CTransactionRef tx, const std::vector<std::string>& messages) override
271 {
272 LOCK(m_wallet->cs_wallet);
273 m_wallet->CommitTransaction(std::move(tx), /*replaces_txid=*/std::nullopt, /*comment=*/std::nullopt, /*comment_to=*/std::nullopt, messages);
274 }
275 bool transactionCanBeAbandoned(const Txid& txid) override { return m_wallet->TransactionCanBeAbandoned(txid); }
276 bool abandonTransaction(const Txid& txid) override
277 {
278 LOCK(m_wallet->cs_wallet);
279 return m_wallet->AbandonTransaction(txid);
280 }
281 bool transactionCanBeBumped(const Txid& txid) override
282 {
283 return feebumper::TransactionCanBeBumped(*m_wallet.get(), txid);
284 }
285 bool createBumpTransaction(const Txid& txid,
286 const CCoinControl& coin_control,
287 std::vector<bilingual_str>& errors,
288 CAmount& old_fee,
289 CAmount& new_fee,
290 CMutableTransaction& mtx) override
291 {
292 std::vector<CTxOut> outputs; // just an empty list of new recipients for now
293 return feebumper::CreateRateBumpTransaction(*m_wallet.get(), txid, coin_control, errors, old_fee, new_fee, mtx, /* require_mine= */ true, outputs) == feebumper::Result::OK;
294 }
295 bool signBumpTransaction(CMutableTransaction& mtx) override { return feebumper::SignTransaction(*m_wallet.get(), mtx); }
296 bool commitBumpTransaction(const Txid& txid,
298 std::vector<bilingual_str>& errors,
299 Txid& bumped_txid) override
300 {
301 return feebumper::CommitTransaction(*m_wallet.get(), txid, std::move(mtx), errors, bumped_txid) ==
303 }
304 CTransactionRef getTx(const Txid& txid) override
305 {
306 LOCK(m_wallet->cs_wallet);
307 auto mi = m_wallet->mapWallet.find(txid);
308 if (mi != m_wallet->mapWallet.end()) {
309 return mi->second.GetTx();
310 }
311 return {};
312 }
313 WalletTx getWalletTx(const Txid& txid) override
314 {
315 LOCK(m_wallet->cs_wallet);
316 auto mi = m_wallet->mapWallet.find(txid);
317 if (mi != m_wallet->mapWallet.end()) {
318 return MakeWalletTx(*m_wallet, mi->second);
319 }
320 return {};
321 }
322 std::set<WalletTx> getWalletTxs() override
323 {
324 LOCK(m_wallet->cs_wallet);
325 std::set<WalletTx> result;
326 for (const auto& entry : m_wallet->mapWallet) {
327 result.emplace(MakeWalletTx(*m_wallet, entry.second));
328 }
329 return result;
330 }
331 bool tryGetTxStatus(const Txid& txid,
333 int& num_blocks,
334 int64_t& block_time) override
335 {
336 TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
337 if (!locked_wallet) {
338 return false;
339 }
340 auto mi = m_wallet->mapWallet.find(txid);
341 if (mi == m_wallet->mapWallet.end()) {
342 return false;
343 }
344 num_blocks = m_wallet->GetLastBlockHeight();
345 block_time = -1;
346 CHECK_NONFATAL(m_wallet->chain().findBlock(m_wallet->GetLastBlockHash(), FoundBlock().time(block_time)));
347 tx_status = MakeWalletTxStatus(*m_wallet, mi->second);
348 return true;
349 }
350 WalletTx getWalletTxDetails(const Txid& txid,
351 WalletTxStatus& tx_status,
352 std::vector<std::string>& messages,
353 std::vector<std::string>& payment_requests,
354 bool& in_mempool,
355 int& num_blocks) override
356 {
357 LOCK(m_wallet->cs_wallet);
358 auto mi = m_wallet->mapWallet.find(txid);
359 if (mi != m_wallet->mapWallet.end()) {
360 num_blocks = m_wallet->GetLastBlockHeight();
361 in_mempool = mi->second.InMempool();
362 messages = mi->second.m_messages;
363 payment_requests = mi->second.m_payment_requests;
364 tx_status = MakeWalletTxStatus(*m_wallet, mi->second);
365 return MakeWalletTx(*m_wallet, mi->second);
366 }
367 return {};
368 }
369 std::optional<PSBTError> fillPSBT(const common::PSBTFillOptions& options,
370 size_t* n_signed,
372 bool& complete) override
373 {
374 return m_wallet->FillPSBT(psbtx, options, complete, n_signed);
375 }
376 WalletBalances getBalances() override
377 {
378 const auto bal = GetBalance(*m_wallet);
379 WalletBalances result;
380 result.balance = bal.m_mine_trusted;
381 result.unconfirmed_balance = bal.m_mine_untrusted_pending;
382 result.immature_balance = bal.m_mine_immature;
383 result.used_balance = bal.m_mine_used;
384 result.nonmempool_balance = bal.m_mine_nonmempool;
385 return result;
386 }
387 bool tryGetBalances(WalletBalances& balances, uint256& block_hash) override
388 {
389 TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
390 if (!locked_wallet) {
391 return false;
392 }
393 block_hash = m_wallet->GetLastBlockHash();
394 balances = getBalances();
395 return true;
396 }
397 CAmount getBalance() override { return GetBalance(*m_wallet).m_mine_trusted; }
398 CAmount getAvailableBalance(const CCoinControl& coin_control) override
399 {
400 LOCK(m_wallet->cs_wallet);
401 CAmount total_amount = 0;
402 // Fetch selected coins total amount
403 if (coin_control.HasSelected()) {
405 CoinSelectionParams params(rng);
406 // Note: for now, swallow any error.
407 if (auto res = FetchSelectedInputs(*m_wallet, coin_control, params)) {
408 total_amount += res->GetTotalAmount();
409 }
410 }
411
412 // And fetch the wallet available coins
413 if (coin_control.m_allow_other_inputs) {
414 total_amount += AvailableCoins(*m_wallet, &coin_control).GetTotalAmount();
415 }
416
417 return total_amount;
418 }
419 bool txinIsMine(const CTxIn& txin) override
420 {
421 LOCK(m_wallet->cs_wallet);
422 return InputIsMine(*m_wallet, txin);
423 }
424 bool txoutIsMine(const CTxOut& txout) override
425 {
426 LOCK(m_wallet->cs_wallet);
427 return m_wallet->IsMine(txout);
428 }
429 CAmount getDebit(const CTxIn& txin) override
430 {
431 LOCK(m_wallet->cs_wallet);
432 return m_wallet->GetDebit(txin);
433 }
434 CAmount getCredit(const CTxOut& txout) override
435 {
436 LOCK(m_wallet->cs_wallet);
437 return OutputGetCredit(*m_wallet, txout);
438 }
439 CoinsList listCoins() override
440 {
441 LOCK(m_wallet->cs_wallet);
442 CoinsList result;
443 for (const auto& entry : ListCoins(*m_wallet)) {
444 auto& group = result[entry.first];
445 for (const auto& coin : entry.second) {
446 group.emplace_back(coin.outpoint,
447 MakeWalletTxOut(*m_wallet, coin));
448 }
449 }
450 return result;
451 }
452 std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) override
453 {
454 LOCK(m_wallet->cs_wallet);
455 std::vector<WalletTxOut> result;
456 result.reserve(outputs.size());
457 for (const auto& output : outputs) {
458 result.emplace_back();
459 auto it = m_wallet->mapWallet.find(output.hash);
460 if (it != m_wallet->mapWallet.end()) {
461 int depth = m_wallet->GetTxDepthInMainChain(it->second);
462 if (depth >= 0) {
463 result.back() = MakeWalletTxOut(*m_wallet, it->second, output.n, depth);
464 }
465 }
466 }
467 return result;
468 }
469 CAmount getRequiredFee(unsigned int tx_bytes) override { return GetRequiredFee(*m_wallet, tx_bytes); }
470 CAmount getMinimumFee(unsigned int tx_bytes,
471 const CCoinControl& coin_control,
472 int* returned_target,
473 FeeReason* reason) override
474 {
475 FeeCalculation fee_calc;
476 CAmount result;
477 result = GetMinimumFee(*m_wallet, tx_bytes, coin_control, &fee_calc);
478 if (returned_target) *returned_target = fee_calc.returnedTarget;
479 if (reason) *reason = fee_calc.reason;
480 return result;
481 }
482 unsigned int getConfirmTarget() override { return m_wallet->m_confirm_target; }
483 bool hdEnabled() override { return m_wallet->IsHDEnabled(); }
484 bool canGetAddresses() override { return m_wallet->CanGetAddresses(); }
485 bool hasExternalSigner() override { return m_wallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER); }
486 bool privateKeysDisabled() override { return m_wallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS); }
487 bool taprootEnabled() override {
488 auto spk_man = m_wallet->GetScriptPubKeyMan(OutputType::BECH32M, /*internal=*/false);
489 return spk_man != nullptr;
490 }
491 OutputType getDefaultAddressType() override { return m_wallet->m_default_address_type; }
492 CAmount getDefaultMaxTxFee() override { return m_wallet->m_default_max_tx_fee; }
493 void remove() override
494 {
495 RemoveWallet(m_context, m_wallet, /*load_on_start=*/false);
496 }
497 std::unique_ptr<Handler> handleUnload(UnloadFn fn) override
498 {
499 return MakeSignalHandler(m_wallet->NotifyUnload.connect(fn));
500 }
501 std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
502 {
503 return MakeSignalHandler(m_wallet->ShowProgress.connect(fn));
504 }
505 std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override
506 {
507 return MakeSignalHandler(m_wallet->NotifyStatusChanged.connect([fn](CWallet*) { fn(); }));
508 }
509 std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override
510 {
511 return MakeSignalHandler(m_wallet->NotifyAddressBookChanged.connect(
512 [fn](const CTxDestination& address, const std::string& label, bool is_mine,
513 AddressPurpose purpose, ChangeType status) { fn(address, label, is_mine, purpose, status); }));
514 }
515 std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override
516 {
517 return MakeSignalHandler(m_wallet->NotifyTransactionChanged.connect(
518 [fn](const Txid& txid, ChangeType status) { fn(txid, status); }));
519 }
520 std::unique_ptr<Handler> handleCanGetAddressesChanged(CanGetAddressesChangedFn fn) override
521 {
522 return MakeSignalHandler(m_wallet->NotifyCanGetAddressesChanged.connect(fn));
523 }
524 CWallet* wallet() override { return m_wallet.get(); }
525
526 util::Result<std::string> exportWatchOnlyWallet(const fs::path& destination) override {
527 LOCK(m_wallet->cs_wallet);
528 m_wallet->TopUpKeyPool();
529 return ExportWatchOnlyWallet(*m_wallet, destination, m_context);
530 }
531
532 WalletContext& m_context;
533 std::shared_ptr<CWallet> m_wallet;
534};
535
536class WalletLoaderImpl : public WalletLoader
537{
538public:
539 WalletLoaderImpl(Chain& chain, ArgsManager& args)
540 {
541 m_context.chain = &chain;
542 m_context.args = &args;
543 }
544 ~WalletLoaderImpl() override { stop(); }
545
547 void registerRpcs() override
548 {
549 for (const CRPCCommand& command : GetWalletRPCCommands()) {
550 m_rpc_commands.emplace_back(command.category, command.name, [this, &command](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
551 JSONRPCRequest wallet_request = request;
552 wallet_request.context = &m_context;
553 return command.actor(wallet_request, result, last_handler);
554 }, command.argNames, command.unique_id);
555 m_rpc_commands.back().metadata_fn = command.metadata_fn;
556 m_rpc_handlers.emplace_back(m_context.chain->handleRpc(m_rpc_commands.back()));
557 }
558 }
559 bool verify() override { return VerifyWallets(m_context); }
560 bool load() override { return LoadWallets(m_context); }
561 void start(CScheduler& scheduler) override
562 {
563 m_context.scheduler = &scheduler;
564 return StartWallets(m_context);
565 }
566 void stop() override { return UnloadWallets(m_context); }
567 void setMockTime(int64_t time) override { return SetMockTime(time); }
568 void schedulerMockForward(std::chrono::seconds delta) override { Assert(m_context.scheduler)->MockForward(delta); }
569
571 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
572 {
573 DatabaseOptions options;
574 DatabaseStatus status;
575 ReadDatabaseArgs(*m_context.args, options);
576 options.require_create = true;
577 options.create_flags = wallet_creation_flags;
578 options.create_passphrase = passphrase;
579 bilingual_str error;
580 std::unique_ptr<Wallet> wallet{MakeWallet(m_context, CreateWallet(m_context, name, /*load_on_start=*/true, options, status, error, warnings))};
581 if (wallet) {
582 return wallet;
583 } else {
584 return util::Error{error};
585 }
586 }
587 util::Result<std::unique_ptr<Wallet>> loadWallet(const std::string& name, std::vector<bilingual_str>& warnings) override
588 {
589 DatabaseOptions options;
590 DatabaseStatus status;
591 ReadDatabaseArgs(*m_context.args, options);
592 options.require_existing = true;
593 bilingual_str error;
594 std::unique_ptr<Wallet> wallet{MakeWallet(m_context, LoadWallet(m_context, name, /*load_on_start=*/true, options, status, error, warnings))};
595 if (wallet) {
596 return wallet;
597 } else {
598 return util::Error{error};
599 }
600 }
601 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
602 {
603 DatabaseStatus status;
604 bilingual_str error;
605 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))};
606 if (!error.empty()) {
607 return util::Error{error};
608 }
609 return wallet;
610 }
611 util::Result<WalletMigrationResult> migrateWallet(const std::string& name, const SecureString& passphrase, bool load_wallet) override
612 {
613 auto res = wallet::MigrateLegacyToDescriptor(name, passphrase, m_context, load_wallet);
614 if (!res) return util::Error{util::ErrorString(res)};
616 .wallet = MakeWallet(m_context, res->wallet),
617 .watchonly_wallet_name = res->watchonly_wallet_name,
618 .solvables_wallet_name = res->solvables_wallet_name,
619 .backup_path = res->backup_path,
620 };
621 return out;
622 }
623 bool isEncrypted(const std::string& wallet_name) override
624 {
625 auto wallets{GetWallets(m_context)};
626 auto it = std::find_if(wallets.begin(), wallets.end(), [&](std::shared_ptr<CWallet> w){ return w->GetName() == wallet_name; });
627 if (it != wallets.end()) return (*it)->HasEncryptionKeys();
628
629 // Unloaded wallet, read db
630 DatabaseOptions options;
631 options.require_existing = true;
632 DatabaseStatus status;
633 bilingual_str error;
634 auto db = MakeWalletDatabase(wallet_name, options, status, error);
636 options.require_format = wallet::DatabaseFormat::BERKELEY_RO;
637 db = MakeWalletDatabase(wallet_name, options, status, error);
638 }
639 if (!db) return false;
640 return WalletBatch(*db).IsEncrypted();
641 }
642 std::string getWalletDir() override
643 {
645 }
646 std::vector<std::pair<std::string, std::string>> listWalletDir() override
647 {
648 std::vector<std::pair<std::string, std::string>> paths;
649 for (auto& [path, format] : ListDatabases(GetWalletDir())) {
650 paths.emplace_back(fs::PathToString(path), format);
651 }
652 return paths;
653 }
654 std::vector<std::unique_ptr<Wallet>> getWallets() override
655 {
656 std::vector<std::unique_ptr<Wallet>> wallets;
657 for (const auto& wallet : GetWallets(m_context)) {
658 wallets.emplace_back(MakeWallet(m_context, wallet));
659 }
660 return wallets;
661 }
662 std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
663 {
664 return HandleLoadWallet(m_context, std::move(fn));
665 }
666 WalletContext* context() override { return &m_context; }
667
668 WalletContext m_context;
669 const std::vector<std::string> m_wallet_filenames;
670 std::vector<std::unique_ptr<Handler>> m_rpc_handlers;
671 std::list<CRPCCommand> m_rpc_commands;
672};
673} // namespace
674} // namespace wallet
675
676namespace interfaces {
677std::unique_ptr<Wallet> MakeWallet(wallet::WalletContext& context, const std::shared_ptr<wallet::CWallet>& wallet) { return wallet ? std::make_unique<wallet::WalletImpl>(context, wallet) : nullptr; }
678
679std::unique_ptr<WalletLoader> MakeWalletLoader(Chain& chain, ArgsManager& args)
680{
681 return std::make_unique<wallet::WalletLoaderImpl>(chain, args);
682}
683} // 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:26
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
uint32_t n
Definition: transaction.h:32
Txid hash
Definition: transaction.h:31
An encapsulated public key.
Definition: pubkey.h:40
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:62
An output of a transaction.
Definition: transaction.h:140
Fast randomness source.
Definition: random.h:386
A version of CTransaction with the PSBT format.
Definition: psbt.h:1240
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:118
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:53
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:64
Wallet chain client that in addition to having chain client methods for starting up,...
Definition: wallet.h:314
256-bit opaque blob.
Definition: uint256.h:196
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:162
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:59
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:677
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:161
bool TransactionCanBeBumped(const CWallet &wallet, const Txid &txid)
Return whether transaction can be bumped.
Definition: feebumper.cpp:150
bool SignTransaction(CWallet &wallet, CMutableTransaction &mtx)
Sign the new transaction,.
Definition: feebumper.cpp:333
Result CommitTransaction(CWallet &wallet, const Txid &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, Txid &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:353
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:372
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:202
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:4276
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
CAmount GetMinimumFee(const CWallet &wallet, unsigned int nTxBytes, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee considering user set parameters and the required fee.
Definition: fees.cpp:19
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:224
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:2962
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:457
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:29
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:46
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:385
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:13
std::span< const CRPCCommand > GetWalletRPCCommands()
Definition: wallet.cpp:1137
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:111
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:186
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:171
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:443
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:403
const char * name
Definition: rest.cpp:56
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:152
SigningResult
Definition: signmessage.h:43
A mutable version of CTransaction.
Definition: transaction.h:358
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:32
Information about one wallet address.
Definition: wallet.h:352
Collection of wallet balances.
Definition: wallet.h:366
Migrated wallet info.
Definition: wallet.h:428
std::vector< bool > txin_is_mine
Definition: wallet.h:385
std::optional< std::string > comment
Definition: wallet.h:396
std::vector< CTxDestination > txout_address
Definition: wallet.h:388
std::vector< bool > txout_address_is_mine
Definition: wallet.h:389
CTransactionRef tx
Definition: wallet.h:384
std::optional< std::string > comment_to
Definition: wallet.h:397
std::vector< bool > txout_is_change
Definition: wallet.h:387
std::vector< bool > txout_is_mine
Definition: wallet.h:386
std::optional< std::string > message
Definition: wallet.h:395
std::optional< std::string > from
Definition: wallet.h:394
Wallet transaction output.
Definition: wallet.h:419
Updated transaction status.
Definition: wallet.h:405
unsigned int time_received
Definition: wallet.h:409
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: receive.h:47
CAmount GetTotalAmount() const
Definition: spend.h:61
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
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:52
AssertLockHeld(pool.cs)
std::list< CRPCCommand > m_rpc_commands
Definition: interfaces.cpp:671
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:533
std::vector< std::unique_ptr< Handler > > m_rpc_handlers
Definition: interfaces.cpp:670
const std::vector< std::string > m_wallet_filenames
Definition: interfaces.cpp:669
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:81