Coverage Report

Created: 2026-08-14 17:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/wallet/interfaces.cpp
Line
Count
Source
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
WalletTx MakeWalletTx(CWallet& wallet, const CWalletTx& wtx)
58
0
{
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) {
  Branch (63:27): [True: 0, False: 0]
64
0
        result.txin_is_mine.emplace_back(InputIsMine(wallet, txin));
65
0
    }
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) {
  Branch (69:28): [True: 0, False: 0]
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()) ?
  Branch (73:51): [True: 0, False: 0]
74
0
                                                      wallet.IsMine(result.txout_address.back()) :
75
0
                                                      false);
76
0
    }
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
WalletTxStatus MakeWalletTxStatus(const CWallet& wallet, const CWalletTx& wtx)
91
    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
92
0
{
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 :
  Branch (97:9): [True: 0, False: 0]
98
0
        wtx.state<TxStateBlockConflicted>() ? wtx.state<TxStateBlockConflicted>()->conflicting_block_height :
  Branch (98:9): [True: 0, False: 0]
99
0
        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
0
}
110
111
//! Construct wallet TxOut struct.
112
WalletTxOut MakeWalletTxOut(const CWallet& wallet,
113
    const CWalletTx& wtx,
114
    int n,
115
    int depth) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
116
0
{
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
WalletTxOut MakeWalletTxOut(const CWallet& wallet,
126
    const COutput& output) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
127
0
{
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
0
    explicit WalletImpl(WalletContext& context, const std::shared_ptr<CWallet>& wallet) : m_context(context), m_wallet(wallet) {}
140
141
    bool encryptWallet(const SecureString& wallet_passphrase) override
142
0
    {
143
0
        return m_wallet->EncryptWallet(wallet_passphrase);
144
0
    }
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
    bool changeWalletPassphrase(const SecureString& old_wallet_passphrase,
150
        const SecureString& new_wallet_passphrase) override
151
0
    {
152
0
        return m_wallet->ChangeWalletPassphrase(old_wallet_passphrase, new_wallet_passphrase);
153
0
    }
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
    util::Result<CTxDestination> getNewDestination(const OutputType type, const std::string& label) override
158
0
    {
159
0
        LOCK(m_wallet->cs_wallet);
160
0
        return m_wallet->GetNewDestination(type, label);
161
0
    }
162
    bool getPubKey(const CScript& script, const CKeyID& address, CPubKey& pub_key) override
163
0
    {
164
0
        std::unique_ptr<SigningProvider> provider = m_wallet->GetSolvingProvider(script);
165
0
        if (provider) {
  Branch (165:13): [True: 0, False: 0]
166
0
            return provider->GetPubKey(address, pub_key);
167
0
        }
168
0
        return false;
169
0
    }
170
    SigningResult signMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) override
171
0
    {
172
0
        return m_wallet->SignMessage(message, pkhash, str_sig);
173
0
    }
174
    bool isSpendable(const CTxDestination& dest) override
175
0
    {
176
0
        LOCK(m_wallet->cs_wallet);
177
0
        return m_wallet->IsMine(dest);
178
0
    }
179
    bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::optional<AddressPurpose>& purpose) override
180
0
    {
181
0
        return m_wallet->SetAddressBook(dest, name, purpose);
182
0
    }
183
    bool delAddressBook(const CTxDestination& dest) override
184
0
    {
185
0
        return m_wallet->DelAddressBook(dest);
186
0
    }
187
    bool getAddress(const CTxDestination& dest,
188
        std::string* name,
189
        AddressPurpose* purpose) override
190
0
    {
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
  Branch (193:13): [True: 0, False: 0]
194
0
        if (name) {
  Branch (194:13): [True: 0, False: 0]
195
0
            *name = entry->GetLabel();
196
0
        }
197
0
        if (purpose) {
  Branch (197:13): [True: 0, False: 0]
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);
  Branch (199:48): [True: 0, False: 0]
200
0
        }
201
0
        return true;
202
0
    }
203
    std::vector<WalletAddress> getAddresses() override
