Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2020 The Bitcoin Core developers
3 : // Distributed under the MIT software license, see the accompanying
4 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 :
6 : #ifndef BITCOIN_WALLET_WALLET_H
7 : #define BITCOIN_WALLET_WALLET_H
8 :
9 : #include <amount.h>
10 : #include <interfaces/chain.h>
11 : #include <interfaces/handler.h>
12 : #include <outputtype.h>
13 : #include <policy/feerate.h>
14 : #include <psbt.h>
15 : #include <tinyformat.h>
16 : #include <util/message.h>
17 : #include <util/strencodings.h>
18 : #include <util/string.h>
19 : #include <util/system.h>
20 : #include <util/ui_change_type.h>
21 : #include <validationinterface.h>
22 : #include <wallet/coinselection.h>
23 : #include <wallet/crypter.h>
24 : #include <wallet/scriptpubkeyman.h>
25 : #include <wallet/walletdb.h>
26 : #include <wallet/walletutil.h>
27 :
28 : #include <algorithm>
29 : #include <atomic>
30 : #include <map>
31 : #include <memory>
32 : #include <set>
33 : #include <stdexcept>
34 : #include <stdint.h>
35 : #include <string>
36 : #include <utility>
37 : #include <vector>
38 :
39 : #include <boost/signals2/signal.hpp>
40 :
41 : using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
42 :
43 : struct bilingual_str;
44 :
45 : //! Explicitly unload and delete the wallet.
46 : //! Blocks the current thread after signaling the unload intent so that all
47 : //! wallet clients release the wallet.
48 : //! Note that, when blocking is not required, the wallet is implicitly unloaded
49 : //! by the shared pointer deleter.
50 : void UnloadWallet(std::shared_ptr<CWallet>&& wallet);
51 :
52 : bool AddWallet(const std::shared_ptr<CWallet>& wallet);
53 : bool RemoveWallet(const std::shared_ptr<CWallet>& wallet, Optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
54 : bool RemoveWallet(const std::shared_ptr<CWallet>& wallet, Optional<bool> load_on_start);
55 : std::vector<std::shared_ptr<CWallet>> GetWallets();
56 : std::shared_ptr<CWallet> GetWallet(const std::string& name);
57 : std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const std::string& name, Optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings);
58 : std::shared_ptr<CWallet> CreateWallet(interfaces::Chain& chain, const std::string& name, Optional<bool> load_on_start, DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings);
59 : std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet);
60 : std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
61 :
62 : //! -paytxfee default
63 : constexpr CAmount DEFAULT_PAY_TX_FEE = 0;
64 : //! -fallbackfee default
65 : static const CAmount DEFAULT_FALLBACK_FEE = 0;
66 : //! -discardfee default
67 : static const CAmount DEFAULT_DISCARD_FEE = 10000;
68 : //! -mintxfee default
69 : static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
70 : /**
71 : * maximum fee increase allowed to do partial spend avoidance, even for nodes with this feature disabled by default
72 : *
73 : * A value of -1 disables this feature completely.
74 : * A value of 0 (current default) means to attempt to do partial spend avoidance, and use its results if the fees remain *unchanged*
75 : * A value > 0 means to do partial spend avoidance if the fee difference against a regular coin selection instance is in the range [0..value].
76 : */
77 : static const CAmount DEFAULT_MAX_AVOIDPARTIALSPEND_FEE = 0;
78 : //! discourage APS fee higher than this amount
79 : constexpr CAmount HIGH_APS_FEE{COIN / 10000};
80 : //! minimum recommended increment for BIP 125 replacement txs
81 : static const CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000;
82 : //! Default for -spendzeroconfchange
83 : static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
84 : //! Default for -walletrejectlongchains
85 : static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
86 : //! -txconfirmtarget default
87 : static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
88 : //! -walletrbf default
89 : static const bool DEFAULT_WALLET_RBF = false;
90 : static const bool DEFAULT_WALLETBROADCAST = true;
91 : static const bool DEFAULT_DISABLE_WALLET = false;
92 : //! -maxtxfee default
93 : constexpr CAmount DEFAULT_TRANSACTION_MAXFEE{COIN / 10};
94 : //! Discourage users to set fees higher than this amount (in satoshis) per kB
95 : constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
96 : //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
97 : constexpr CAmount HIGH_MAX_TX_FEE{100 * HIGH_TX_FEE_PER_KB};
98 :
99 : //! Pre-calculated constants for input size estimation in *virtual size*
100 : static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
101 :
102 : class CCoinControl;
103 : class COutput;
104 : class CScript;
105 : class CWalletTx;
106 : struct FeeCalculation;
107 : enum class FeeEstimateMode;
108 : class ReserveDestination;
109 :
110 : //! Default for -addresstype
111 : constexpr OutputType DEFAULT_ADDRESS_TYPE{OutputType::BECH32};
112 :
113 : static constexpr uint64_t KNOWN_WALLET_FLAGS =
114 : WALLET_FLAG_AVOID_REUSE
115 : | WALLET_FLAG_BLANK_WALLET
116 : | WALLET_FLAG_KEY_ORIGIN_METADATA
117 : | WALLET_FLAG_DISABLE_PRIVATE_KEYS
118 : | WALLET_FLAG_DESCRIPTORS;
119 :
120 : static constexpr uint64_t MUTABLE_WALLET_FLAGS =
121 : WALLET_FLAG_AVOID_REUSE;
122 :
123 32095 : static const std::map<std::string,WalletFlags> WALLET_FLAG_MAP{
124 6419 : {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
125 6419 : {"blank", WALLET_FLAG_BLANK_WALLET},
126 6419 : {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
127 6419 : {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
128 6419 : {"descriptor_wallet", WALLET_FLAG_DESCRIPTORS},
129 : };
130 :
131 : extern const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS;
132 :
133 : /** A wrapper to reserve an address from a wallet
134 : *
135 : * ReserveDestination is used to reserve an address.
136 : * It is currently only used inside of CreateTransaction.
137 : *
138 : * Instantiating a ReserveDestination does not reserve an address. To do so,
139 : * GetReservedDestination() needs to be called on the object. Once an address has been
140 : * reserved, call KeepDestination() on the ReserveDestination object to make sure it is not
141 : * returned. Call ReturnDestination() to return the address so it can be re-used (for
142 : * example, if the address was used in a new transaction
143 : * and that transaction was not completed and needed to be aborted).
144 : *
145 : * If an address is reserved and KeepDestination() is not called, then the address will be
146 : * returned when the ReserveDestination goes out of scope.
147 : */
148 : class ReserveDestination
149 : {
150 : protected:
151 : //! The wallet to reserve from
152 : const CWallet* const pwallet;
153 : //! The ScriptPubKeyMan to reserve from. Based on type when GetReservedDestination is called
154 2707 : ScriptPubKeyMan* m_spk_man{nullptr};
155 : OutputType const type;
156 : //! The index of the address's key in the keypool
157 2707 : int64_t nIndex{-1};
158 : //! The destination
159 : CTxDestination address;
160 : //! Whether this is from the internal (change output) keypool
161 2707 : bool fInternal{false};
162 :
163 : public:
164 : //! Construct a ReserveDestination object. This does NOT reserve an address yet
165 5414 : explicit ReserveDestination(CWallet* pwallet, OutputType type)
166 2707 : : pwallet(pwallet)
167 8121 : , type(type) { }
168 :
169 : ReserveDestination(const ReserveDestination&) = delete;
170 : ReserveDestination& operator=(const ReserveDestination&) = delete;
171 :
172 : //! Destructor. If a key has been reserved and not KeepKey'ed, it will be returned to the keypool
173 5414 : ~ReserveDestination()
174 2707 : {
175 2707 : ReturnDestination();
176 5414 : }
177 :
178 : //! Reserve an address
179 : bool GetReservedDestination(CTxDestination& pubkey, bool internal);
180 : //! Return reserved address
181 : void ReturnDestination();
182 : //! Keep the address. Do not return it's key to the keypool when this object goes out of scope
183 : void KeepDestination();
184 : };
185 :
186 : /** Address book data */
187 26498 : class CAddressBookData
188 : {
189 : private:
190 13249 : bool m_change{true};
191 : std::string m_label;
192 : public:
193 : std::string purpose;
194 :
195 26498 : CAddressBookData() : purpose("unknown") {}
196 :
197 : typedef std::map<std::string, std::string> StringMap;
198 : StringMap destdata;
199 :
200 52717 : bool IsChange() const { return m_change; }
201 51645 : const std::string& GetLabel() const { return m_label; }
202 13315 : void SetLabel(const std::string& label) {
203 13315 : m_change = false;
204 13315 : m_label = label;
205 13315 : }
206 : };
207 :
208 178758 : struct CRecipient
209 : {
210 : CScript scriptPubKey;
211 : CAmount nAmount;
212 : bool fSubtractFeeFromAmount;
213 : };
214 :
215 : typedef std::map<std::string, std::string> mapValue_t;
216 :
217 :
218 9580 : static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
219 : {
220 9580 : if (!mapValue.count("n"))
221 : {
222 0 : nOrderPos = -1; // TODO: calculate elsewhere
223 0 : return;
224 : }
225 9580 : nOrderPos = atoi64(mapValue["n"]);
226 9580 : }
227 :
228 :
229 140360 : static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
230 : {
231 140360 : if (nOrderPos == -1)
232 : return;
233 140360 : mapValue["n"] = ToString(nOrderPos);
234 140360 : }
235 :
236 117650 : struct COutputEntry
237 : {
238 : CTxDestination destination;
239 : CAmount amount;
240 : int vout;
241 : };
242 :
243 : /** Legacy class used for deserializing vtxPrev for backwards compatibility.
244 : * vtxPrev was removed in commit 93a18a3650292afbb441a47d1fa1b94aeb0164e3,
245 : * but old wallet.dat files may still contain vtxPrev vectors of CMerkleTxs.
246 : * These need to get deserialized for field alignment when deserializing
247 : * a CWalletTx, but the deserialized values are discarded.**/
248 : class CMerkleTx
249 : {
250 : public:
251 : template<typename Stream>
252 0 : void Unserialize(Stream& s)
253 : {
254 0 : CTransactionRef tx;
255 0 : uint256 hashBlock;
256 0 : std::vector<uint256> vMerkleBranch;
257 0 : int nIndex;
258 :
259 0 : s >> tx >> hashBlock >> vMerkleBranch >> nIndex;
260 0 : }
261 : };
262 :
263 : //Get the marginal bytes of spending the specified output
264 : int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, bool use_max_sig = false);
265 :
266 : /**
267 : * A transaction with a bunch of additional info that only the owner cares about.
268 : * It includes any unrecorded transactions needed to link it back to the block chain.
269 : */
270 344180 : class CWalletTx
271 : {
272 : private:
273 : const CWallet* const pwallet;
274 :
275 : /** Constant used in hashBlock to indicate tx has been abandoned, only used at
276 : * serialization/deserialization to avoid ambiguity with conflicted.
277 : */
278 : static const uint256 ABANDON_HASH;
279 :
280 : public:
281 : /**
282 : * Key/value map with information about the transaction.
283 : *
284 : * The following keys can be read and written through the map and are
285 : * serialized in the wallet database:
286 : *
287 : * "comment", "to" - comment strings provided to sendtoaddress,
288 : * and sendmany wallet RPCs
289 : * "replaces_txid" - txid (as HexStr) of transaction replaced by
290 : * bumpfee on transaction created by bumpfee
291 : * "replaced_by_txid" - txid (as HexStr) of transaction created by
292 : * bumpfee on transaction replaced by bumpfee
293 : * "from", "message" - obsolete fields that could be set in UI prior to
294 : * 2011 (removed in commit 4d9b223)
295 : *
296 : * The following keys are serialized in the wallet database, but shouldn't
297 : * be read or written through the map (they will be temporarily added and
298 : * removed from the map during serialization):
299 : *
300 : * "fromaccount" - serialized strFromAccount value
301 : * "n" - serialized nOrderPos value
302 : * "timesmart" - serialized nTimeSmart value
303 : * "spent" - serialized vfSpent value that existed prior to
304 : * 2014 (removed in commit 93a18a3)
305 : */
306 : mapValue_t mapValue;
307 : std::vector<std::pair<std::string, std::string> > vOrderForm;
308 : unsigned int fTimeReceivedIsTxTime;
309 : unsigned int nTimeReceived; //!< time received by this node
310 : /**
311 : * Stable timestamp that never changes, and reflects the order a transaction
312 : * was added to the wallet. Timestamp is based on the block time for a
313 : * transaction added as part of a block, or else the time when the
314 : * transaction was received if it wasn't part of a block, with the timestamp
315 : * adjusted in both cases so timestamp order matches the order transactions
316 : * were added to the wallet. More details can be found in
317 : * CWallet::ComputeTimeSmart().
318 : */
319 : unsigned int nTimeSmart;
320 : /**
321 : * From me flag is set to 1 for transactions that were created by the wallet
322 : * on this bitcoin node, and set to 0 for transactions that were created
323 : * externally and came in through the network or sendrawtransaction RPC.
324 : */
325 : bool fFromMe;
326 : int64_t nOrderPos; //!< position in ordered transaction list
327 : std::multimap<int64_t, CWalletTx*>::const_iterator m_it_wtxOrdered;
328 :
329 : // memory only
330 : enum AmountType { DEBIT, CREDIT, IMMATURE_CREDIT, AVAILABLE_CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
331 : CAmount GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate = false) const;
332 : mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
333 : /**
334 : * This flag is true if all m_amounts caches are empty. This is particularly
335 : * useful in places where MarkDirty is conditionally called and the
336 : * condition can be expensive and thus can be skipped if the flag is true.
337 : * See MarkDestinationsDirty.
338 : */
339 172090 : mutable bool m_is_cache_empty{true};
340 : mutable bool fChangeCached;
341 : mutable bool fInMempool;
342 : mutable CAmount nChangeCached;
343 :
344 860450 : CWalletTx(const CWallet* wallet, CTransactionRef arg)
345 172090 : : pwallet(wallet),
346 172090 : tx(std::move(arg))
347 172090 : {
348 172090 : Init();
349 344180 : }
350 :
351 181670 : void Init()
352 : {
353 181670 : mapValue.clear();
354 181670 : vOrderForm.clear();
355 181670 : fTimeReceivedIsTxTime = false;
356 181670 : nTimeReceived = 0;
357 181670 : nTimeSmart = 0;
358 181670 : fFromMe = false;
359 181670 : fChangeCached = false;
360 181670 : fInMempool = false;
361 181670 : nChangeCached = 0;
362 181670 : nOrderPos = -1;
363 181670 : m_confirm = Confirmation{};
364 181670 : }
365 :
366 : CTransactionRef tx;
367 :
368 : /* New transactions start as UNCONFIRMED. At BlockConnected,
369 : * they will transition to CONFIRMED. In case of reorg, at BlockDisconnected,
370 : * they roll back to UNCONFIRMED. If we detect a conflicting transaction at
371 : * block connection, we update conflicted tx and its dependencies as CONFLICTED.
372 : * If tx isn't confirmed and outside of mempool, the user may switch it to ABANDONED
373 : * by using the abandontransaction call. This last status may be override by a CONFLICTED
374 : * or CONFIRMED transition.
375 : */
376 : enum Status {
377 : UNCONFIRMED,
378 : CONFIRMED,
379 : CONFLICTED,
380 : ABANDONED
381 : };
382 :
383 : /* Confirmation includes tx status and a triplet of {block height/block hash/tx index in block}
384 : * at which tx has been confirmed. All three are set to 0 if tx is unconfirmed or abandoned.
385 : * Meaning of these fields changes with CONFLICTED state where they instead point to block hash
386 : * and block height of the deepest conflicting tx.
387 : */
388 : struct Confirmation {
389 : Status status;
390 : int block_height;
391 : uint256 hashBlock;
392 : int nIndex;
393 1339994 : Confirmation(Status s = UNCONFIRMED, int b = 0, uint256 h = uint256(), int i = 0) : status(s), block_height(b), hashBlock(h), nIndex(i) {}
394 : };
395 :
396 : Confirmation m_confirm;
397 :
398 : template<typename Stream>
399 140360 : void Serialize(Stream& s) const
400 : {
401 140360 : mapValue_t mapValueCopy = mapValue;
402 :
403 140360 : mapValueCopy["fromaccount"] = "";
404 140360 : WriteOrderPos(nOrderPos, mapValueCopy);
405 140360 : if (nTimeSmart) {
406 140360 : mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
407 140360 : }
408 :
409 140360 : std::vector<char> dummy_vector1; //!< Used to be vMerkleBranch
410 140360 : std::vector<char> dummy_vector2; //!< Used to be vtxPrev
411 140360 : bool dummy_bool = false; //!< Used to be fSpent
412 140360 : uint256 serializedHash = isAbandoned() ? ABANDON_HASH : m_confirm.hashBlock;
413 140360 : int serializedIndex = isAbandoned() || isConflicted() ? -1 : m_confirm.nIndex;
414 140360 : s << tx << serializedHash << dummy_vector1 << serializedIndex << dummy_vector2 << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << dummy_bool;
415 140360 : }
416 :
417 : template<typename Stream>
418 9580 : void Unserialize(Stream& s)
419 : {
420 9580 : Init();
421 :
422 9580 : std::vector<uint256> dummy_vector1; //!< Used to be vMerkleBranch
423 9580 : std::vector<CMerkleTx> dummy_vector2; //!< Used to be vtxPrev
424 9580 : bool dummy_bool; //! Used to be fSpent
425 9580 : int serializedIndex;
426 9580 : s >> tx >> m_confirm.hashBlock >> dummy_vector1 >> serializedIndex >> dummy_vector2 >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> dummy_bool;
427 :
428 : /* At serialization/deserialization, an nIndex == -1 means that hashBlock refers to
429 : * the earliest block in the chain we know this or any in-wallet ancestor conflicts
430 : * with. If nIndex == -1 and hashBlock is ABANDON_HASH, it means transaction is abandoned.
431 : * In same context, an nIndex >= 0 refers to a confirmed transaction (if hashBlock set) or
432 : * unconfirmed one. Older clients interpret nIndex == -1 as unconfirmed for backward
433 : * compatibility (pre-commit 9ac63d6).
434 : */
435 9580 : if (serializedIndex == -1 && m_confirm.hashBlock == ABANDON_HASH) {
436 6 : setAbandoned();
437 9574 : } else if (serializedIndex == -1) {
438 50 : setConflicted();
439 9574 : } else if (!m_confirm.hashBlock.IsNull()) {
440 9442 : m_confirm.nIndex = serializedIndex;
441 9442 : setConfirmed();
442 9442 : }
443 :
444 9580 : ReadOrderPos(nOrderPos, mapValue);
445 9580 : nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
446 :
447 9580 : mapValue.erase("fromaccount");
448 9580 : mapValue.erase("spent");
449 9580 : mapValue.erase("n");
450 9580 : mapValue.erase("timesmart");
451 9580 : }
452 :
453 0 : void SetTx(CTransactionRef arg)
454 : {
455 0 : tx = std::move(arg);
456 0 : }
457 :
458 : //! make sure balances are recalculated
459 216905 : void MarkDirty()
460 : {
461 216905 : m_amounts[DEBIT].Reset();
462 216905 : m_amounts[CREDIT].Reset();
463 216905 : m_amounts[IMMATURE_CREDIT].Reset();
464 216905 : m_amounts[AVAILABLE_CREDIT].Reset();
465 216905 : fChangeCached = false;
466 216905 : m_is_cache_empty = true;
467 216905 : }
468 :
469 : //! filter decides which addresses will count towards the debit
470 : CAmount GetDebit(const isminefilter& filter) const;
471 : CAmount GetCredit(const isminefilter& filter) const;
472 : CAmount GetImmatureCredit(bool fUseCache = true) const;
473 : // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
474 : // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The
475 : // annotation "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid
476 : // having to resolve the issue of member access into incomplete type CWallet.
477 : CAmount GetAvailableCredit(bool fUseCache = true, const isminefilter& filter = ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS;
478 : CAmount GetImmatureWatchOnlyCredit(const bool fUseCache = true) const;
479 : CAmount GetChange() const;
480 :
481 : // Get the marginal bytes if spending the specified output from this transaction
482 334452 : int GetSpendSize(unsigned int out, bool use_max_sig = false) const
483 : {
484 334452 : return CalculateMaximumSignedInputSize(tx->vout[out], pwallet, use_max_sig);
485 : }
486 :
487 : void GetAmounts(std::list<COutputEntry>& listReceived,
488 : std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const;
489 :
490 457622 : bool IsFromMe(const isminefilter& filter) const
491 : {
492 457622 : return (GetDebit(filter) > 0);
493 : }
494 :
495 : // True if only scriptSigs are different
496 : bool IsEquivalentTo(const CWalletTx& tx) const;
497 :
498 : bool InMempool() const;
499 : bool IsTrusted() const;
500 :
501 : int64_t GetTxTime() const;
502 :
503 : // Pass this transaction to node for mempool insertion and relay to peers if flag set to true
504 : bool SubmitMemoryPoolAndRelay(std::string& err_string, bool relay);
505 :
506 : // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
507 : // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
508 : // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
509 : // resolve the issue of member access into incomplete type CWallet. Note
510 : // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
511 : // in place.
512 : std::set<uint256> GetConflicts() const NO_THREAD_SAFETY_ANALYSIS;
513 :
514 : /**
515 : * Return depth of transaction in blockchain:
516 : * <0 : conflicts with a transaction this deep in the blockchain
517 : * 0 : in memory pool, waiting to be included in a block
518 : * >=1 : this many blocks deep in the main chain
519 : */
520 : // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
521 : // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
522 : // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
523 : // resolve the issue of member access into incomplete type CWallet. Note
524 : // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
525 : // in place.
526 : int GetDepthInMainChain() const NO_THREAD_SAFETY_ANALYSIS;
527 47264 : bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
528 :
529 : /**
530 : * @return number of blocks to maturity for this transaction:
531 : * 0 : is not a coinbase transaction, or is a mature coinbase transaction
532 : * >0 : is a coinbase transaction which matures in this many blocks
533 : */
534 : int GetBlocksToMaturity() const;
535 2388969 : bool isAbandoned() const { return m_confirm.status == CWalletTx::ABANDONED; }
536 13 : void setAbandoned()
537 : {
538 13 : m_confirm.status = CWalletTx::ABANDONED;
539 13 : m_confirm.hashBlock = uint256();
540 13 : m_confirm.block_height = 0;
541 13 : m_confirm.nIndex = 0;
542 13 : }
543 2207391 : bool isConflicted() const { return m_confirm.status == CWalletTx::CONFLICTED; }
544 323 : void setConflicted() { m_confirm.status = CWalletTx::CONFLICTED; }
545 2246978 : bool isUnconfirmed() const { return m_confirm.status == CWalletTx::UNCONFIRMED; }
546 565 : void setUnconfirmed() { m_confirm.status = CWalletTx::UNCONFIRMED; }
547 646 : bool isConfirmed() const { return m_confirm.status == CWalletTx::CONFIRMED; }
548 9442 : void setConfirmed() { m_confirm.status = CWalletTx::CONFIRMED; }
549 706745 : const uint256& GetHash() const { return tx->GetHash(); }
550 1136313 : bool IsCoinBase() const { return tx->IsCoinBase(); }
551 : bool IsImmatureCoinBase() const;
552 :
553 : // Disable copying of CWalletTx objects to prevent bugs where instances get
554 : // copied in and out of the mapWallet map, and fields are updated in the
555 : // wrong copy.
556 : CWalletTx(CWalletTx const &) = delete;
557 : void operator=(CWalletTx const &x) = delete;
558 : };
559 :
560 : class COutput
561 : {
562 : public:
563 : const CWalletTx *tx;
564 : int i;
565 : int nDepth;
566 :
567 : /** Pre-computed estimated size of this output as a fully-signed input in a transaction. Can be -1 if it could not be calculated */
568 : int nInputBytes;
569 :
570 : /** Whether we have the private keys to spend this output */
571 : bool fSpendable;
572 :
573 : /** Whether we know how to spend this output, ignoring the lack of keys */
574 : bool fSolvable;
575 :
576 : /** Whether to use the maximum sized, 72 byte signature when calculating the size of the input spend. This should only be set when watch-only outputs are allowed */
577 : bool use_max_sig;
578 :
579 : /**
580 : * Whether this output is considered safe to spend. Unconfirmed transactions
581 : * from outside keys and unconfirmed replacement transactions are considered
582 : * unsafe and will not be used to fund new spending transactions.
583 : */
584 : bool fSafe;
585 :
586 669422 : COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in = false)
587 334711 : {
588 334711 : tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn; nInputBytes = -1; use_max_sig = use_max_sig_in;
589 : // If known and signable by the given wallet, compute nInputBytes
590 : // Failure will keep this value -1
591 334711 : if (fSpendable && tx) {
592 333474 : nInputBytes = tx->GetSpendSize(i, use_max_sig);
593 333474 : }
594 669422 : }
595 :
596 : std::string ToString() const;
597 :
598 1151184 : inline CInputCoin GetInputCoin() const
599 : {
600 1151184 : return CInputCoin(tx->tx, i, nInputBytes);
601 : }
602 : };
603 :
604 : struct CoinSelectionParams
605 : {
606 2640 : bool use_bnb = true;
607 2640 : size_t change_output_size = 0;
608 2640 : size_t change_spend_size = 0;
609 2640 : CFeeRate effective_fee = CFeeRate(0);
610 2640 : size_t tx_noinputs_size = 0;
611 : //! Indicate that we are subtracting the fee from outputs
612 2931 : bool m_subtract_fee_outputs = false;
613 :
614 582 : CoinSelectionParams(bool use_bnb, size_t change_output_size, size_t change_spend_size, CFeeRate effective_fee, size_t tx_noinputs_size) : use_bnb(use_bnb), change_output_size(change_output_size), change_spend_size(change_spend_size), effective_fee(effective_fee), tx_noinputs_size(tx_noinputs_size) {}
615 5280 : CoinSelectionParams() {}
616 : };
617 :
618 : class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
619 : /**
620 : * A CWallet maintains a set of transactions and balances, and provides the ability to create new transactions.
621 : */
622 : class CWallet final : public WalletStorage, public interfaces::Chain::Notifications
623 : {
624 : private:
625 : CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
626 :
627 :
628 : bool Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys = false);
629 :
630 873 : std::atomic<bool> fAbortRescan{false};
631 873 : std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
632 873 : std::atomic<int64_t> m_scanning_start{0};
633 873 : std::atomic<double> m_scanning_progress{0};
634 : friend class WalletRescanReserver;
635 :
636 : //! the current wallet version: clients below this version are not able to load the wallet
637 873 : int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
638 :
639 : //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
640 873 : int nWalletMaxVersion GUARDED_BY(cs_wallet) = FEATURE_BASE;
641 :
642 873 : int64_t nNextResend = 0;
643 873 : bool fBroadcastTransactions = false;
644 : // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
645 873 : std::atomic<int64_t> m_best_block_time {0};
646 :
647 : /**
648 : * Used to keep track of spent outpoints, and
649 : * detect and report conflicts (double-spends or
650 : * mutated transactions where the mutant gets mined).
651 : */
652 : typedef std::multimap<COutPoint, uint256> TxSpends;
653 : TxSpends mapTxSpends GUARDED_BY(cs_wallet);
654 : void AddToSpends(const COutPoint& outpoint, const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
655 : void AddToSpends(const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
656 :
657 : /**
658 : * Add a transaction to the wallet, or update it. pIndex and posInBlock should
659 : * be set when the transaction was known to be included in a block. When
660 : * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
661 : * notifications happen and cached balances are marked dirty.
662 : *
663 : * If fUpdate is true, existing transactions will be updated.
664 : * TODO: One exception to this is that the abandoned state is cleared under the
665 : * assumption that any further notification of a transaction that was considered
666 : * abandoned is an indication that it is not safe to be considered abandoned.
667 : * Abandoned state should probably be more carefully tracked via different
668 : * posInBlock signals or by checking mempool presence when necessary.
669 : */
670 : bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
671 :
672 : /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
673 : void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
674 :
675 : /* Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
676 : void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
677 :
678 : void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
679 :
680 : /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
681 : * Should be called with non-zero block_hash and posInBlock if this is for a transaction that is included in a block. */
682 : void SyncTransaction(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool update_tx = true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
683 :
684 873 : std::atomic<uint64_t> m_wallet_flags{0};
685 :
686 : bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose);
687 :
688 : //! Unsets a wallet flag and saves it to disk
689 : void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
690 :
691 : //! Unset the blank wallet flag and saves it to disk
692 : void UnsetBlankWalletFlag(WalletBatch& batch) override;
693 :
694 : /** Interface for accessing chain state. */
695 : interfaces::Chain* m_chain;
696 :
697 : /** Wallet name: relative directory name or "" for default wallet. */
698 : std::string m_name;
699 :
700 : /** Internal database handle. */
701 : std::unique_ptr<WalletDatabase> database;
702 :
703 : /**
704 : * The following is used to keep track of how far behind the wallet is
705 : * from the chain sync, and to allow clients to block on us being caught up.
706 : *
707 : * Processed hash is a pointer on node's tip and doesn't imply that the wallet
708 : * has scanned sequentially all blocks up to this one.
709 : */
710 : uint256 m_last_block_processed GUARDED_BY(cs_wallet);
711 :
712 : /* Height of last block processed is used by wallet to know depth of transactions
713 : * without relying on Chain interface beyond asynchronous updates. For safety, we
714 : * initialize it to -1. Height is a pointer on node's tip and doesn't imply
715 : * that the wallet has scanned sequentially all blocks up to this one.
716 : */
717 873 : int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
718 :
719 : std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
720 : std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
721 :
722 : // Indexed by a unique identifier produced by each ScriptPubKeyMan using
723 : // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
724 : std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
725 :
726 : bool CreateTransactionInternal(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, const CCoinControl& coin_control, bool sign);
727 :
728 : public:
729 : /*
730 : * Main wallet lock.
731 : * This lock protects all the fields added by CWallet.
732 : */
733 : mutable RecursiveMutex cs_wallet;
734 :
735 : /** Get database handle used by this wallet. Ideally this function would
736 : * not be necessary.
737 : */
738 26268 : WalletDatabase& GetDBHandle()
739 : {
740 26268 : return *database;
741 : }
742 60914 : WalletDatabase& GetDatabase() override { return *database; }
743 :
744 : /**
745 : * Select a set of coins such that nValueRet >= nTargetValue and at least
746 : * all coins from coinControl are selected; Never select unconfirmed coins
747 : * if they are not ours
748 : */
749 : bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet,
750 : const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
751 :
752 : /** Get a name for this wallet for logging/debugging purposes.
753 : */
754 224645 : const std::string& GetName() const { return m_name; }
755 :
756 : typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
757 : MasterKeyMap mapMasterKeys;
758 873 : unsigned int nMasterKeyMaxID = 0;
759 :
760 : /** Construct wallet with specified name and database implementation. */
761 2619 : CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database)
762 873 : : m_chain(chain),
763 873 : m_name(name),
764 873 : database(std::move(database))
765 1746 : {
766 1746 : }
767 :
768 1746 : ~CWallet()
769 1746 : {
770 : // Should not have slots connected at this point.
771 873 : assert(NotifyUnload.empty());
772 1746 : }
773 :
774 : bool IsCrypted() const;
775 : bool IsLocked() const override;
776 : bool Lock();
777 :
778 : /** Interface to assert chain access */
779 9574 : bool HaveChain() const { return m_chain ? true : false; }
780 :
781 : std::map<uint256, CWalletTx> mapWallet GUARDED_BY(cs_wallet);
782 :
783 : typedef std::multimap<int64_t, CWalletTx*> TxItems;
784 : TxItems wtxOrdered;
785 :
786 873 : int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
787 873 : uint64_t nAccountingEntryNumber = 0;
788 :
789 : std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
790 : const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
791 :
792 : std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
793 :
794 : /** Registered interfaces::Chain::Notifications handler. */
795 : std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
796 :
797 : /** Interface for accessing chain state. */
798 2174227 : interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
799 :
800 : const CWalletTx* GetWalletTx(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
801 : bool IsTrusted(const CWalletTx& wtx, std::set<uint256>& trusted_parents) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
802 :
803 : //! check whether we are allowed to upgrade (or already support) to the named feature
804 76944 : bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
805 :
806 : /**
807 : * populate vCoins with vector of available COutputs.
808 : */
809 : void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlySafe = true, const CCoinControl* coinControl = nullptr, const CAmount& nMinimumAmount = 1, const CAmount& nMaximumAmount = MAX_MONEY, const CAmount& nMinimumSumAmount = MAX_MONEY, const uint64_t nMaximumCount = 0) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
810 :
811 : /**
812 : * Return list of available coins and locked coins grouped by non-change output address.
813 : */
814 : std::map<CTxDestination, std::vector<COutput>> ListCoins() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
815 :
816 : /**
817 : * Find non-change parent output.
818 : */
819 : const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
820 :
821 : /**
822 : * Shuffle and select coins until nTargetValue is reached while avoiding
823 : * small change; This method is stochastic for some inputs and upon
824 : * completion the coin set and corresponding actual target value is
825 : * assembled
826 : */
827 : bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
828 : std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const;
829 :
830 : bool IsSpent(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
831 :
832 : // Whether this or any known UTXO with the same single key has been spent.
833 : bool IsSpentKey(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
834 : void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
835 :
836 : std::vector<OutputGroup> GroupOutputs(const std::vector<COutput>& outputs, bool single_coin, const size_t max_ancestors) const;
837 :
838 : bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
839 : void LockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
840 : void UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
841 : void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
842 : void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
843 :
844 : /*
845 : * Rescan abort properties
846 : */
847 0 : void AbortRescan() { fAbortRescan = true; }
848 547 : bool IsAbortingRescan() const { return fAbortRescan; }
849 1068 : bool IsScanning() const { return fScanningWallet; }
850 0 : int64_t ScanningDuration() const { return fScanningWallet ? GetTimeMillis() - m_scanning_start : 0; }
851 0 : double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
852 :
853 : //! Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo
854 : void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
855 :
856 309 : bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
857 :
858 : /**
859 : * Adds a destination data tuple to the store, and saves it to disk
860 : * When adding new fields, take care to consider how DelAddressBook should handle it!
861 : */
862 : bool AddDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
863 : //! Erases a destination data tuple in the store and on disk
864 : bool EraseDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
865 : //! Adds a destination data tuple to the store, without saving it to disk
866 : void LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
867 : //! Look up a destination data tuple in the store, return true if found false otherwise
868 : bool GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
869 : //! Get all destination values matching a prefix.
870 : std::vector<std::string> GetDestValues(const std::string& prefix) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
871 :
872 : //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
873 873 : int64_t nRelockTime GUARDED_BY(cs_wallet){0};
874 :
875 : // Used to prevent concurrent calls to walletpassphrase RPC.
876 : Mutex m_unlock_mutex;
877 : bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
878 : bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
879 : bool EncryptWallet(const SecureString& strWalletPassphrase);
880 :
881 : void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
882 : unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
883 :
884 : /**
885 : * Increment the next transaction order id
886 : * @return next transaction order id
887 : */
888 : int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
889 : DBErrors ReorderTransactions();
890 :
891 : void MarkDirty();
892 :
893 : //! Callback for updating transaction metadata in mapWallet.
894 : //!
895 : //! @param wtx - reference to mapWallet transaction to update
896 : //! @param new_tx - true if wtx is newly inserted, false if it previously existed
897 : //!
898 : //! @return true if wtx is changed and needs to be saved to disk, otherwise false
899 : using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
900 :
901 : CWalletTx* AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true);
902 : bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
903 : void transactionAddedToMempool(const CTransactionRef& tx) override;
904 : void blockConnected(const CBlock& block, int height) override;
905 : void blockDisconnected(const CBlock& block, int height) override;
906 : void updatedBlockTip() override;
907 : int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
908 :
909 1278 : struct ScanResult {
910 639 : enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
911 :
912 : //! Hash and height of most recent block that was successfully scanned.
913 : //! Unset if no blocks were scanned due to read errors or the chain
914 : //! being empty.
915 : uint256 last_scanned_block;
916 : Optional<int> last_scanned_height;
917 :
918 : //! Height of the most recent block that could not be scanned due to
919 : //! read errors or pruning. Will be set if status is FAILURE, unset if
920 : //! status is SUCCESS, and may or may not be set if status is
921 : //! USER_ABORT.
922 : uint256 last_failed_block;
923 : };
924 : ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, Optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate);
925 : void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override;
926 : void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
927 : void ResendWalletTransactions();
928 3618 : struct Balance {
929 1809 : CAmount m_mine_trusted{0}; //!< Trusted, at depth=GetBalance.min_depth or more
930 1809 : CAmount m_mine_untrusted_pending{0}; //!< Untrusted, but in mempool (pending)
931 1809 : CAmount m_mine_immature{0}; //!< Immature coinbases in the main chain
932 1809 : CAmount m_watchonly_trusted{0};
933 1809 : CAmount m_watchonly_untrusted_pending{0};
934 1809 : CAmount m_watchonly_immature{0};
935 : };
936 : Balance GetBalance(int min_depth = 0, bool avoid_reuse = true) const;
937 : CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
938 :
939 : OutputType TransactionChangeType(const Optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend);
940 :
941 : /**
942 : * Insert additional inputs into the transaction by
943 : * calling CreateTransaction();
944 : */
945 : bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
946 : // Fetch the inputs and sign with SIGHASH_ALL.
947 : bool SignTransaction(CMutableTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
948 : // Sign the tx given the input coins and sighash.
949 : bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const;
950 : SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
951 :
952 : /**
953 : * Fills out a PSBT with information from the wallet. Fills in UTXOs if we have
954 : * them. Tries to sign if sign=true. Sets `complete` if the PSBT is now complete
955 : * (i.e. has all required signatures or signature-parts, and is ready to
956 : * finalize.) Sets `error` and returns false if something goes wrong.
957 : *
958 : * @param[in] psbtx PartiallySignedTransaction to fill in
959 : * @param[out] complete indicates whether the PSBT is now complete
960 : * @param[in] sighash_type the sighash type to use when signing (if PSBT does not specify)
961 : * @param[in] sign whether to sign or not
962 : * @param[in] bip32derivs whether to fill in bip32 derivation information if available
963 : * return error
964 : */
965 : TransactionError FillPSBT(PartiallySignedTransaction& psbtx,
966 : bool& complete,
967 : int sighash_type = 1 /* SIGHASH_ALL */,
968 : bool sign = true,
969 : bool bip32derivs = true,
970 : size_t* n_signed = nullptr) const;
971 :
972 : /**
973 : * Create a new transaction paying the recipients with a set of coins
974 : * selected by SelectCoins(); Also create the change output, when needed
975 : * @note passing nChangePosInOut as -1 will result in setting a random position
976 : */
977 : bool CreateTransaction(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, const CCoinControl& coin_control, bool sign = true);
978 : /**
979 : * Submit the transaction to the node's mempool and then relay to peers.
980 : * Should be called after CreateTransaction unless you want to abort
981 : * broadcasting the transaction.
982 : *
983 : * @param[in] tx The transaction to be broadcast.
984 : * @param[in] mapValue key-values to be set on the transaction.
985 : * @param[in] orderForm BIP 70 / BIP 21 order form details to be set on the transaction.
986 : */
987 : void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
988 :
989 : bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, bool use_max_sig = false) const
990 : {
991 : std::vector<CTxOut> v_txouts(txouts.size());
992 : std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
993 : return DummySignTx(txNew, v_txouts, use_max_sig);
994 : }
995 : bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig = false) const;
996 : bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig = false) const;
997 :
998 : bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
999 : bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1000 : bool ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1001 : bool ImportScriptPubKeys(const std::string& label, const std::set<CScript>& script_pub_keys, const bool have_solving_data, const bool apply_label, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1002 :
1003 873 : CFeeRate m_pay_tx_fee{DEFAULT_PAY_TX_FEE};
1004 873 : unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
1005 873 : bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
1006 873 : bool m_signal_rbf{DEFAULT_WALLET_RBF};
1007 873 : bool m_allow_fallback_fee{true}; //!< will be false if -fallbackfee=0
1008 873 : CFeeRate m_min_fee{DEFAULT_TRANSACTION_MINFEE}; //!< Override with -mintxfee
1009 : /**
1010 : * If fee estimation does not have enough data to provide estimates, use this fee instead.
1011 : * Has no effect if not using fee estimation
1012 : * Override with -fallbackfee
1013 : */
1014 873 : CFeeRate m_fallback_fee{DEFAULT_FALLBACK_FEE};
1015 873 : CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
1016 873 : CAmount m_max_aps_fee{DEFAULT_MAX_AVOIDPARTIALSPEND_FEE}; //!< note: this is absolute fee, not fee rate
1017 873 : OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
1018 : /**
1019 : * Default output type for change outputs. When unset, automatically choose type
1020 : * based on address type setting and the types other of non-change outputs
1021 : * (see -changetype option documentation and implementation in
1022 : * CWallet::TransactionChangeType for details).
1023 : */
1024 873 : Optional<OutputType> m_default_change_type{};
1025 : /** Absolute maximum transaction fee (in satoshis) used by default for the wallet */
1026 873 : CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
1027 :
1028 : size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1029 : bool TopUpKeyPool(unsigned int kpSize = 0);
1030 :
1031 : int64_t GetOldestKeyPoolTime() const;
1032 :
1033 : std::set<std::set<CTxDestination>> GetAddressGroupings() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1034 : std::map<CTxDestination, CAmount> GetAddressBalances() const;
1035 :
1036 : std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
1037 :
1038 : /**
1039 : * Marks all outputs in each one of the destinations dirty, so their cache is
1040 : * reset and does not return outdated information.
1041 : */
1042 : void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1043 :
1044 : bool GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error);
1045 : bool GetNewChangeDestination(const OutputType type, CTxDestination& dest, std::string& error);
1046 :
1047 : isminetype IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1048 : isminetype IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1049 : isminetype IsMine(const CTxIn& txin) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1050 : /**
1051 : * Returns amount of debit if the input matches the
1052 : * filter, otherwise returns 0
1053 : */
1054 : CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1055 : isminetype IsMine(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1056 : CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1057 : bool IsChange(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1058 : bool IsChange(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1059 : CAmount GetChange(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1060 : bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1061 : /** should probably be renamed to IsRelevantToMe */
1062 : bool IsFromMe(const CTransaction& tx) const;
1063 : CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1064 : /** Returns whether all of the inputs match the filter */
1065 : bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1066 : CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1067 : CAmount GetChange(const CTransaction& tx) const;
1068 : void chainStateFlushed(const CBlockLocator& loc) override;
1069 :
1070 : DBErrors LoadWallet(bool& fFirstRunRet);
1071 : DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1072 :
1073 : bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1074 :
1075 : bool DelAddressBook(const CTxDestination& address);
1076 :
1077 : unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1078 :
1079 : //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1080 : void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr, bool fExplicit = false) override;
1081 :
1082 : //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1083 : bool SetMaxVersion(int nVersion);
1084 :
1085 : //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1086 1819 : int GetVersion() const { LOCK(cs_wallet); return nWalletVersion; }
1087 :
1088 : //! Get wallet transactions that conflict with given transaction (spend same outputs)
1089 : std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1090 :
1091 : //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
1092 : bool HasWalletSpend(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1093 :
1094 : //! Flush wallet (bitdb flush)
1095 : void Flush();
1096 :
1097 : //! Close wallet database
1098 : void Close();
1099 :
1100 : /** Wallet is about to be unloaded */
1101 : boost::signals2::signal<void ()> NotifyUnload;
1102 :
1103 : /**
1104 : * Address book entry changed.
1105 : * @note called with lock cs_wallet held.
1106 : */
1107 : boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1108 : &address, const std::string &label, bool isMine,
1109 : const std::string &purpose,
1110 : ChangeType status)> NotifyAddressBookChanged;
1111 :
1112 : /**
1113 : * Wallet transaction added, removed or updated.
1114 : * @note called with lock cs_wallet held.
1115 : */
1116 : boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1117 : ChangeType status)> NotifyTransactionChanged;
1118 :
1119 : /** Show progress e.g. for rescan */
1120 : boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1121 :
1122 : /** Watch-only address added */
1123 : boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1124 :
1125 : /** Keypool has new keys */
1126 : boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
1127 :
1128 : /**
1129 : * Wallet status (encrypted, locked) changed.
1130 : * Note: Called without locks held.
1131 : */
1132 : boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
1133 :
1134 : /** Inquire whether this wallet broadcasts transactions. */
1135 1923 : bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1136 : /** Set whether this wallet broadcasts transactions. */
1137 727 : void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1138 :
1139 : /** Return whether transaction can be abandoned */
1140 : bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1141 :
1142 : /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1143 : bool AbandonTransaction(const uint256& hashTx);
1144 :
1145 : /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1146 : bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1147 :
1148 : /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1149 : static std::shared_ptr<CWallet> Create(interfaces::Chain& chain, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings);
1150 :
1151 : /**
1152 : * Wallet post-init setup
1153 : * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1154 : */
1155 : void postInitProcess();
1156 :
1157 : bool BackupWallet(const std::string& strDest) const;
1158 :
1159 : /* Returns true if HD is enabled */
1160 : bool IsHDEnabled() const;
1161 :
1162 : /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
1163 : bool CanGetAddresses(bool internal = false) const;
1164 :
1165 : /**
1166 : * Blocks until the wallet state is up-to-date to /at least/ the current
1167 : * chain at the time this function is entered
1168 : * Obviously holding cs_main/cs_wallet when going into this call may cause
1169 : * deadlock
1170 : */
1171 : void BlockUntilSyncedToCurrentChain() const EXCLUSIVE_LOCKS_REQUIRED(!::cs_main, !cs_wallet);
1172 :
1173 : /** set a single wallet flag */
1174 : void SetWalletFlag(uint64_t flags);
1175 :
1176 : /** Unsets a single wallet flag */
1177 : void UnsetWalletFlag(uint64_t flag);
1178 :
1179 : /** check if a certain wallet flag is set */
1180 : bool IsWalletFlagSet(uint64_t flag) const override;
1181 :
1182 : /** overwrite all flags by the given uint64_t
1183 : returns false if unknown, non-tolerable flags are present */
1184 : bool AddWalletFlags(uint64_t flags);
1185 : /** Loads the flags into the wallet. (used by LoadWallet) */
1186 : bool LoadWalletFlags(uint64_t flags);
1187 :
1188 : /** Determine if we are a legacy wallet */
1189 : bool IsLegacy() const;
1190 :
1191 : /** Returns a bracketed wallet name for displaying in logs, will return [default wallet] if the wallet has no name */
1192 209965 : const std::string GetDisplayName() const override {
1193 209965 : std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
1194 209965 : return strprintf("[%s]", wallet_name);
1195 209965 : };
1196 :
1197 : /** Prepends the wallet name in logging output to ease debugging in multi-wallet use cases */
1198 : template<typename... Params>
1199 177719 : void WalletLogPrintf(std::string fmt, Params... parameters) const {
1200 177719 : LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
1201 177719 : };
1202 :
1203 : /** Upgrade the wallet */
1204 : bool UpgradeWallet(int version, bilingual_str& error, std::vector<bilingual_str>& warnings);
1205 :
1206 : //! Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers
1207 : std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
1208 :
1209 : //! Returns all unique ScriptPubKeyMans
1210 : std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
1211 :
1212 : //! Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
1213 : ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
1214 :
1215 : //! Get the ScriptPubKeyMan for a script
1216 : ScriptPubKeyMan* GetScriptPubKeyMan(const CScript& script) const;
1217 : //! Get the ScriptPubKeyMan by id
1218 : ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
1219 :
1220 : //! Get all of the ScriptPubKeyMans for a script given additional information in sigdata (populated by e.g. a psbt)
1221 : std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script, SignatureData& sigdata) const;
1222 :
1223 : //! Get the SigningProvider for a script
1224 : std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
1225 : std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
1226 :
1227 : //! Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
1228 : LegacyScriptPubKeyMan* GetLegacyScriptPubKeyMan() const;
1229 : LegacyScriptPubKeyMan* GetOrCreateLegacyScriptPubKeyMan();
1230 :
1231 : //! Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
1232 : void SetupLegacyScriptPubKeyMan();
1233 :
1234 : const CKeyingMaterial& GetEncryptionKey() const override;
1235 : bool HasEncryptionKeys() const override;
1236 :
1237 : /** Get last block processed height */
1238 2069111 : int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1239 : {
1240 2069111 : AssertLockHeld(cs_wallet);
1241 2069111 : assert(m_last_block_processed_height >= 0);
1242 2069111 : return m_last_block_processed_height;
1243 : };
1244 79896 : uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1245 : {
1246 79896 : AssertLockHeld(cs_wallet);
1247 79896 : assert(m_last_block_processed_height >= 0);
1248 79896 : return m_last_block_processed;
1249 : }
1250 : /** Set last block processed height, currently only use in unit test */
1251 10 : void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1252 : {
1253 10 : AssertLockHeld(cs_wallet);
1254 10 : m_last_block_processed_height = block_height;
1255 10 : m_last_block_processed = block_hash;
1256 10 : };
1257 :
1258 : //! Connect the signals from ScriptPubKeyMans to the signals in CWallet
1259 : void ConnectScriptPubKeyManNotifiers();
1260 :
1261 : //! Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it
1262 : void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc);
1263 :
1264 : //! Adds the active ScriptPubKeyMan for the specified type and internal. Writes it to the wallet file
1265 : //! @param[in] id The unique id for the ScriptPubKeyMan
1266 : //! @param[in] type The OutputType this ScriptPubKeyMan provides addresses for
1267 : //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
1268 : void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1269 :
1270 : //! Loads an active ScriptPubKeyMan for the specified type and internal. (used by LoadWallet)
1271 : //! @param[in] id The unique id for the ScriptPubKeyMan
1272 : //! @param[in] type The OutputType this ScriptPubKeyMan provides addresses for
1273 : //! @param[in] internal Whether this ScriptPubKeyMan provides change addresses
1274 : void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1275 :
1276 : //! Create new DescriptorScriptPubKeyMans and add them to the wallet
1277 : void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1278 :
1279 : //! Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet
1280 : DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1281 :
1282 : //! Add a descriptor to the wallet, return a ScriptPubKeyMan & associated output type
1283 : ScriptPubKeyMan* AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label);
1284 : };
1285 :
1286 : /**
1287 : * Called periodically by the schedule thread. Prompts individual wallets to resend
1288 : * their transactions. Actual rebroadcast schedule is managed by the wallets themselves.
1289 : */
1290 : void MaybeResendWalletTxs();
1291 :
1292 : /** RAII object to check and reserve a wallet rescan */
1293 : class WalletRescanReserver
1294 : {
1295 : private:
1296 : CWallet& m_wallet;
1297 : bool m_could_reserve;
1298 : public:
1299 1612 : explicit WalletRescanReserver(CWallet& w) : m_wallet(w), m_could_reserve(false) {}
1300 :
1301 677 : bool reserve()
1302 : {
1303 677 : assert(!m_could_reserve);
1304 677 : if (m_wallet.fScanningWallet.exchange(true)) {
1305 0 : return false;
1306 : }
1307 677 : m_wallet.m_scanning_start = GetTimeMillis();
1308 677 : m_wallet.m_scanning_progress = 0;
1309 677 : m_could_reserve = true;
1310 677 : return true;
1311 677 : }
1312 :
1313 639 : bool isReserved() const
1314 : {
1315 639 : return (m_could_reserve && m_wallet.fScanningWallet);
1316 : }
1317 :
1318 1612 : ~WalletRescanReserver()
1319 806 : {
1320 806 : if (m_could_reserve) {
1321 677 : m_wallet.fScanningWallet = false;
1322 677 : }
1323 1612 : }
1324 : };
1325 :
1326 : // Calculate the size of the transaction assuming all signatures are max size
1327 : // Use DummySignatureCreator, which inserts 71 byte signatures everywhere.
1328 : // NOTE: this requires that all inputs must be in mapWallet (eg the tx should
1329 : // be IsAllFromMe).
1330 : int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig = false) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);
1331 : int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig = false);
1332 :
1333 : //! Add wallet name to persistent configuration so it will be loaded on startup.
1334 : bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1335 :
1336 : //! Remove wallet name from persistent configuration so it will not be loaded on startup.
1337 : bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1338 :
1339 : #endif // BITCOIN_WALLET_WALLET_H
|