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