Coverage Report

Created: 2026-09-21 19:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/interfaces/wallet.h
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
#ifndef BITCOIN_INTERFACES_WALLET_H
6
#define BITCOIN_INTERFACES_WALLET_H
7
8
#include <addresstype.h>
9
#include <common/signmessage.h>
10
#include <common/types.h>
11
#include <consensus/amount.h>
12
#include <interfaces/chain.h>
13
#include <primitives/transaction.h>
14
#include <pubkey.h>
15
#include <support/allocators/secure.h>
16
#include <util/expected.h>
17
#include <util/fs.h>
18
#include <util/result.h>
19
#include <util/ui_change_type.h>
20
#include <wallet/types.h>
21
22
#include <compare>
23
#include <cstddef>
24
#include <cstdint>
25
#include <functional>
26
#include <map>
27
#include <memory>
28
#include <optional>
29
#include <set>
30
#include <string>
31
#include <tuple>
32
#include <utility>
33
#include <vector>
34
35
class ArgsManager;
36
class CScript;
37
class PartiallySignedTransaction;
38
class uint256;
39
enum class FeeReason;
40
enum class OutputType;
41
struct bilingual_str;
42
struct CExtKey;
43
44
namespace wallet {
45
class CCoinControl;
46
class CWallet;
47
struct ImportDescriptorRequest;
48
struct ImportResult;
49
struct CRecipient;
50
struct WalletContext;
51
} // namespace wallet
52
53
namespace interfaces {
54
55
class Handler;
56
struct WalletAddress;
57
struct WalletBalances;
58
struct WalletTx;
59
struct WalletTxOut;
60
struct WalletTxStatus;
61
struct WalletMigrationResult;
62
63
//! Interface for accessing a wallet.
64
class Wallet
65
{
66
public:
67
5
    virtual ~Wallet() = default;
68
69
    //! Encrypt wallet.
70
    virtual bool encryptWallet(const SecureString& wallet_passphrase) = 0;
71
72
    //! Return whether wallet is encrypted.
73
    virtual bool isCrypted() = 0;
74
75
    //! Lock wallet.
76
    virtual bool lock() = 0;
77
78
    //! Unlock wallet.
79
    virtual bool unlock(const SecureString& wallet_passphrase) = 0;
80
81
    //! Return whether wallet is locked.
82
    virtual bool isLocked() = 0;
83
84
    //! Change wallet passphrase.
85
    virtual bool changeWalletPassphrase(const SecureString& old_wallet_passphrase,
86
        const SecureString& new_wallet_passphrase) = 0;
87
88
    //! Abort a rescan.
89
    virtual void abortRescan() = 0;
90
91
    //! Back up wallet.
92
    virtual bool backupWallet(const std::string& filename) = 0;
93
94
    //! Get wallet name.
95
    virtual std::string getWalletName() = 0;
96
97
    // Get a new address.
98
    virtual util::Result<CTxDestination> getNewDestination(OutputType type, const std::string& label) = 0;
99
100
    //! Get public key.
101
    virtual bool getPubKey(const CScript& script, const CKeyID& address, CPubKey& pub_key) = 0;
102
103
    //! Generate and add a new HD key to the wallet.
104
    //! Requires the wallet to be unlocked. Returns a `WalletError` with code
105
    //! `WalletErrorCode::UnlockNeeded` if the wallet is locked.
106
    //!
107
    //! Return the master xpub for the added HD key, or a `WalletError` on failure.
108
    virtual util::Expected<CExtPubKey, wallet::WalletError> addHDKey(const std::optional<CExtKey>& key) = 0;
109
110
    //! Sign message
111
    virtual SigningResult signMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) = 0;
112
113
    //! Return whether wallet has private key.
114
    virtual bool isSpendable(const CTxDestination& dest) = 0;
115
116
    //! Add or update address.
117
    virtual bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::optional<wallet::AddressPurpose>& purpose) = 0;
118
119
    // Remove address.
120
    virtual bool delAddressBook(const CTxDestination& dest) = 0;
121
122
    //! Look up address in wallet, return whether exists.
123
    virtual bool getAddress(const CTxDestination& dest,
124
        std::string* name,
125
        wallet::AddressPurpose* purpose) = 0;
126
127
    //! Get wallet address list.
128
    virtual std::vector<WalletAddress> getAddresses() = 0;
129
130
    //! Get receive requests.
131
    virtual std::vector<std::string> getAddressReceiveRequests() = 0;
132
133
    //! Save or remove receive request.
