Coverage Report

Created: 2026-09-21 19:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/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 <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
WalletTx MakeWalletTx(CWallet& wallet, const CWalletTx& wtx)
61
0
{
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
0
    }
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
0
                                                      false);
79
0
    }
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
WalletTxStatus MakeWalletTxStatus(const CWallet& wallet, const CWalletTx& wtx)
94
    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
95
0
{
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
0
        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
0
}
113
114
//! Construct wallet TxOut struct.
115
WalletTxOut MakeWalletTxOut(const CWallet& wallet,
116
    const CWalletTx& wtx,
117
    int n,
118
    int depth) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
119
0
{
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
WalletTxOut MakeWalletTxOut(const CWallet& wallet,
129
    const COutput& output) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
130
0
{
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
    bool encryptWallet(const SecureString& wallet_passphrase) override
145
0
    {
146
0
        return m_wallet->EncryptWallet(wallet_passphrase);
147
0
    }
148
0
    bool isCrypted() override { return m_wallet->HasEncryptionKeys(); }
149
0
    bool lock() override { return m_wallet->Lock(); }
150
0
    bool unlock(const SecureString& wallet_passphrase) override { return m_wallet->Unlock(wallet_passphrase); }
151
0
    bool isLocked() override { return m_wallet->IsLocked(); }
152
    bool changeWalletPassphrase(const SecureString& old_wallet_passphrase,
153
        const SecureString& new_wallet_passphrase) override
154
0
    {
155
0
        return m_wallet->ChangeWalletPassphrase(old_wallet_passphrase, new_wallet_passphrase);
156
0
    }
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
    util::Result<CTxDestination> getNewDestination(const OutputType type, const std::string& label) override
161
0
    {
162
0
        LOCK(m_wallet->cs_wallet);
163
0
        return m_wallet->GetNewDestination(type, label);
164
0
    }
165
    bool getPubKey(const CScript& script, const CKeyID& address, CPubKey& pub_key) override
166
0
    {
167
0
        std::unique_ptr<SigningProvider> provider = m_wallet->GetSolvingProvider(script);
168
0
        if (provider) {
169
0
            return provider->GetPubKey(address, pub_key);
170
0
        }
171
0
        return false;
172
0
    }
173
    util::Expected<CExtPubKey, wallet::WalletError> addHDKey(const std::optional<CExtKey>& key) override
174
4
    {
175
4
        return m_wallet->AddHDKey(key);
176
4
    }
177
178
    SigningResult signMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) override
179
0
    {
180
0
        return m_wallet->SignMessage(message, pkhash, str_sig);
181
0
    }
182
    bool isSpendable(const CTxDestination& dest) override
183
0
    {
184
0
        LOCK(m_wallet->cs_wallet);
185
0
        return m_wallet->IsMine(dest);
186
0
    }
187
    bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::optional<AddressPurpose>& purpose) override
188
0
    {
189
0
        return m_wallet->SetAddressBook(dest, name, purpose);
190
0
    }
191
    bool delAddressBook(const CTxDestination& dest) override
192
0
    {
193
0
        return m_wallet->DelAddressBook(dest);
194
0
    }
195
    bool getAddress(const CTxDestination& dest,
196
        std::string* name,
197
        AddressPurpose* purpose) override
198
0
    {
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
0
        }
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
0
        }
209
0
        return true;
210
0
    }
211
    std::vector<WalletAddress> getAddresses() override
212
0
    {
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
0
        });
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
    util::Result<void> displayAddress(const CTxDestination& dest) override
246
0
    {
247
0
        LOCK(m_wallet->cs_wallet);
248
0
        return m_wallet->DisplayAddress(dest);
249
0
    }
250
    bool lockCoin(const COutPoint& output, const bool write_to_db) override
251
0
    {
252
0
        LOCK(m_wallet->cs_wallet);
253
0
        return m_wallet->LockCoin(output, write_to_db);
254
0
    }
255
    bool unlockCoin(const COutPoint& output) override
256
0
    {
257
0
        LOCK(m_wallet->cs_wallet);
258
0
        return m_wallet->UnlockCoin(output);
259
0
    }
260
    bool isLockedCoin(const COutPoint& output) override
261
0
    {
262
0
        LOCK(m_wallet->cs_wallet);
263
0
        return m_wallet->IsLockedCoin(output);
264
0
    }
265
    void listLockedCoins(std::vector<COutPoint>& outputs) override
266
0
    {
267
0
        LOCK(m_wallet->cs_wallet);
268
0
        return m_wallet->ListLockedCoins(outputs);
269
0
    }
270
    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
0
    {
275
0
        LOCK(m_wallet->cs_wallet);
276
0
        return CreateTransaction(*m_wallet, recipients, change_pos, coin_control, sign);
277
0
    }