204
0
    {
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;
  Branch (208:17): [True: 0, False: 0]
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);
  Branch (211:65): [True: 0, False: 0]
212
0
        });
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)
  Branch (234:16): [True: 0, False: 0]
235
0
                             : m_wallet->SetAddressReceiveRequest(batch, dest, id, value);
236
0
    }
237
    util::Result<void> displayAddress(const CTxDestination& dest) override
238
0
    {
239
0
        LOCK(m_wallet->cs_wallet);
240
0
        return m_wallet->DisplayAddress(dest);
241
0
    }
242
    bool lockCoin(const COutPoint& output, const bool write_to_db) override
243
0
    {
244
0
        LOCK(m_wallet->cs_wallet);
245
0
        return m_wallet->LockCoin(output, write_to_db);
246
0
    }
247
    bool unlockCoin(const COutPoint& output) override
248
0
    {
249
0
        LOCK(m_wallet->cs_wallet);
250
0
        return m_wallet->UnlockCoin(output);
251
0
    }
252
    bool isLockedCoin(const COutPoint& output) override
253
0
    {
254
0
        LOCK(m_wallet->cs_wallet);
255
0
        return m_wallet->IsLockedCoin(output);
256
0
    }
257
    void listLockedCoins(std::vector<COutPoint>& outputs) override
258
0
    {
259
0
        LOCK(m_wallet->cs_wallet);
260
0
        return m_wallet->ListLockedCoins(outputs);
261
0
    }
262
    util::Result<wallet::CreatedTransactionResult> createTransaction(const std::vector<CRecipient>& recipients,
263
        const CCoinControl& coin_control,
264
        bool sign,
265
        std::optional<unsigned int> change_pos) override
266
0
    {
267
0
        LOCK(m_wallet->cs_wallet);
268
0
        return CreateTransaction(*m_wallet, recipients, change_pos, coin_control, sign);
269
0
    }
270
    void commitTransaction(CTransactionRef tx, const std::vector<std::string>& messages) override
