Line data Source code
1 : // Copyright (c) 2018-2021 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 <consensus/amount.h> // For CAmount
9 : #include <fs.h>
10 : #include <governance/common.h>
11 : #include <interfaces/chain.h> // For ChainClient
12 : #include <pubkey.h> // For CKeyID and CScriptID (definitions needed in CTxDestination instantiation)
13 : #include <script/standard.h> // For CTxDestination
14 : #include <support/allocators/secure.h> // For SecureString
15 : #include <util/message.h>
16 : #include <util/result.h>
17 : #include <util/ui_change_type.h>
18 :
19 : #include <cstdint>
20 : #include <functional>
21 : #include <map>
22 : #include <memory>
23 : #include <psbt.h>
24 : #include <set>
25 : #include <string>
26 : #include <tuple>
27 : #include <type_traits>
28 : #include <utility>
29 : #include <vector>
30 :
31 : class CFeeRate;
32 : class CGovernanceVote;
33 : class CKey;
34 : class CRPCCommand;
35 : enum class FeeReason;
36 : enum class TransactionError;
37 : struct bilingual_str;
38 : struct PartiallySignedTransaction;
39 : namespace node {
40 : struct NodeContext;
41 : } // namespace node
42 : namespace wallet {
43 : class CCoinControl;
44 : class CWallet;
45 : enum isminetype : unsigned int;
46 : enum class RescanStatus : uint8_t;
47 : struct CRecipient;
48 : struct WalletContext;
49 : using isminefilter = std::underlying_type<isminetype>::type;
50 : } // namespace wallet
51 :
52 : class UniValue;
53 :
54 : template <typename T>
55 : class Span;
56 :
57 : namespace interfaces {
58 :
59 : class Handler;
60 : struct WalletAddress;
61 : struct WalletBalances;
62 : struct WalletTx;
63 : struct WalletTxOut;
64 : struct WalletTxStatus;
65 : namespace CoinJoin {
66 : class Loader;
67 : }
68 :
69 : using WalletOrderForm = std::vector<std::pair<std::string, std::string>>;
70 : using WalletValueMap = std::map<std::string, std::string>;
71 :
72 : //! Interface for accessing a wallet.
73 : class Wallet
74 : {
75 : public:
76 13170 : virtual ~Wallet() {}
77 :
78 : //! Mark wallet as dirty
79 : virtual void markDirty() = 0;
80 :
81 : //! Encrypt wallet.
82 : virtual bool encryptWallet(const SecureString& wallet_passphrase) = 0;
83 :
84 : //! Return whether wallet is encrypted.
85 : virtual bool isCrypted() = 0;
86 :
87 : //! Lock wallet.
88 : virtual bool lock(bool fAllowMixing = false) = 0;
89 :
90 : //! Unlock wallet.
91 : virtual bool unlock(const SecureString& wallet_passphrase, bool fAllowMixing = false) = 0;
92 :
93 : //! Return whether wallet is locked.
94 : virtual bool isLocked(bool fForMixing = false) = 0;
95 :
96 : //! Change wallet passphrase.
97 : virtual bool changeWalletPassphrase(const SecureString& old_wallet_passphrase,
98 : const SecureString& new_wallet_passphrase) = 0;
99 :
100 : //! Initiate a rescan. Returns status indicating success, failure, abort, or already rescanning.
101 : virtual wallet::RescanStatus startRescan(bool from_genesis) = 0;
102 :
103 : //! Abort a rescan.
104 : virtual void abortRescan() = 0;
105 :
106 : //! Lock masternode collaterals
107 : virtual void autoLockMasternodeCollaterals() = 0;
108 :
109 : //! Back up wallet.
110 : virtual bool backupWallet(const std::string& filename) = 0;
111 :
112 : //! Automatically backup up wallet.
113 : virtual bool autoBackupWallet(const fs::path& wallet_path, bilingual_str& error_string, std::vector<bilingual_str>& warnings) = 0;
114 :
115 : //! Get the number of keys since the last auto backup
116 : virtual int64_t getKeysLeftSinceAutoBackup() = 0;
117 :
118 : //! Get wallet name.
119 : virtual std::string getWalletName() = 0;
120 :
121 : // Get a new address.
122 : virtual util::Result<CTxDestination> getNewDestination(const std::string& label) = 0;
123 :
124 : //! Get public key.
125 : virtual bool getPubKey(const CScript& script, const CKeyID& address, CPubKey& pub_key) = 0;
126 :
127 : //! Sign message
128 : virtual SigningResult signMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) = 0;
129 :
130 : //! Sign special transaction payload
131 : virtual bool signSpecialTxPayload(const uint256& hash, const CKeyID& keyid, std::vector<unsigned char>& vchSig) = 0;
132 :
133 : //! Return whether wallet has private key.
134 : virtual bool isSpendable(const CScript& script) = 0;
135 : virtual bool isSpendable(const CTxDestination& dest) = 0;
136 :
137 : //! Return whether wallet has watch only keys.
138 : virtual bool haveWatchOnly() = 0;
139 :
140 : //! Add or update address.
141 : virtual bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::string& purpose) = 0;
142 :
143 : // Remove address.
144 : virtual bool delAddressBook(const CTxDestination& dest) = 0;
145 :
146 : //! Look up address in wallet, return whether exists.
147 : virtual bool getAddress(const CTxDestination& dest,
148 : std::string* name,
149 : wallet::isminetype* is_mine,
150 : std::string* purpose) = 0;
151 :
152 : //! Get wallet address list.
153 : virtual std::vector<WalletAddress> getAddresses() const = 0;
154 :
155 : //! Get receive requests.
156 : virtual std::vector<std::string> getAddressReceiveRequests() = 0;
157 :
158 : //! Save or remove receive request.
159 : virtual bool setAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& value) = 0;
160 :
161 : //! Display address on external signer
162 : virtual bool displayAddress(const CTxDestination& dest) = 0;
163 :
164 : //! Lock coin.
165 : virtual bool lockCoin(const COutPoint& output, const bool write_to_db) = 0;
166 :
167 : //! Unlock coin.
168 : virtual bool unlockCoin(const COutPoint& output) = 0;
169 :
170 : //! Return whether coin is locked.
171 : virtual bool isLockedCoin(const COutPoint& output) = 0;
172 :
173 : //! List locked coins.
174 : virtual std::set<COutPoint> listLockedCoins() = 0;
175 :
176 : //! Lock the provided coins in a single batch.
177 : virtual bool lockCoins(const std::vector<COutPoint>& outputs) = 0;
178 :
179 : //! Unlock the provided coins in a single batch.
180 : virtual bool unlockCoins(const std::vector<COutPoint>& outputs) = 0;
181 :
182 : //! Set dust protection threshold (does not lock anything by itself).
183 : virtual void setDustProtectionThreshold(CAmount threshold) = 0;
184 :
185 : //! Lock all existing dust UTXOs that match the current threshold.
186 : virtual void lockExistingDustOutputs() = 0;
187 :
188 : //! List protx coins.
189 : virtual std::vector<COutPoint> listProTxCoins() = 0;
190 :
191 : //! Create transaction.
192 : virtual util::Result<CTransactionRef> createTransaction(const std::vector<wallet::CRecipient>& recipients,
193 : const wallet::CCoinControl& coin_control,
194 : bool sign,
195 : int& change_pos,
196 : CAmount& fee) = 0;
197 :
198 : //! Commit transaction.
199 : virtual void commitTransaction(CTransactionRef tx,
200 : WalletValueMap value_map,
201 : WalletOrderForm order_form) = 0;
202 :
203 : //! Return whether transaction can be abandoned.
204 : virtual bool transactionCanBeAbandoned(const uint256& txid) = 0;
205 :
206 : //! Return whether transaction can be resent.
207 : virtual bool transactionCanBeResent(const uint256& txid) = 0;
208 :
209 : //! Abandon transaction.
210 : virtual bool abandonTransaction(const uint256& txid) = 0;
211 :
212 : //! Resend transaction.
213 : virtual bool resendTransaction(const uint256& txid) = 0;
214 :
215 : //! Get a transaction.
216 : virtual CTransactionRef getTx(const uint256& txid) = 0;
217 :
218 : //! Get transaction information.
219 : virtual WalletTx getWalletTx(const uint256& txid) = 0;
220 :
221 : //! Get list of all wallet transactions.
222 : virtual std::set<WalletTx> getWalletTxs() = 0;
223 :
224 : //! Try to get updated status for a particular transaction, if possible without blocking.
225 : virtual bool tryGetTxStatus(const uint256& txid,
226 : WalletTxStatus& tx_status,
227 : int& num_blocks,
228 : int64_t& block_time) = 0;
229 :
230 : //! Get transaction details.
231 : virtual WalletTx getWalletTxDetails(const uint256& txid,
232 : WalletTxStatus& tx_status,
233 : WalletOrderForm& order_form,
234 : bool& in_mempool,
235 : int& num_blocks) = 0;
236 :
237 : // Get the number of coinjoin rounds an output went through
238 : virtual int getRealOutpointCoinJoinRounds(const COutPoint& outpoint) = 0;
239 :
240 : // Check if an outpoint is fully mixed
241 : virtual bool isFullyMixed(const COutPoint& outpoint) = 0;
242 :
243 : //! Fill PSBT.
244 : virtual TransactionError fillPSBT(int sighash_type,
245 : bool sign,
246 : bool bip32derivs,
247 : size_t* n_signed,
248 : PartiallySignedTransaction& psbtx,
249 : bool& complete) = 0;
250 :
251 : //! Get balances.
252 : virtual WalletBalances getBalances() = 0;
253 :
254 : //! Get balances if possible without blocking.
255 : virtual bool tryGetBalances(WalletBalances& balances, uint256& block_hash) = 0;
256 :
257 : //! Get balance.
258 : virtual CAmount getBalance() = 0;
259 :
260 : //! Get anonymizable balance.
261 : virtual CAmount getAnonymizableBalance(bool fSkipDenominated, bool fSkipUnconfirmed) = 0;
262 :
263 : //! Get normalized anonymized balance.
264 : virtual CAmount getNormalizedAnonymizedBalance() = 0;
265 :
266 : //! Get average anonymized rounds.
267 : virtual CAmount getAverageAnonymizedRounds() = 0;
268 :
269 : //! Get available balance.
270 : virtual CAmount getAvailableBalance(const wallet::CCoinControl& coin_control) = 0;
271 :
272 : //! Return whether transaction input belongs to wallet.
273 : virtual wallet::isminetype txinIsMine(const CTxIn& txin) = 0;
274 :
275 : //! Return whether transaction output belongs to wallet.
276 : virtual wallet::isminetype txoutIsMine(const CTxOut& txout) = 0;
277 :
278 : //! Return debit amount if transaction input belongs to wallet.
279 : virtual CAmount getDebit(const CTxIn& txin, wallet::isminefilter filter) = 0;
280 :
281 : //! Return credit amount if transaction input belongs to wallet.
282 : virtual CAmount getCredit(const CTxOut& txout, wallet::isminefilter filter) = 0;
283 :
284 : //! Return AvailableCoins + LockedCoins grouped by wallet address.
285 : //! (put change in one group with wallet address)
286 : using CoinsList = std::map<CTxDestination, std::vector<std::tuple<COutPoint, WalletTxOut>>>;
287 : virtual CoinsList listCoins() = 0;
288 :
289 : //! Return wallet transaction output information.
290 : virtual std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) = 0;
291 :
292 : //! Get required fee.
293 : virtual CAmount getRequiredFee(unsigned int tx_bytes) = 0;
294 :
295 : //! Get minimum fee.
296 : virtual CAmount getMinimumFee(unsigned int tx_bytes,
297 : const wallet::CCoinControl& coin_control,
298 : int* returned_target,
299 : FeeReason* reason) = 0;
300 :
301 : //! Get tx confirm target.
302 : virtual unsigned int getConfirmTarget() = 0;
303 :
304 : // Return whether HD enabled.
305 : virtual bool hdEnabled() = 0;
306 :
307 : // Return whether the wallet is blank.
308 : virtual bool canGetAddresses() = 0;
309 :
310 : // Return whether private keys enabled.
311 : virtual bool privateKeysDisabled() = 0;
312 :
313 : // Return whether wallet uses an external signer.
314 : virtual bool hasExternalSigner() = 0;
315 :
316 : //! Get max tx fee.
317 : virtual CAmount getDefaultMaxTxFee() = 0;
318 :
319 : // Remove wallet.
320 : virtual void remove() = 0;
321 :
322 : //! Return whether is a legacy wallet
323 : virtual bool isLegacy() = 0;
324 :
325 : //! Get mnemonic phrase from wallet.
326 : virtual bool getMnemonic(SecureString& mnemonic_out, SecureString& mnemonic_passphrase_out) = 0;
327 :
328 : //! Register handler for unload message.
329 : using UnloadFn = std::function<void()>;
330 : virtual std::unique_ptr<Handler> handleUnload(UnloadFn fn) = 0;
331 :
332 : //! Register handler for show progress messages.
333 : using ShowProgressFn = std::function<void(const std::string& title, int progress)>;
334 : virtual std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) = 0;
335 :
336 : //! Register handler for status changed messages.
337 : using StatusChangedFn = std::function<void()>;
338 : virtual std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) = 0;
339 :
340 : //! Register handler for address book changed messages.
341 : using AddressBookChangedFn = std::function<void(const CTxDestination& address,
342 : const std::string& label,
343 : bool is_mine,
344 : const std::string& purpose,
345 : ChangeType status)>;
346 : virtual std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) = 0;
347 :
348 : //! Register handler for transaction changed messages.
349 : using TransactionChangedFn = std::function<void(const uint256& txid, ChangeType status)>;
350 : virtual std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) = 0;
351 :
352 : //! Register handler for instantlock messages.
353 : using InstantLockReceivedFn = std::function<void()>;
354 : virtual std::unique_ptr<Handler> handleInstantLockReceived(InstantLockReceivedFn fn) = 0;
355 :
356 : //! Register handler for chainlock messages.
357 : using ChainLockReceivedFn = std::function<void(int chainLockHeight)>;
358 : virtual std::unique_ptr<Handler> handleChainLockReceived(ChainLockReceivedFn fn) = 0;
359 :
360 : //! Register handler for watchonly changed messages.
361 : using WatchOnlyChangedFn = std::function<void(bool have_watch_only)>;
362 : virtual std::unique_ptr<Handler> handleWatchOnlyChanged(WatchOnlyChangedFn fn) = 0;
363 :
364 : //! Register handler for keypool changed messages.
365 : using CanGetAddressesChangedFn = std::function<void()>;
366 : virtual std::unique_ptr<Handler> handleCanGetAddressesChanged(CanGetAddressesChangedFn fn) = 0;
367 :
368 : //! Get governance objects stored in the wallet.
369 : virtual std::vector<Governance::Object> getGovernanceObjects() = 0;
370 :
371 : //! Prepare a governance proposal (burns fee).
372 : virtual bool prepareProposal(const uint256& govobj_hash, CAmount fee, int32_t revision, int64_t created_time,
373 : const std::string& data_hex, const COutPoint& outpoint,
374 : std::string& out_fee_txid, std::string& error) = 0;
375 :
376 : //! Sign a governance vote with the given voting key.
377 : virtual bool signGovernanceVote(const CKeyID& keyID, CGovernanceVote& vote) = 0;
378 :
379 : //! Return pointer to internal wallet class, useful for testing.
380 0 : virtual wallet::CWallet* wallet() { return nullptr; }
381 : };
382 :
383 : //! Wallet chain client that in addition to having chain client methods for
384 : //! starting up, shutting down, and registering RPCs, also has additional
385 : //! methods (called by the GUI) to load and create wallets.
386 : class WalletLoader : public ChainClient
387 : {
388 : public:
389 : //! Register non-core wallet RPCs
390 : virtual void registerOtherRpcs(const Span<const CRPCCommand>& commands) = 0;
391 :
392 : //! Create new wallet.
393 : 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;
394 :
395 : //! Load existing wallet.
396 : virtual util::Result<std::unique_ptr<Wallet>> loadWallet(const std::string& name, std::vector<bilingual_str>& warnings) = 0;
397 :
398 : //! Return default wallet directory.
399 : virtual std::string getWalletDir() = 0;
400 :
401 : //! Restore backup wallet
402 : virtual util::Result<std::unique_ptr<Wallet>> restoreWallet(const fs::path& backup_file, const std::string& wallet_name, std::vector<bilingual_str>& warnings) = 0;
403 :
404 : //! Return available wallets in wallet directory.
405 : virtual std::vector<std::string> listWalletDir() = 0;
406 :
407 : //! Return interfaces for accessing wallets (if any).
408 : virtual std::vector<std::unique_ptr<Wallet>> getWallets() = 0;
409 :
410 : //! Register handler for load wallet messages. This callback is triggered by
411 : //! createWallet and loadWallet above, and also triggered when wallets are
412 : //! loaded at startup or by RPC.
413 : using LoadWalletFn = std::function<void(std::unique_ptr<Wallet> wallet)>;
414 : virtual std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) = 0;
415 :
416 : //! Register handler for wallet-loading messages. This callback is triggered
417 : //! after a wallet object exists and can emit progress, but before startup
418 : //! load work like AttachChain()/rescan necessarily completes.
419 : virtual std::unique_ptr<Handler> handleLoadWalletLoading(LoadWalletFn fn) = 0;
420 :
421 : //! Return pointer to internal context, useful for testing.
422 0 : virtual wallet::WalletContext* context() { return nullptr; }
423 : };
424 :
425 : //! Information about one wallet address.
426 : struct WalletAddress
427 : {
428 : CTxDestination dest;
429 : wallet::isminetype is_mine;
430 : std::string name;
431 : std::string purpose;
432 :
433 0 : WalletAddress(CTxDestination dest, wallet::isminetype is_mine, std::string name, std::string purpose)
434 0 : : dest(std::move(dest)), is_mine(is_mine), name(std::move(name)), purpose(std::move(purpose))
435 0 : {
436 0 : }
437 : };
438 :
439 : //! Collection of wallet balances.
440 0 : struct WalletBalances
441 : {
442 0 : CAmount balance = 0;
443 0 : CAmount unconfirmed_balance = 0;
444 0 : CAmount immature_balance = 0;
445 0 : CAmount anonymized_balance = 0;
446 0 : bool have_watch_only = false;
447 0 : CAmount watch_only_balance = 0;
448 0 : CAmount unconfirmed_watch_only_balance = 0;
449 0 : CAmount immature_watch_only_balance = 0;
450 0 : CAmount denominated_untrusted_pending = 0;
451 0 : CAmount denominated_trusted = 0;
452 :
453 : bool balanceChanged(const WalletBalances& prev) const
454 : {
455 : return balance != prev.balance || unconfirmed_balance != prev.unconfirmed_balance || anonymized_balance != prev.anonymized_balance ||
456 : immature_balance != prev.immature_balance || watch_only_balance != prev.watch_only_balance ||
457 : unconfirmed_watch_only_balance != prev.unconfirmed_watch_only_balance ||
458 : immature_watch_only_balance != prev.immature_watch_only_balance;
459 : }
460 : };
461 :
462 : // Wallet transaction information.
463 0 : struct WalletTx
464 : {
465 : CTransactionRef tx;
466 : std::vector<wallet::isminetype> txin_is_mine;
467 : std::vector<wallet::isminetype> txout_is_mine;
468 : std::vector<CTxDestination> txout_address;
469 : std::vector<wallet::isminetype> txout_address_is_mine;
470 : CAmount credit;
471 : CAmount debit;
472 : CAmount change;
473 : int64_t time;
474 : std::map<std::string, std::string> value_map;
475 : bool is_coinbase;
476 0 : bool is_platform_transfer{false};
477 : bool is_denominate;
478 :
479 0 : bool operator<(const WalletTx& a) const { return tx->GetHash() < a.tx->GetHash(); }
480 : };
481 :
482 : //! Updated transaction status.
483 : struct WalletTxStatus
484 : {
485 : int block_height;
486 : int blocks_to_maturity;
487 : int depth_in_main_chain;
488 : unsigned int time_received;
489 : uint32_t lock_time;
490 : bool is_trusted;
491 : bool is_abandoned;
492 : bool is_coinbase;
493 : bool is_in_main_chain;
494 : bool is_chainlocked;
495 : bool is_islocked;
496 : };
497 :
498 : //! Wallet transaction output.
499 0 : struct WalletTxOut
500 : {
501 : CTxOut txout;
502 : int64_t time;
503 0 : int depth_in_main_chain = -1;
504 0 : bool is_spent = false;
505 : };
506 :
507 : //! Return implementation of Wallet interface. This function is defined in
508 : //! dummywallet.cpp and throws if the wallet component is not compiled.
509 : std::unique_ptr<Wallet> MakeWallet(wallet::WalletContext& context, const std::shared_ptr<wallet::CWallet>& wallet);
510 :
511 : //! Return implementation of ChainClient interface for a wallet loader. This
512 : //! function will be undefined in builds where ENABLE_WALLET is false.
513 : std::unique_ptr<WalletLoader> MakeWalletLoader(Chain& chain, ArgsManager& args, node::NodeContext& node_context,
514 : CoinJoin::Loader& coinjoin_loader);
515 :
516 : } // namespace interfaces
517 :
518 : #endif // BITCOIN_INTERFACES_WALLET_H
|