278
    void commitTransaction(CTransactionRef tx, const std::vector<std::string>& messages) override
279
0
    {
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
    bool abandonTransaction(const Txid& txid) override
285
0
    {
286
0
        LOCK(m_wallet->cs_wallet);
287
0
        return m_wallet->AbandonTransaction(txid);
288
0
    }
289
    bool transactionCanBeBumped(const Txid& txid) override
290
0
    {
291
0
        return feebumper::TransactionCanBeBumped(*m_wallet.get(), txid);
292
0
    }
293
    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
0
    {
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
    bool commitBumpTransaction(const Txid& txid,
305
        CMutableTransaction&& mtx,
306
        std::vector<bilingual_str>& errors,
307
        Txid& bumped_txid) override
308
0
    {
309
0
        return feebumper::CommitTransaction(*m_wallet.get(), txid, std::move(mtx), errors, bumped_txid) ==
310
0
               feebumper::Result::OK;
311
0
    }
312
    CTransactionRef getTx(const Txid& txid) override
313
0
    {
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
0
        }
319
0
        return {};
320
0
    }
321
    WalletTx getWalletTx(const Txid& txid) override
322
0
    {
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
0
        }
328
0
        return {};
329
0
    }
330
    std::set<WalletTx> getWalletTxs() override
331
0
    {
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
0
        }
337
0
        return result;
338
0
    }
339
    bool tryGetTxStatus(const Txid& txid,
340
        interfaces::WalletTxStatus& tx_status,
341
        int& num_blocks,
342
        int64_t& block_time) override
343
0
    {
344
0
        TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
345
0
        if (!locked_wallet) {
346
0
            return false;
347
0
        }
348
0
        auto mi = m_wallet->mapWallet.find(txid);
349
0
        if (mi == m_wallet->mapWallet.end()) {
350
0
            return false;
351
0
        }
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
0
        return true;
357
0
    }
358
    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
0
    {
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
0
        }
375
0
        return {};
376
0
    }
377
    std::optional<PSBTError> fillPSBT(const common::PSBTFillOptions& options,
378
        size_t* n_signed,
379
        PartiallySignedTransaction& psbtx,
380
        bool& complete) override
381
0
    {
382
0
        return m_wallet->FillPSBT(psbtx, options, complete, n_signed);
383
0
    }
384
    std::vector<wallet::ImportResult> importDescriptors(std::vector<wallet::ImportDescriptorRequest>& requests) override
385
0
    {
386
0
        return wallet::ProcessDescriptorsImport(*m_wallet, requests);
387
0
    }
388
    WalletBalances getBalances() override
389
0
    {
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
0
    }
399
    bool tryGetBalances(WalletBalances& balances, uint256& block_hash) override
400
0
    {
401
0
        TRY_LOCK(m_wallet->cs_wallet, locked_wallet);
402
0
        if (!locked_wallet) {
403
0
            return false;
404
0
        }
405
0
        block_hash = m_wallet->GetLastBlockHash();
406
0
        balances = getBalances();
407
0
        return true;
408
0
    }
409
0
    CAmount getBalance() override { return GetBalance(*m_wallet).m_mine_trusted; }
410
    CAmount getAvailableBalance(const CCoinControl& coin_control) override
411
0
    {
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
0
        }
428
429
0
        return total_amount;
430
0
    }
431
    bool txinIsMine(const CTxIn& txin) override
432
0
    {
433
0
        LOCK(m_wallet->cs_wallet);
434
0
        return InputIsMine(*m_wallet, txin);
435
0
    }
436
    bool txoutIsMine(const CTxOut& txout) override
437
0
    {
438
0
        LOCK(m_wallet->cs_wallet);
439
0
        return m_wallet->IsMine(txout);
440
0
    }
441
    CAmount getDebit(const CTxIn& txin) override
442
0
    {
443
0
        LOCK(m_wallet->cs_wallet);
444
0
        return m_wallet->GetDebit(txin);
445
0
    }
446
    CAmount getCredit(const CTxOut& txout) override
447
0
    {
448
0
        LOCK(m_wallet->cs_wallet);
449
0
        return OutputGetCredit(*m_wallet, txout);
450
0
    }
451
    CoinsList listCoins() override
452
0
    {
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
0
            }
461
0
        }
462
0
        return result;
463
0
    }
464
    std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) override
465
0
    {
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
0
                }
477
0
            }
478
0
        }
479
0
        return result;
480
0
    }
481
0
    CAmount getRequiredFee(unsigned int tx_bytes) override { return GetRequiredFee(*m_wallet, tx_bytes); }
482
    CAmount getMinimumFee(unsigned int tx_bytes,
483
        const CCoinControl& coin_control,
484
        std::optional<int>* returned_target,
485
        FeeReason* reason) override