271
0
    {
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
    bool abandonTransaction(const Txid& txid) override
277
0
    {
278
0
        LOCK(m_wallet->cs_wallet);
279
0
        return m_wallet->AbandonTransaction(txid);
280
0
    }
281
    bool transactionCanBeBumped(const Txid& txid) override
282
0
    {
283
0
        return feebumper::TransactionCanBeBumped(*m_wallet.get(), txid);
284
0
    }
285
    bool createBumpTransaction(const Txid& txid,
286
        const CCoinControl& coin_control,
287
        std::vector<bilingual_str>& errors,
288
        CAmount& old_fee,
289
        CAmount& new_fee,
290
        CMutableTransaction& mtx) override
291
0
    {
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
    bool commitBumpTransaction(const Txid& txid,
297
        CMutableTransaction&& mtx,
298
        std::vector<bilingual_str>& errors,
299
        Txid& bumped_txid) override
300
0
    {
301
0
        return feebumper::CommitTransaction(*m_wallet.get(), txid, std::move(mtx), errors, bumped_txid) ==
302
0
               feebumper::Result::OK;
303
0
    }
304
    CTransactionRef getTx(const Txid& txid) override
305
0
    {
306
0
        LOCK(m_wallet->cs_wallet);
307
0
        auto mi = m_wallet->mapWallet.find(txid);
308
0
        if (mi != m_wallet->mapWallet.end()) {
  Branch (308:13): [True: 0, False: 0]
309
0
            return mi->second.GetTx();
310
0
        }
311
0
        return {};
312
0
    }
313
    WalletTx getWalletTx(const Txid& txid) override
314
0
    {
315
0
        LOCK(m_wallet->cs_wallet);
316
0
        auto mi = m_wallet->mapWallet.find(txid);
317
0
        if (mi != m_wallet->mapWallet.end()) {
  Branch (317:13): [True: 0, False: 0]
318
0
            return MakeWalletTx(*m_wallet, mi->second);
319
0
        }
320
0
        return {};
321
0
    }
322
    std::set<WalletTx> getWalletTxs() override
323
0
    {
324
0
        LOCK(m_wallet->cs_wallet);
325
0
        std::set<WalletTx> result;
326
0
        for (const auto& entry : m_wallet->mapWallet) {
  Branch (326:32): [True: 0, False: 0]
327
0
            result.emplace(MakeWalletTx(*m_wallet, entry.second));
328
0
        }
329
0
        return result;
330
0
    }
331
    bool tryGetTxStatus(const Txid& txid,
332
        interfaces::WalletTxStatus& tx_status,
333
        int& num_blocks,
334
        int64_t& block_time) override
335
0
    {
336
0
        TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
337
0
        if (!locked_wallet) {
  Branch (337:13): [True: 0, False: 0]
338
0
            return false;
339
0
        }
340
0
        auto mi = m_wallet->mapWallet.find(txid);
341
0
        if (mi == m_wallet->mapWallet.end()) {
  Branch (341:13): [True: 0, False: 0]
342
0
            return false;
343
0
        }
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
0
        return true;
349
0
    }
350
    WalletTx getWalletTxDetails(const Txid& txid,
351
        WalletTxStatus& tx_status,
352
        std::vector<std::string>& messages,
353
        std::vector<std::string>& payment_requests,
354
        bool& in_mempool,
355
        int& num_blocks) override
356
0
    {
357
0
        LOCK(m_wallet->cs_wallet);
358
0
        auto mi = m_wallet->mapWallet.find(txid);
359
0
        if (mi != m_wallet->mapWallet.end()) {
  Branch (359:13): [True: 0, False: 0]
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
0
        }
367
0
        return {};
368
0
    }
369
    std::optional<PSBTError> fillPSBT(const common::PSBTFillOptions& options,
370
        size_t* n_signed,
371
        PartiallySignedTransaction& psbtx,
372
        bool& complete) override
373
0
    {
374
0
        return m_wallet->FillPSBT(psbtx, options, complete, n_signed);
375
0
    }
376
    WalletBalances getBalances() override
377
0
    {
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
0
    }
387
    bool tryGetBalances(WalletBalances& balances, uint256& block_hash) override
388
0
    {
389
0
        TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
390
0
        if (!locked_wallet) {
  Branch (390:13): [True: 0, False: 0]
391
0
            return false;
392
0
        }
393
0
        block_hash = m_wallet->GetLastBlockHash();
394
0
        balances = getBalances();
395
0
        return true;
396
0
    }
397
0
    CAmount getBalance() override { return GetBalance(*m_wallet).m_mine_trusted; }
398
    CAmount getAvailableBalance(const CCoinControl& coin_control) override
399
0
    {
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()) {
  Branch (403:13): [True: 0, False: 0]
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)) {
  Branch (407:22): [True: 0, False: 0]
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) {
  Branch (413:13): [True: 0, False: 0]
414
0
            total_amount += AvailableCoins(*m_wallet, &coin_control).GetTotalAmount();
415
0
        }
416
417
0
        return total_amount;
418
0
    }
419
    bool txinIsMine(const CTxIn& txin) override
420
0
    {
421
0
        LOCK(m_wallet->cs_wallet);
422
0
        return InputIsMine(*m_wallet, txin);
423
0
    }
424
    bool txoutIsMine(const CTxOut& txout) override
425
0
    {
426
0
        LOCK(m_wallet->cs_wallet);
427
0
        return m_wallet->IsMine(txout);
428
0
    }
429
    CAmount getDebit(const CTxIn& txin) override
430
0
    {
431
0
        LOCK(m_wallet->cs_wallet);
432
0
        return m_wallet->GetDebit(txin);
433
0
    }
434
    CAmount getCredit(const CTxOut& txout) override
435
0
    {
436
0
        LOCK(m_wallet->cs_wallet);
437
0
        return OutputGetCredit(*m_wallet, txout);
438
0
    }
439
    CoinsList listCoins() override