134
    virtual bool setAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& value) = 0;
135
136
    //! Display address on external signer
137
    virtual util::Result<void> displayAddress(const CTxDestination& dest) = 0;
138
139
    //! Lock coin.
140
    virtual bool lockCoin(const COutPoint& output, bool write_to_db) = 0;
141
142
    //! Unlock coin.
143
    virtual bool unlockCoin(const COutPoint& output) = 0;
144
145
    //! Return whether coin is locked.
146
    virtual bool isLockedCoin(const COutPoint& output) = 0;
147
148
    //! List locked coins.
149
    virtual void listLockedCoins(std::vector<COutPoint>& outputs) = 0;
150
151
    //! Create transaction.
152
    virtual util::Result<wallet::CreatedTransactionResult> createTransaction(const std::vector<wallet::CRecipient>& recipients,
153
        const wallet::CCoinControl& coin_control,
154
        bool sign,
155
        std::optional<unsigned int> change_pos) = 0;
156
157
    //! Commit transaction.
158
    virtual void commitTransaction(CTransactionRef tx, const std::vector<std::string>& messages) = 0;
159
160
    //! Return whether transaction can be abandoned.
161
    virtual bool transactionCanBeAbandoned(const Txid& txid) = 0;
162
163
    //! Abandon transaction.
164
    virtual bool abandonTransaction(const Txid& txid) = 0;
165
166
    //! Return whether transaction can be bumped.
167
    virtual bool transactionCanBeBumped(const Txid& txid) = 0;
168
169
    //! Create bump transaction.
170
    virtual bool createBumpTransaction(const Txid& txid,
171
        const wallet::CCoinControl& coin_control,
172
        std::vector<bilingual_str>& errors,
173
        CAmount& old_fee,
174
        CAmount& new_fee,
175
        CMutableTransaction& mtx) = 0;
176
177
    //! Sign bump transaction.
178
    virtual bool signBumpTransaction(CMutableTransaction& mtx) = 0;
179
180
    //! Commit bump transaction.
181
    virtual bool commitBumpTransaction(const Txid& txid,
182
        CMutableTransaction&& mtx,
183
        std::vector<bilingual_str>& errors,
184
        Txid& bumped_txid) = 0;
185
186
    //! Get a transaction.
187
    virtual CTransactionRef getTx(const Txid& txid) = 0;
188
189
    //! Get transaction information.
190
    virtual WalletTx getWalletTx(const Txid& txid) = 0;
191
192
    //! Get list of all wallet transactions.
193
    virtual std::set<WalletTx> getWalletTxs() = 0;
194
195
    //! Try to get updated status for a particular transaction, if possible without blocking.
196
    virtual bool tryGetTxStatus(const Txid& txid,
197
        WalletTxStatus& tx_status,
198
        int& num_blocks,
199
        int64_t& block_time) = 0;
200
201
    //! Get transaction details.
202
    virtual WalletTx getWalletTxDetails(const Txid& txid,
203
        WalletTxStatus& tx_status,
204
        std::vector<std::string>& messages,
205
        std::vector<std::string>& payment_requests,
206
        bool& in_mempool,
207
        int& num_blocks) = 0;
208
209
    //! Fill PSBT.
210
    virtual std::optional<common::PSBTError> fillPSBT(const common::PSBTFillOptions& options,
211
        size_t* n_signed,
212
        PartiallySignedTransaction& psbtx,
213
        bool& complete) = 0;
214
215
    //! Import descriptors
216
    virtual std::vector<wallet::ImportResult> importDescriptors(std::vector<wallet::ImportDescriptorRequest>& requests) = 0;
217
218
    //! Get balances.
219
    virtual WalletBalances getBalances() = 0;
220
221
    //! Get balances if possible without blocking.
222
    virtual bool tryGetBalances(WalletBalances& balances, uint256& block_hash) = 0;
223
224
    //! Get balance.
225
    virtual CAmount getBalance() = 0;
226
227
    //! Get available balance.
228
    virtual CAmount getAvailableBalance(const wallet::CCoinControl& coin_control) = 0;
229
230
    //! Return whether transaction input belongs to wallet.
231
    virtual bool txinIsMine(const CTxIn& txin) = 0;
232
233
    //! Return whether transaction output belongs to wallet.
234
    virtual bool txoutIsMine(const CTxOut& txout) = 0;
235
236
    //! Return debit amount if transaction input belongs to wallet.
237
    virtual CAmount getDebit(const CTxIn& txin) = 0;
