Coverage Report

Created: 2026-04-29 19:21

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