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