238
239
    //! Return credit amount if transaction input belongs to wallet.
240
    virtual CAmount getCredit(const CTxOut& txout) = 0;
241
242
    //! Return AvailableCoins + LockedCoins grouped by wallet address.
243
    //! (put change in one group with wallet address)
244
    using CoinsList = std::map<CTxDestination, std::vector<std::tuple<COutPoint, WalletTxOut>>>;
245
    virtual CoinsList listCoins() = 0;
246
247
    //! Return wallet transaction output information.
248
    virtual std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) = 0;
249
250
    //! Get required fee.
251
    virtual CAmount getRequiredFee(unsigned int tx_bytes) = 0;
252
253
    //! Get minimum fee.
254
    virtual CAmount getMinimumFee(unsigned int tx_bytes,
255
        const wallet::CCoinControl& coin_control,
256
        std::optional<int>* returned_target,
257
        FeeReason* reason) = 0;
258
259
    //! Get tx confirm target.
260
    virtual unsigned int getConfirmTarget() = 0;
261
262
    // Return whether HD enabled.
263
    virtual bool hdEnabled() = 0;
264
265
    // Return whether the wallet is blank.
266
    virtual bool canGetAddresses() = 0;
267
268
    // Return whether private keys enabled.
269
    virtual bool privateKeysDisabled() = 0;
270
271
    // Return whether the wallet contains a Taproot scriptPubKeyMan
272
    virtual bool taprootEnabled() = 0;
273
274
    // Return whether wallet uses an external signer.
275
    virtual bool hasExternalSigner() = 0;
276
277
    // Get default address type.
278
    virtual OutputType getDefaultAddressType() = 0;
279
280
    //! Get max tx fee.
281
    virtual CAmount getDefaultMaxTxFee() = 0;
282
283
    // Remove wallet.
284
    virtual void remove() = 0;
285
286
    //! Register handler for unload message.
287
    using UnloadFn = std::function<void()>;
288
    virtual std::unique_ptr<Handler> handleUnload(UnloadFn fn) = 0;
289
290
    //! Register handler for show progress messages.
291
    using ShowProgressFn = std::function<void(const std::string& title, int progress)>;
292
    virtual std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) = 0;
293
294
    //! Register handler for status changed messages.
295
    using StatusChangedFn = std::function<void()>;
296
    virtual std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) = 0;
297
298
    //! Register handler for address book changed messages.
299
    using AddressBookChangedFn = std::function<void(const CTxDestination& address,
300
        const std::string& label,
301
        bool is_mine,
302
        wallet::AddressPurpose purpose,
303
        ChangeType status)>;
304
    virtual std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) = 0;
305
306
    //! Register handler for transaction changed messages.
307
    using TransactionChangedFn = std::function<void(const Txid& txid, ChangeType status)>;
308
    virtual std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) = 0;
309
310
    //! Register handler for keypool changed messages.
311
    using CanGetAddressesChangedFn = std::function<void()>;
312
    virtual std::unique_ptr<Handler> handleCanGetAddressesChanged(CanGetAddressesChangedFn fn) = 0;
313
314
    //! Return pointer to internal wallet class, useful for testing.
315
0
    virtual wallet::CWallet* wallet() { return nullptr; }
316
317
    //! Export a watchonly wallet file. See CWallet::ExportWatchOnlyWallet
318
    virtual util::Result<std::string> exportWatchOnlyWallet(const fs::path& destination) = 0;
319
};
320
321
//! Wallet chain client that in addition to having chain client methods for
322
//! starting up, shutting down, and registering RPCs, also has additional
323
//! methods (called by the GUI) to load and create wallets.
324
class WalletLoader : public ChainClient
325
{
326
public:
327
    //! Create new wallet.
328
    virtual util::Result<std::unique_ptr<Wallet>> createWallet(const std::string& name, const SecureString& passphrase, uint64_t wallet_creation_flags, std::vector<bilingual_str>& warnings) = 0;
329
330
    //! Load existing wallet.
331
    virtual util::Result<std::unique_ptr<Wallet>> loadWallet(const std::string& name, std::vector<bilingual_str>& warnings) = 0;
332
333
    //! Return default wallet directory.
334
    virtual std::string getWalletDir() = 0;
335
336
    //! Restore backup wallet
337
    virtual 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) = 0;
338
339
    //! Migrate a wallet
340
    virtual util::Result<WalletMigrationResult> migrateWallet(const std::string& name, const SecureString& passphrase, bool load_wallet) = 0;