440
0
    {
441
0
        LOCK(m_wallet->cs_wallet);
442
0
        CoinsList result;
443
0
        for (const auto& entry : ListCoins(*m_wallet)) {
  Branch (443:32): [True: 0, False: 0]
444
0
            auto& group = result[entry.first];
445
0
            for (const auto& coin : entry.second) {
  Branch (445:35): [True: 0, False: 0]
446
0
                group.emplace_back(coin.outpoint,
447
0
                    MakeWalletTxOut(*m_wallet, coin));
448
0
            }
449
0
        }
450
0
        return result;
451
0
    }
452
    std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) override
453
0
    {
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) {
  Branch (457:33): [True: 0, False: 0]
458
0
            result.emplace_back();
459
0
            auto it = m_wallet->mapWallet.find(output.hash);
460
0
            if (it != m_wallet->mapWallet.end()) {
  Branch (460:17): [True: 0, False: 0]
461
0
                int depth = m_wallet->GetTxDepthInMainChain(it->second);
462
0
                if (depth >= 0) {
  Branch (462:21): [True: 0, False: 0]
463
0
                    result.back() = MakeWalletTxOut(*m_wallet, it->second, output.n, depth);
464
0
                }
465
0
            }
466
0
        }
467
0
        return result;
468
0
    }
469
0
    CAmount getRequiredFee(unsigned int tx_bytes) override { return GetRequiredFee(*m_wallet, tx_bytes); }
470
    CAmount getMinimumFee(unsigned int tx_bytes,
471
        const CCoinControl& coin_control,
472
        int* returned_target,
473
        FeeReason* reason) override
474
0
    {
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;
  Branch (478:13): [True: 0, False: 0]
479
0
        if (reason) *reason = fee_calc.reason;
  Branch (479:13): [True: 0, False: 0]
480
0
        return result;
481
0
    }
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
0
    }
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
    void remove() override
494
0
    {
495
0
        RemoveWallet(m_context, m_wallet, /*load_on_start=*/false);
496
0
    }
497
    std::unique_ptr<Handler> handleUnload(UnloadFn fn) override
498
0
    {
499
0
        return MakeSignalHandler(m_wallet->NotifyUnload.connect(fn));
500
0
    }
501
    std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
502
0
    {
503
0
        return MakeSignalHandler(m_wallet->ShowProgress.connect(fn));
504
0
    }
505
    std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override
506
0
    {
507
0
        return MakeSignalHandler(m_wallet->NotifyStatusChanged.connect([fn](CWallet*) { fn(); }));
508
0
    }
509
    std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override
510
0
    {
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
0
    }
515
    std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override
516
0
    {
517
0
        return MakeSignalHandler(m_wallet->NotifyTransactionChanged.connect(
518
0
            [fn](const Txid& txid, ChangeType status) { fn(txid, status); }));
519
0
    }
520
    std::unique_ptr<Handler> handleCanGetAddressesChanged(CanGetAddressesChangedFn fn) override
521
0
    {
522
0
        return MakeSignalHandler(m_wallet->NotifyCanGetAddressesChanged.connect(fn));
523
0
    }
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
    WalletLoaderImpl(Chain& chain, ArgsManager& args)
540
0
    {
541
0
        m_context.chain = &chain;
542
0
        m_context.args = &args;
543
0
    }
544
0
    ~WalletLoaderImpl() override { stop(); }
545
546
    //! ChainClient methods
547
    void registerRpcs() override
548
0
    {
549
0
        for (const CRPCCommand& command : GetWalletRPCCommands()) {
  Branch (549:41): [True: 0, False: 0]
550
0
            m_rpc_commands.emplace_back(command.category, command.name, [this, &command](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
551
0
                JSONRPCRequest wallet_request = request;
552
0
                wallet_request.context = &m_context;
553
0
                return command.actor(wallet_request, result, last_handler);
554
0
            }, command.argNames, command.unique_id);
555
0
            m_rpc_commands.back().metadata_fn = command.metadata_fn;
556
0
            m_rpc_handlers.emplace_back(m_context.chain->handleRpc(m_rpc_commands.back()));
557
0
        }
558
0
    }
559
0
    bool verify() override { return VerifyWallets(m_context); }
560
0
    bool load() override { return LoadWallets(m_context); }
