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