341
342
    //! Returns true if wallet stores encryption keys
343
    virtual bool isEncrypted(const std::string& wallet_name) = 0;
344
345
    //! Return available wallets in wallet directory.
346
    virtual std::vector<std::pair<std::string, std::string>> listWalletDir() = 0;
347
348
    //! Return interfaces for accessing wallets (if any).
349
    virtual std::vector<std::unique_ptr<Wallet>> getWallets() = 0;
350
351
    //! Register handler for load wallet messages. This callback is triggered by
352
    //! createWallet and loadWallet above, and also triggered when wallets are
353
    //! loaded at startup or by RPC.
354
    using LoadWalletFn = std::function<void(std::unique_ptr<Wallet> wallet)>;
355
    virtual std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) = 0;
356
357
    //! Return pointer to internal context, useful for testing.
358
0
    virtual wallet::WalletContext* context() { return nullptr; }
359
};
360
361
//! Information about one wallet address.
362
struct WalletAddress
363
{
364
    CTxDestination dest;
365
    bool is_mine;
366
    wallet::AddressPurpose purpose;
367
    std::string name;
368
369
    WalletAddress(CTxDestination dest, bool is_mine, wallet::AddressPurpose purpose, std::string name)
370
0
        : dest(std::move(dest)), is_mine(is_mine), purpose(std::move(purpose)), name(std::move(name))
371
0
    {
372
0
    }
373
};
374
375
//! Collection of wallet balances.
376
struct WalletBalances
377
{
378
    CAmount balance = 0;
379
    CAmount unconfirmed_balance = 0;
380
    CAmount immature_balance = 0;
381
    CAmount used_balance = 0;
382
    CAmount nonmempool_balance = 0;
383
384
    bool balanceChanged(const WalletBalances& prev) const
385
0
    {
386
0
        return balance != prev.balance || unconfirmed_balance != prev.unconfirmed_balance ||
387
0
               immature_balance != prev.immature_balance ||
388
0
               used_balance != prev.used_balance || nonmempool_balance != prev.nonmempool_balance;
389
0
    }
390
};
391
392
// Wallet transaction information.
393
struct WalletTx
394
{
395
    CTransactionRef tx;
396
    std::vector<bool> txin_is_mine;
397
    std::vector<bool> txout_is_mine;
398
    std::vector<bool> txout_is_change;
399
    std::vector<CTxDestination> txout_address;
400
    std::vector<bool> txout_address_is_mine;
401
    CAmount credit;
402
    CAmount debit;
403
    CAmount change;
404
    int64_t time;
405
    std::optional<std::string> from; // Deprecated
406
    std::optional<std::string> message; // Deprecated
407
    std::optional<std::string> comment;
408
    std::optional<std::string> comment_to;
409
    bool is_coinbase;
410
411
0
    bool operator<(const WalletTx& a) const { return tx->GetHash() < a.tx->GetHash(); }
412
};
413
414
//! Updated transaction status.
415
struct WalletTxStatus
416
{
417
    int block_height;
418
    int blocks_to_maturity;
419
    int depth_in_main_chain;
420
    unsigned int time_received;
421
    uint32_t lock_time;
422
    bool is_trusted;
423
    bool is_abandoned;
424
    bool is_coinbase;
425
    bool is_in_main_chain;
426
};
427
428
//! Wallet transaction output.
429
struct WalletTxOut
430
{
431
    CTxOut txout;
432
    int64_t time;
433
    int depth_in_main_chain = -1;
434
    bool is_spent = false;
435
};
436
437
//! Migrated wallet info
438
struct WalletMigrationResult
439
{
440
    std::unique_ptr<Wallet> wallet;
441
    std::optional<std::string> watchonly_wallet_name;
442
    std::optional<std::string> solvables_wallet_name;
443
    fs::path backup_path;
444
};
445
446
//! Return implementation of Wallet interface. This function is defined in
447
//! dummywallet.cpp and throws if the wallet component is not compiled.
448
std::unique_ptr<Wallet> MakeWallet(wallet::WalletContext& context, const std::shared_ptr<wallet::CWallet>& wallet);
449
450
//! Return implementation of ChainClient interface for a wallet loader. This
451
//! function will be undefined in builds where ENABLE_WALLET is false.
452
std::unique_ptr<WalletLoader> MakeWalletLoader(Chain& chain, ArgsManager& args);
453
454
} // namespace interfaces
455
456
#endif // BITCOIN_INTERFACES_WALLET_H