561
    void start(CScheduler& scheduler) override
562
0
    {
563
0
        m_context.scheduler = &scheduler;
564
0
        return StartWallets(m_context);
565
0
    }
566
0
    void stop() override { return UnloadWallets(m_context); }
567
0
    void setMockTime(int64_t time) override { return SetMockTime(time); }
568
0
    void schedulerMockForward(std::chrono::seconds delta) override { Assert(m_context.scheduler)->MockForward(delta); }
569
570
    //! WalletLoader methods
571
    util::Result<std::unique_ptr<Wallet>> createWallet(const std::string& name, const SecureString& passphrase, uint64_t wallet_creation_flags, std::vector<bilingual_str>& warnings) override
572
0
    {
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) {
  Branch (581:13): [True: 0, False: 0]
582
0
            return wallet;
583
0
        } else {
584
0
            return util::Error{error};
585
0
        }
586
0
    }
587
    util::Result<std::unique_ptr<Wallet>> loadWallet(const std::string& name, std::vector<bilingual_str>& warnings) override
588
0
    {
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) {
  Branch (595:13): [True: 0, False: 0]
596
0
            return wallet;
597
0
        } else {
598
0
            return util::Error{error};
599
0
        }
600
0
    }
601
    util::Result<std::unique_ptr<Wallet>> restoreWallet(const fs::path& backup_file, const std::string& wallet_name, std::vector<bilingual_str>& warnings, bool load_after_restore) override
602
0
    {
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()) {
  Branch (606:13): [True: 0, False: 0]
607
0
            return util::Error{error};
608
0
        }
609
0
        return wallet;
610
0
    }
611
    util::Result<WalletMigrationResult> migrateWallet(const std::string& name, const SecureString& passphrase, bool load_wallet) override
612
0
    {
613
0
        auto res = wallet::MigrateLegacyToDescriptor(name, passphrase, m_context, load_wallet);
614
0
        if (!res) return util::Error{util::ErrorString(res)};
  Branch (614:13): [True: 0, False: 0]
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
    bool isEncrypted(const std::string& wallet_name) override
624
0
    {
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();
  Branch (627:13): [True: 0, False: 0]
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) {
  Branch (635:13): [True: 0, False: 0]
  Branch (635:20): [True: 0, False: 0]
636
0
            options.require_format = wallet::DatabaseFormat::BERKELEY_RO;
637
0
            db = MakeWalletDatabase(wallet_name, options, status, error);
638
0
        }
639
0
        if (!db) return false;
  Branch (639:13): [True: 0, False: 0]
640
0
        return WalletBatch(*db).IsEncrypted();
641
0
    }
642
    std::string getWalletDir() override
643
0
    {
644
0
        return fs::PathToString(GetWalletDir());
645
0
    }
646
    std::vector<std::pair<std::string, std::string>> listWalletDir() override
647
0
    {
648
0
        std::vector<std::pair<std::string, std::string>> paths;
649
0
        for (auto& [path, format] : ListDatabases(GetWalletDir())) {
  Branch (649:35): [True: 0, False: 0]
650
0
            paths.emplace_back(fs::PathToString(path), format);
651
0
        }
652
0
        return paths;
653
0
    }
654
    std::vector<std::unique_ptr<Wallet>> getWallets() override
655
0
    {
656
0
        std::vector<std::unique_ptr<Wallet>> wallets;
657
0
        for (const auto& wallet : GetWallets(m_context)) {
  Branch (657:33): [True: 0, False: 0]
658
0
            wallets.emplace_back(MakeWallet(m_context, wallet));
659
0
        }
660
0
        return wallets;
661
0
    }
662
    std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
663
0
    {
664
0
        return HandleLoadWallet(m_context, std::move(fn));
665
0
    }
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
0
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; }
  Branch (677:125): [True: 0, False: 0]
678
679
std::unique_ptr<WalletLoader> MakeWalletLoader(Chain& chain, ArgsManager& args)
680
0
{
681
0
    return std::make_unique<wallet::WalletLoaderImpl>(chain, args);
682
0
}
683
} // namespace interfaces