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