486
0
    {
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
0
    }
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
0
    }
502
0
    OutputType getDefaultAddressType() override { return m_wallet->m_default_address_type; }
503
0
    CAmount getDefaultMaxTxFee() override { return m_wallet->m_default_max_tx_fee; }
504
    void remove() override
505
0
    {
506
0
        RemoveWallet(m_context, m_wallet, /*load_on_start=*/false);
507
0
    }
508
    std::unique_ptr<Handler> handleUnload(UnloadFn fn) override
509
0
    {
510
0
        return MakeSignalHandler(m_wallet->NotifyUnload.connect(fn));
511
0
    }
512
    std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
513
0
    {
514
0
        return MakeSignalHandler(m_wallet->ShowProgress.connect(fn));
515
0
    }
516
    std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override
517
0
    {
518
0
        return MakeSignalHandler(m_wallet->NotifyStatusChanged.connect([fn](CWallet*) { fn(); }));
519
0
    }
520
    std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override
521
0
    {
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
0
    }
526
    std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override
527
0
    {
528
0
        return MakeSignalHandler(m_wallet->NotifyTransactionChanged.connect(
529
0
            [fn](const Txid& txid, ChangeType status) { fn(txid, status); }));
530
0
    }
531
    std::unique_ptr<Handler> handleCanGetAddressesChanged(CanGetAddressesChangedFn fn) override
532
0
    {
533
0
        return MakeSignalHandler(m_wallet->NotifyCanGetAddressesChanged.connect(fn));
534
0
    }
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
    WalletLoaderImpl(Chain& chain, ArgsManager& args)
551
439
    {
552
439
        m_context.chain = &chain;
553
439
        m_context.args = &args;
554
439
    }
555
439
    ~WalletLoaderImpl() override { stop(); }
556
557
    //! ChainClient methods
558
    void registerRpcs() override
559
432
    {
560
25.4k
        for (const CRPCCommand& command : GetWalletRPCCommands()) {
561
25.4k
            m_rpc_commands.emplace_back(command.category, command.name, [this, &command](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
562
22.0k
                JSONRPCRequest wallet_request = request;
563
22.0k
                wallet_request.context = &m_context;
564
22.0k
                return command.actor(wallet_request, result, last_handler);
565
22.0k
            }, command.argNames, command.unique_id);
566
25.4k
            m_rpc_commands.back().metadata_fn = command.metadata_fn;
567
25.4k
            m_rpc_handlers.emplace_back(m_context.chain->handleRpc(m_rpc_commands.back()));
568
25.4k
        }
569
432
    }
570
421
    bool verify() override { return VerifyWallets(m_context); }
571
363
    bool load() override { return LoadWallets(m_context); }
572
    void start(CScheduler& scheduler) override
573
360
    {
574
360
        m_context.scheduler = &scheduler;
575
360
        return StartWallets(m_context);
576
360
    }
577
853
    void stop() override { return UnloadWallets(m_context); }
578
191
    void setMockTime(int64_t time) override { return SetMockTime(std::chrono::seconds{time}); }
579
25
    void schedulerMockForward(std::chrono::seconds delta) override { Assert(m_context.scheduler)->MockForward(delta); }
580
581
    //! WalletLoader methods
582
    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
0
    {
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
0
        } else {
595
0
            return util::Error{error};
596
0
        }
597
0
    }
598
    util::Result<std::unique_ptr<Wallet>> loadWallet(const std::string& name, std::vector<bilingual_str>& warnings) override
599
0
    {
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
0
        } else {
609
0
            return util::Error{error};
610
0
        }
611
0
    }
612
    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
0
    {
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
0
        }
620
0
        return wallet;
621
0
    }
622
    util::Result<WalletMigrationResult> migrateWallet(const std::string& name, const SecureString& passphrase, bool load_wallet) override
623
0
    {
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
    bool isEncrypted(const std::string& wallet_name) override
635
0
    {
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
0
        }
650
0
        if (!db) return false;
651
0
        return WalletBatch(*db).IsEncrypted();
652
0
    }
653
    std::string getWalletDir() override
654
0
    {
655
0
        return fs::PathToString(GetWalletDir());
656
0
    }
657
    std::vector<std::pair<std::string, std::string>> listWalletDir() override
658
0
    {
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
    std::vector<std::unique_ptr<Wallet>> getWallets() override
666
0
    {
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
0
        }
671
0
        return wallets;
672
0
    }
673
    std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
674
0
    {
675
0
        return HandleLoadWallet(m_context, std::move(fn));
676
0
    }
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
std::unique_ptr<WalletLoader> MakeWalletLoader(Chain& chain, ArgsManager& args)
691
439
{
692
439
    return std::make_unique<wallet::WalletLoaderImpl>(chain, args);
693
439
}
694
} // namespace interfaces