Bitcoin Core 29.99.0
P2P Digital Currency
interfaces.cpp
Go to the documentation of this file.
1// Copyright (c) 2018-2022 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>
12#include <policy/fees.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/types.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
53
54namespace wallet {
55// All members of the classes in this namespace are intentionally public, as the
56// classes themselves are private.
57namespace {
59WalletTx MakeWalletTx(CWallet& wallet, const CWalletTx& wtx)
60{
61 LOCK(wallet.cs_wallet);
62 WalletTx result;
63 result.tx = wtx.tx;
64 result.txin_is_mine.reserve(wtx.tx->vin.size());
65 for (const auto& txin : wtx.tx->vin) {
66 result.txin_is_mine.emplace_back(InputIsMine(wallet, txin));
67 }
68 result.txout_is_mine.reserve(wtx.tx->vout.size());
69 result.txout_address.reserve(wtx.tx->vout.size());
70 result.txout_address_is_mine.reserve(wtx.tx->vout.size());
71 for (const auto& txout : wtx.tx->vout) {
72 result.txout_is_mine.emplace_back(wallet.IsMine(txout));
73 result.txout_is_change.push_back(OutputIsChange(wallet, txout));
74 result.txout_address.emplace_back();
75 result.txout_address_is_mine.emplace_back(ExtractDestination(txout.scriptPubKey, result.txout_address.back()) ?
76 wallet.IsMine(result.txout_address.back()) :
77 ISMINE_NO);
78 }
81 result.change = CachedTxGetChange(wallet, wtx);
82 result.time = wtx.GetTxTime();
83 result.value_map = wtx.mapValue;
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->IsCrypted(); }
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) & ISMINE_SPENDABLE;
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 isminetype* is_mine,
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 std::optional<isminetype> dest_is_mine;
198 if (is_mine || purpose) {
199 dest_is_mine = m_wallet->IsMine(dest);
200 }
201 if (is_mine) {
202 *is_mine = *dest_is_mine;
203 }
204 if (purpose) {
205 // In very old wallets, address purpose may not be recorded so we derive it from IsMine
206 *purpose = entry->purpose.value_or(*dest_is_mine ? AddressPurpose::RECEIVE : AddressPurpose::SEND);
207 }
208 return true;
209 }
210 std::vector<WalletAddress> getAddresses() override
211 {
212 LOCK(m_wallet->cs_wallet);
213 std::vector<WalletAddress> result;
214 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) {
215 if (is_change) return;
216 isminetype is_mine = m_wallet->IsMine(dest);
217 // In very old wallets, address purpose may not be recorded so we derive it from IsMine
218 result.emplace_back(dest, is_mine, purpose.value_or(is_mine ? AddressPurpose::RECEIVE : AddressPurpose::SEND), label);
219 });
220 return result;
221 }
222 std::vector<std::string> getAddressReceiveRequests() override {
223 LOCK(m_wallet->cs_wallet);
224 return m_wallet->GetAddressReceiveRequests();
225 }
226 bool setAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& value) override {
227 // Note: The setAddressReceiveRequest interface used by the GUI to store
228 // receive requests is a little awkward and could be improved in the
229 // future:
230 //
231 // - The same method is used to save requests and erase them, but
232 // having separate methods could be clearer and prevent bugs.
233 //
234 // - Request ids are passed as strings even though they are generated as
235 // integers.
236 //
237 // - Multiple requests can be stored for the same address, but it might
238 // be better to only allow one request or only keep the current one.
239 LOCK(m_wallet->cs_wallet);
240 WalletBatch batch{m_wallet->GetDatabase()};
241 return value.empty() ? m_wallet->EraseAddressReceiveRequest(batch, dest, id)
242 : m_wallet->SetAddressReceiveRequest(batch, dest, id, value);
243 }
244 util::Result<void> displayAddress(const CTxDestination& dest) override
245 {
246 LOCK(m_wallet->cs_wallet);
247 return m_wallet->DisplayAddress(dest);
248 }
249 bool lockCoin(const COutPoint& output, const bool write_to_db) override
250 {
251 LOCK(m_wallet->cs_wallet);
252 std::unique_ptr<WalletBatch> batch = write_to_db ? std::make_unique<WalletBatch>(m_wallet->GetDatabase()) : nullptr;
253 return m_wallet->LockCoin(output, batch.get());
254 }
255 bool unlockCoin(const COutPoint& output) override
256 {
257 LOCK(m_wallet->cs_wallet);
258 std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_wallet->GetDatabase());
259 return m_wallet->UnlockCoin(output, batch.get());
260 }
261 bool isLockedCoin(const COutPoint& output) override
262 {
263 LOCK(m_wallet->cs_wallet);
264 return m_wallet->IsLockedCoin(output);
265 }
266 void listLockedCoins(std::vector<COutPoint>& outputs) override
267 {
268 LOCK(m_wallet->cs_wallet);
269 return m_wallet->ListLockedCoins(outputs);
270 }
271 util::Result<CTransactionRef> createTransaction(const std::vector<CRecipient>& recipients,
272 const CCoinControl& coin_control,
273 bool sign,
274 int& change_pos,
275 CAmount& fee) override
276 {
277 LOCK(m_wallet->cs_wallet);
278 auto res = CreateTransaction(*m_wallet, recipients, change_pos == -1 ? std::nullopt : std::make_optional(change_pos),
279 coin_control, sign);
280 if (!res) return util::Error{util::ErrorString(res)};
281 const auto& txr = *res;
282 fee = txr.fee;
283 change_pos = txr.change_pos ? int(*txr.change_pos) : -1;
284
285 return txr.tx;
286 }
287 void commitTransaction(CTransactionRef tx,
288 WalletValueMap value_map,
289 WalletOrderForm order_form) override
290 {
291 LOCK(m_wallet->cs_wallet);
292 m_wallet->CommitTransaction(std::move(tx), std::move(value_map), std::move(order_form));
293 }
294 bool transactionCanBeAbandoned(const Txid& txid) override { return m_wallet->TransactionCanBeAbandoned(txid); }
295 bool abandonTransaction(const Txid& txid) override
296 {
297 LOCK(m_wallet->cs_wallet);
298 return m_wallet->AbandonTransaction(txid);
299 }
300 bool transactionCanBeBumped(const Txid& txid) override
301 {
302 return feebumper::TransactionCanBeBumped(*m_wallet.get(), txid);
303 }
304 bool createBumpTransaction(const Txid& txid,
305 const CCoinControl& coin_control,
306 std::vector<bilingual_str>& errors,
307 CAmount& old_fee,
308 CAmount& new_fee,
309 CMutableTransaction& mtx) override
310 {
311 std::vector<CTxOut> outputs; // just an empty list of new recipients for now
312 return feebumper::CreateRateBumpTransaction(*m_wallet.get(), txid, coin_control, errors, old_fee, new_fee, mtx, /* require_mine= */ true, outputs) == feebumper::Result::OK;
313 }
314 bool signBumpTransaction(CMutableTransaction& mtx) override { return feebumper::SignTransaction(*m_wallet.get(), mtx); }
315 bool commitBumpTransaction(const Txid& txid,
317 std::vector<bilingual_str>& errors,
318 Txid& bumped_txid) override
319 {
320 return feebumper::CommitTransaction(*m_wallet.get(), txid, std::move(mtx), errors, bumped_txid) ==
322 }
323 CTransactionRef getTx(const Txid& txid) override
324 {
325 LOCK(m_wallet->cs_wallet);
326 auto mi = m_wallet->mapWallet.find(txid);
327 if (mi != m_wallet->mapWallet.end()) {
328 return mi->second.tx;
329 }
330 return {};
331 }
332 WalletTx getWalletTx(const Txid& txid) override
333 {
334 LOCK(m_wallet->cs_wallet);
335 auto mi = m_wallet->mapWallet.find(txid);
336 if (mi != m_wallet->mapWallet.end()) {
337 return MakeWalletTx(*m_wallet, mi->second);
338 }
339 return {};
340 }
341 std::set<WalletTx> getWalletTxs() override
342 {
343 LOCK(m_wallet->cs_wallet);
344 std::set<WalletTx> result;
345 for (const auto& entry : m_wallet->mapWallet) {
346 result.emplace(MakeWalletTx(*m_wallet, entry.second));
347 }
348 return result;
349 }
350 bool tryGetTxStatus(const Txid& txid,
352 int& num_blocks,
353 int64_t& block_time) override
354 {
355 TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
356 if (!locked_wallet) {
357 return false;
358 }
359 auto mi = m_wallet->mapWallet.find(txid);
360 if (mi == m_wallet->mapWallet.end()) {
361 return false;
362 }
363 num_blocks = m_wallet->GetLastBlockHeight();
364 block_time = -1;
365 CHECK_NONFATAL(m_wallet->chain().findBlock(m_wallet->GetLastBlockHash(), FoundBlock().time(block_time)));
366 tx_status = MakeWalletTxStatus(*m_wallet, mi->second);
367 return true;
368 }
369 WalletTx getWalletTxDetails(const Txid& txid,
370 WalletTxStatus& tx_status,
371 WalletOrderForm& order_form,
372 bool& in_mempool,
373 int& num_blocks) override
374 {
375 LOCK(m_wallet->cs_wallet);
376 auto mi = m_wallet->mapWallet.find(txid);
377 if (mi != m_wallet->mapWallet.end()) {
378 num_blocks = m_wallet->GetLastBlockHeight();
379 in_mempool = mi->second.InMempool();
380 order_form = mi->second.vOrderForm;
381 tx_status = MakeWalletTxStatus(*m_wallet, mi->second);
382 return MakeWalletTx(*m_wallet, mi->second);
383 }
384 return {};
385 }
386 std::optional<PSBTError> fillPSBT(std::optional<int> sighash_type,
387 bool sign,
388 bool bip32derivs,
389 size_t* n_signed,
391 bool& complete) override
392 {
393 return m_wallet->FillPSBT(psbtx, complete, sighash_type, sign, bip32derivs, n_signed);
394 }
395 WalletBalances getBalances() override
396 {
397 const auto bal = GetBalance(*m_wallet);
398 WalletBalances result;
399 result.balance = bal.m_mine_trusted;
400 result.unconfirmed_balance = bal.m_mine_untrusted_pending;
401 result.immature_balance = bal.m_mine_immature;
402 return result;
403 }
404 bool tryGetBalances(WalletBalances& balances, uint256& block_hash) override
405 {
406 TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
407 if (!locked_wallet) {
408 return false;
409 }
410 block_hash = m_wallet->GetLastBlockHash();
411 balances = getBalances();
412 return true;
413 }
414 CAmount getBalance() override { return GetBalance(*m_wallet).m_mine_trusted; }
415 CAmount getAvailableBalance(const CCoinControl& coin_control) override
416 {
417 LOCK(m_wallet->cs_wallet);
418 CAmount total_amount = 0;
419 // Fetch selected coins total amount
420 if (coin_control.HasSelected()) {
421 FastRandomContext rng{};
422 CoinSelectionParams params(rng);
423 // Note: for now, swallow any error.
424 if (auto res = FetchSelectedInputs(*m_wallet, coin_control, params)) {
425 total_amount += res->total_amount;
426 }
427 }
428
429 // And fetch the wallet available coins
430 if (coin_control.m_allow_other_inputs) {
431 total_amount += AvailableCoins(*m_wallet, &coin_control).GetTotalAmount();
432 }
433
434 return total_amount;
435 }
436 isminetype txinIsMine(const CTxIn& txin) override
437 {
438 LOCK(m_wallet->cs_wallet);
439 return InputIsMine(*m_wallet, txin);
440 }
441 isminetype txoutIsMine(const CTxOut& txout) override
442 {
443 LOCK(m_wallet->cs_wallet);
444 return m_wallet->IsMine(txout);
445 }
446 CAmount getDebit(const CTxIn& txin, isminefilter filter) override
447 {
448 LOCK(m_wallet->cs_wallet);
449 return m_wallet->GetDebit(txin, filter);
450 }
451 CAmount getCredit(const CTxOut& txout, isminefilter filter) override
452 {
453 LOCK(m_wallet->cs_wallet);
454 return OutputGetCredit(*m_wallet, txout, filter);
455 }
456 CoinsList listCoins() override
457 {
458 LOCK(m_wallet->cs_wallet);
459 CoinsList result;
460 for (const auto& entry : ListCoins(*m_wallet)) {
461 auto& group = result[entry.first];
462 for (const auto& coin : entry.second) {
463 group.emplace_back(coin.outpoint,
464 MakeWalletTxOut(*m_wallet, coin));
465 }
466 }
467 return result;
468 }
469 std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) override
470 {
471 LOCK(m_wallet->cs_wallet);
472 std::vector<WalletTxOut> result;
473 result.reserve(outputs.size());
474 for (const auto& output : outputs) {
475 result.emplace_back();
476 auto it = m_wallet->mapWallet.find(output.hash);
477 if (it != m_wallet->mapWallet.end()) {
478 int depth = m_wallet->GetTxDepthInMainChain(it->second);
479 if (depth >= 0) {
480 result.back() = MakeWalletTxOut(*m_wallet, it->second, output.n, depth);
481 }
482 }
483 }
484 return result;
485 }
486 CAmount getRequiredFee(unsigned int tx_bytes) override { return GetRequiredFee(*m_wallet, tx_bytes); }
487 CAmount getMinimumFee(unsigned int tx_bytes,
488 const CCoinControl& coin_control,
489 int* returned_target,
490 FeeReason* reason) override
491 {
492 FeeCalculation fee_calc;
493 CAmount result;
494 result = GetMinimumFee(*m_wallet, tx_bytes, coin_control, &fee_calc);
495 if (returned_target) *returned_target = fee_calc.returnedTarget;
496 if (reason) *reason = fee_calc.reason;
497 return result;
498 }
499 unsigned int getConfirmTarget() override { return m_wallet->m_confirm_target; }
500 bool hdEnabled() override { return m_wallet->IsHDEnabled(); }
501 bool canGetAddresses() override { return m_wallet->CanGetAddresses(); }
502 bool hasExternalSigner() override { return m_wallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER); }
503 bool privateKeysDisabled() override { return m_wallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS); }
504 bool taprootEnabled() override {
505 auto spk_man = m_wallet->GetScriptPubKeyMan(OutputType::BECH32M, /*internal=*/false);
506 return spk_man != nullptr;
507 }
508 OutputType getDefaultAddressType() override { return m_wallet->m_default_address_type; }
509 CAmount getDefaultMaxTxFee() override { return m_wallet->m_default_max_tx_fee; }
510 void remove() override
511 {
512 RemoveWallet(m_context, m_wallet, /*load_on_start=*/false);
513 }
514 std::unique_ptr<Handler> handleUnload(UnloadFn fn) override
515 {
516 return MakeSignalHandler(m_wallet->NotifyUnload.connect(fn));
517 }
518 std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
519 {
520 return MakeSignalHandler(m_wallet->ShowProgress.connect(fn));
521 }
522 std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override
523 {
524 return MakeSignalHandler(m_wallet->NotifyStatusChanged.connect([fn](CWallet*) { fn(); }));
525 }
526 std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override
527 {
528 return MakeSignalHandler(m_wallet->NotifyAddressBookChanged.connect(
529 [fn](const CTxDestination& address, const std::string& label, bool is_mine,
530 AddressPurpose purpose, ChangeType status) { fn(address, label, is_mine, purpose, status); }));
531 }
532 std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override
533 {
534 return MakeSignalHandler(m_wallet->NotifyTransactionChanged.connect(
535 [fn](const Txid& txid, ChangeType status) { fn(txid, status); }));
536 }
537 std::unique_ptr<Handler> handleCanGetAddressesChanged(CanGetAddressesChangedFn fn) override
538 {
539 return MakeSignalHandler(m_wallet->NotifyCanGetAddressesChanged.connect(fn));
540 }
541 CWallet* wallet() override { return m_wallet.get(); }
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_handlers.emplace_back(m_context.chain->handleRpc(m_rpc_commands.back()));
567 }
568 }
569 bool verify() override { return VerifyWallets(m_context); }
570 bool load() override { return LoadWallets(m_context); }
571 void start(CScheduler& scheduler) override
572 {
573 m_context.scheduler = &scheduler;
574 return StartWallets(m_context);
575 }
576 void stop() override { return UnloadWallets(m_context); }
577 void setMockTime(int64_t time) override { return SetMockTime(time); }
578 void schedulerMockForward(std::chrono::seconds delta) override { Assert(m_context.scheduler)->MockForward(delta); }
579
581 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
582 {
583 DatabaseOptions options;
584 DatabaseStatus status;
585 ReadDatabaseArgs(*m_context.args, options);
586 options.require_create = true;
587 options.create_flags = wallet_creation_flags;
588 options.create_passphrase = passphrase;
589 bilingual_str error;
590 std::unique_ptr<Wallet> wallet{MakeWallet(m_context, CreateWallet(m_context, name, /*load_on_start=*/true, options, status, error, warnings))};
591 if (wallet) {
592 return wallet;
593 } else {
594 return util::Error{error};
595 }
596 }
597 util::Result<std::unique_ptr<Wallet>> loadWallet(const std::string& name, std::vector<bilingual_str>& warnings) override
598 {
599 DatabaseOptions options;
600 DatabaseStatus status;
601 ReadDatabaseArgs(*m_context.args, options);
602 options.require_existing = true;
603 bilingual_str error;
604 std::unique_ptr<Wallet> wallet{MakeWallet(m_context, LoadWallet(m_context, name, /*load_on_start=*/true, options, status, error, warnings))};
605 if (wallet) {
606 return wallet;
607 } else {
608 return util::Error{error};
609 }
610 }
611 util::Result<std::unique_ptr<Wallet>> restoreWallet(const fs::path& backup_file, const std::string& wallet_name, std::vector<bilingual_str>& warnings) override
612 {
613 DatabaseStatus status;
614 bilingual_str error;
615 std::unique_ptr<Wallet> wallet{MakeWallet(m_context, RestoreWallet(m_context, backup_file, wallet_name, /*load_on_start=*/true, status, error, warnings))};
616 if (wallet) {
617 return wallet;
618 } else {
619 return util::Error{error};
620 }
621 }
622 util::Result<WalletMigrationResult> migrateWallet(const std::string& name, const SecureString& passphrase) override
623 {
624 auto res = wallet::MigrateLegacyToDescriptor(name, passphrase, m_context);
625 if (!res) return util::Error{util::ErrorString(res)};
627 .wallet = MakeWallet(m_context, res->wallet),
628 .watchonly_wallet_name = res->watchonly_wallet ? std::make_optional(res->watchonly_wallet->GetName()) : std::nullopt,
629 .solvables_wallet_name = res->solvables_wallet ? std::make_optional(res->solvables_wallet->GetName()) : std::nullopt,
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)->IsCrypted();
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);
646 if (!db) return false;
647 return WalletBatch(*db).IsEncrypted();
648 }
649 std::string getWalletDir() override
650 {
652 }
653 std::vector<std::pair<std::string, std::string>> listWalletDir() override
654 {
655 std::vector<std::pair<std::string, std::string>> paths;
656 for (auto& [path, format] : ListDatabases(GetWalletDir())) {
657 paths.emplace_back(fs::PathToString(path), format);
658 }
659 return paths;
660 }
661 std::vector<std::unique_ptr<Wallet>> getWallets() override
662 {
663 std::vector<std::unique_ptr<Wallet>> wallets;
664 for (const auto& wallet : GetWallets(m_context)) {
665 wallets.emplace_back(MakeWallet(m_context, wallet));
666 }
667 return wallets;
668 }
669 std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
670 {
671 return HandleLoadWallet(m_context, std::move(fn));
672 }
673 WalletContext* context() override { return &m_context; }
674
675 WalletContext m_context;
676 const std::vector<std::string> m_wallet_filenames;
677 std::vector<std::unique_ptr<Handler>> m_rpc_handlers;
678 std::list<CRPCCommand> m_rpc_commands;
679};
680} // namespace
681} // namespace wallet
682
683namespace interfaces {
684std::unique_ptr<Wallet> MakeWallet(wallet::WalletContext& context, const std::shared_ptr<wallet::CWallet>& wallet) { return wallet ? std::make_unique<wallet::WalletImpl>(context, wallet) : nullptr; }
685
686std::unique_ptr<WalletLoader> MakeWalletLoader(Chain& chain, ArgsManager& args)
687{
688 return std::make_unique<wallet::WalletLoaderImpl>(chain, args);
689}
690} // 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:277
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:102
#define Assert(val)
Identity function.
Definition: check.h:106
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:34
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:40
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
An input of a transaction.
Definition: transaction.h:67
An output of a transaction.
Definition: transaction.h:150
Fast randomness source.
Definition: random.h:377
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:130
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:49
Generic interface for managing an event handler or callback function registered with another interfac...
Definition: handler.h:23
Interface for accessing a wallet.
Definition: wallet.h:67
Wallet chain client that in addition to having chain client methods for starting up,...
Definition: wallet.h:319
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:151
uint64_t fee
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:17
std::unique_ptr< Handler > MakeSignalHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: interfaces.cpp:47
std::unique_ptr< WalletLoader > MakeWalletLoader(Chain &chain, ArgsManager &args)
Return implementation of ChainClient interface for a wallet loader.
Definition: dummywallet.cpp:60
std::vector< std::pair< std::string, std::string > > WalletOrderForm
Definition: wallet.h:62
std::unique_ptr< Wallet > MakeWallet(wallet::WalletContext &context, const std::shared_ptr< wallet::CWallet > &wallet)
Return implementation of Wallet interface.
Definition: interfaces.cpp:684
std::map< std::string, std::string > WalletValueMap
Definition: wallet.h:63
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:160
bool TransactionCanBeBumped(const CWallet &wallet, const Txid &txid)
Return whether transaction can be bumped.
Definition: feebumper.cpp:149
bool SignTransaction(CWallet &wallet, CMutableTransaction &mtx)
Sign the new transaction,.
Definition: feebumper.cpp:331
Result CommitTransaction(CWallet &wallet, const Txid &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, Txid &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:351
void StartWallets(WalletContext &context)
Complete startup of wallets.
Definition: load.cpp:156
bool OutputIsChange(const CWallet &wallet, const CTxOut &txout)
Definition: receive.cpp:73
void ReadDatabaseArgs(const ArgsManager &args, DatabaseOptions &options)
Definition: db.cpp:154
Balance GetBalance(const CWallet &wallet, const int min_depth, bool avoid_reuse)
Definition: receive.cpp:293
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:367
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:1369
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:192
bool CachedTxIsTrusted(const CWallet &wallet, const CWalletTx &wtx, std::set< Txid > &trusted_parents)
Definition: receive.cpp:257
CAmount CachedTxGetDebit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
filter decides which addresses will count towards the debit
Definition: receive.cpp:126
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
CAmount OutputGetCredit(const CWallet &wallet, const CTxOut &txout, const isminefilter &filter)
Definition: receive.cpp:31
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)
Definition: wallet.cpp:492
util::Result< PreSelectedInputs > FetchSelectedInputs(const CWallet &wallet, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params)
Fetch and validate coin control selected inputs.
Definition: spend.cpp:268
std::underlying_type_t< isminetype > isminefilter
used for bitflags of isminetype
Definition: wallet.h:49
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:214
CAmount CachedTxGetCredit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
Definition: receive.cpp:109
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:13
util::Result< MigrationResult > MigrateLegacyToDescriptor(const std::string &wallet_name, const SecureString &passphrase, WalletContext &context)
Do all steps to migrate a legacy wallet to a descriptor wallet.
Definition: wallet.cpp:4183
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2810
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:505
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: types.h:41
@ ISMINE_NO
Definition: types.h:42
@ ISMINE_SPENDABLE
Definition: types.h:44
@ ISMINE_ALL
Definition: types.h:46
CAmount CachedTxGetChange(const CWallet &wallet, const CWalletTx &wtx)
Definition: receive.cpp:139
AddressPurpose
Address purpose field that has been been stored with wallet sending and receiving addresses since BIP...
Definition: types.h:61
isminetype InputIsMine(const CWallet &wallet, const CTxIn &txin)
Definition: receive.cpp:12
void UnloadWallets(WalletContext &context)
Definition: load.cpp:165
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:380
bool LoadWallets(WalletContext &context)
Load wallet databases.
Definition: load.cpp:112
@ WALLET_FLAG_EXTERNAL_SIGNER
Indicates that the wallet needs an external signer.
Definition: walletutil.h:77
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:51
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:995
CTxDestination getNewDestination(CWallet &w, OutputType output_type)
Returns a new destination, of an specific type, from the wallet.
Definition: util.cpp:92
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:183
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:161
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:315
NodeContext * m_context
Definition: interfaces.cpp:430
is a home for public enum and struct type definitions that are used internally by node code,...
OutputType
Definition: outputtype.h:17
FeeReason
Definition: fees.h:60
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
const char * name
Definition: rest.cpp:49
static bool verify(const CScriptNum10 &bignum, const CScriptNum &scriptnum)
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:58
static RPCHelpMan stop()
Definition: server.cpp:156
SigningResult
Definition: signmessage.h:43
A mutable version of CTransaction.
Definition: transaction.h:378
int returnedTarget
Definition: fees.h:97
FeeReason reason
Definition: fees.h:95
A version of CTransaction with the PSBT format.
Definition: psbt.h:1119
Bilingual messages:
Definition: translation.h:24
Information about one wallet address.
Definition: wallet.h:357
Collection of wallet balances.
Definition: wallet.h:371
Migrated wallet info.
Definition: wallet.h:427
std::vector< wallet::isminetype > txin_is_mine
Definition: wallet.h:387
std::vector< CTxDestination > txout_address
Definition: wallet.h:390
std::vector< wallet::isminetype > txout_address_is_mine
Definition: wallet.h:391
CTransactionRef tx
Definition: wallet.h:386
std::vector< bool > txout_is_change
Definition: wallet.h:389
std::map< std::string, std::string > value_map
Definition: wallet.h:396
std::vector< wallet::isminetype > txout_is_mine
Definition: wallet.h:388
Wallet transaction output.
Definition: wallet.h:418
Updated transaction status.
Definition: wallet.h:404
unsigned int time_received
Definition: wallet.h:408
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: receive.h:53
CAmount GetTotalAmount()
Definition: spend.h:61
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:36
#define LOCK(cs)
Definition: sync.h:257
#define TRY_LOCK(cs, name)
Definition: sync.h:262
#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:40
AssertLockHeld(pool.cs)
std::list< CRPCCommand > m_rpc_commands
Definition: interfaces.cpp:678
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:544
std::vector< std::unique_ptr< Handler > > m_rpc_handlers
Definition: interfaces.cpp:677
const std::vector< std::string > m_wallet_filenames
Definition: interfaces.cpp:676
is a home for public enum and struct type definitions that are used by internally by wallet code,...
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:80