1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 <outputtype.h>
12 #include <policy/feerate.h>
13 #include <streams.h>
14 #include <tinyformat.h>
15 #include <ui_interface.h>
16 #include <util/strencodings.h>
17 #include <validationinterface.h>
18 #include <script/ismine.h>
19 #include <script/sign.h>
20 #include <util/system.h>
21 #include <wallet/crypter.h>
22 #include <wallet/coinselection.h>
23 #include <wallet/walletdb.h>
24 #include <wallet/walletutil.h>
25
26 #include <algorithm>
27 #include <atomic>
28 #include <map>
29 #include <memory>
30 #include <set>
31 #include <stdexcept>
32 #include <stdint.h>
33 #include <string>
34 #include <utility>
35 #include <vector>
36
37 //! Responsible for reading and validating the -wallet arguments and verifying the wallet database.
38 //! This function will perform salvage on the wallet if requested, as long as only one wallet is
39 //! being loaded (WalletParameterInteraction forbids -salvagewallet, -zapwallettxes or -upgradewallet with multiwallet).
40 bool VerifyWallets(interfaces::Chain& chain, const std::vector<std::string>& wallet_files);
41
42 //! Load wallet databases.
43 bool LoadWallets(interfaces::Chain& chain, const std::vector<std::string>& wallet_files);
44
45 //! Complete startup of wallets.
46 void StartWallets(CScheduler& scheduler);
47
48 //! Flush all wallets in preparation for shutdown.
49 void FlushWallets();
50
51 //! Stop all wallets. Wallets will be flushed first.
52 void StopWallets();
53
54 //! Close all wallets.
55 void UnloadWallets();
56
57 //! Explicitly unload and delete the wallet.
58 //! Blocks the current thread after signaling the unload intent so that all
59 //! wallet clients release the wallet.
60 //! Note that, when blocking is not required, the wallet is implicitly unloaded
61 //! by the shared pointer deleter.
62 void UnloadWallet(std::shared_ptr<CWallet>&& wallet);
63
64 bool AddWallet(const std::shared_ptr<CWallet>& wallet);
65 bool RemoveWallet(const std::shared_ptr<CWallet>& wallet);
66 bool HasWallets();
67 std::vector<std::shared_ptr<CWallet>> GetWallets();
68 std::shared_ptr<CWallet> GetWallet(const std::string& name);
69 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const WalletLocation& location, std::string& error, std::string& warning);
70
71 //! Default for -keypool
72 static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
73 //! -paytxfee default
74 constexpr CAmount DEFAULT_PAY_TX_FEE = 0;
75 //! -fallbackfee default
76 static const CAmount DEFAULT_FALLBACK_FEE = 200000;
77 //! -discardfee default
78 static const CAmount DEFAULT_DISCARD_FEE = 10000;
79 //! -mintxfee default
80 static const CAmount DEFAULT_TRANSACTION_MINFEE = 10000;
81 //! minimum recommended increment for BIP 125 replacement txs
82 static const CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000;
83 //! Default for -spendzeroconfchange
84 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
85 //! Default for -walletrejectlongchains
86 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
87 //! Default for -avoidpartialspends
88 static const bool DEFAULT_AVOIDPARTIALSPENDS = false;
89 //! -txconfirmtarget default
90 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
91 //! -walletrbf default
92 static const bool DEFAULT_WALLET_RBF = false;
93 static const bool DEFAULT_WALLETBROADCAST = true;
94 static const bool DEFAULT_DISABLE_WALLET = false;
95
96 //! Pre-calculated constants for input size estimation in *virtual size*
97 static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
98
99 class CCoinControl;
100 class COutput;
101 class CReserveKey;
102 class CScript;
103 class CTxMemPool;
104 class CBlockPolicyEstimator;
105 class CWalletTx;
106 struct FeeCalculation;
107 enum class FeeEstimateMode;
108
109 /** (client) version numbers for particular wallet features */
110 enum WalletFeature
111 {
112 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getwalletinfo's clientversion output)
113
114 FEATURE_WALLETCRYPT = 40000, // wallet encryption
115 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
116
117 FEATURE_HD = 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
118
119 FEATURE_HD_SPLIT = 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
120
121 FEATURE_NO_DEFAULT_KEY = 159900, // Wallet without a default key written
122
123 FEATURE_PRE_SPLIT_KEYPOOL = 169900, // Upgraded to HD SPLIT and can have a pre-split keypool
124
125 FEATURE_LATEST = FEATURE_PRE_SPLIT_KEYPOOL
126 };
127
128 //! Default for -addresstype
129 constexpr OutputType DEFAULT_ADDRESS_TYPE{OutputType::P2SH_SEGWIT};
130
131 //! Default for -changetype
132 constexpr OutputType DEFAULT_CHANGE_TYPE{OutputType::CHANGE_AUTO};
133
134 enum WalletFlags : uint64_t {
135 // wallet flags in the upper section (> 1 << 31) will lead to not opening the wallet if flag is unknown
136 // unknown wallet flags in the lower section <= (1 << 31) will be tolerated
137
138 // Indicates that the metadata has already been upgraded to contain key origins
139 WALLET_FLAG_KEY_ORIGIN_METADATA = (1ULL << 1),
140
141 // will enforce the rule that the wallet can't contain any private keys (only watch-only/pubkeys)
142 WALLET_FLAG_DISABLE_PRIVATE_KEYS = (1ULL << 32),
143
144 //! Flag set when a wallet contains no HD seed and no private keys, scripts,
145 //! addresses, and other watch only things, and is therefore "blank."
146 //!
147 //! The only function this flag serves is to distinguish a blank wallet from
148 //! a newly created wallet when the wallet database is loaded, to avoid
149 //! initialization that should only happen on first run.
150 //!
151 //! This flag is also a mandatory flag to prevent previous versions of
152 //! bitcoin from opening the wallet, thinking it was newly created, and
153 //! then improperly reinitializing it.
154 WALLET_FLAG_BLANK_WALLET = (1ULL << 33),
155 };
156
157 static constexpr uint64_t g_known_wallet_flags = WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET | WALLET_FLAG_KEY_ORIGIN_METADATA;
158
159 /** A key pool entry */
160 class CKeyPool
161 {
162 public:
163 int64_t nTime;
164 CPubKey vchPubKey;
165 bool fInternal; // for change outputs
166 bool m_pre_split; // For keys generated before keypool split upgrade
167
168 CKeyPool();
169 CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn);
170
171 ADD_SERIALIZE_METHODS;
172
173 template <typename Stream, typename Operation>
SerializationOp(Stream & s,Operation ser_action)174 inline void SerializationOp(Stream& s, Operation ser_action) {
175 int nVersion = s.GetVersion();
176 if (!(s.GetType() & SER_GETHASH))
177 READWRITE(nVersion);
178 READWRITE(nTime);
179 READWRITE(vchPubKey);
180 if (ser_action.ForRead()) {
181 try {
182 READWRITE(fInternal);
183 }
184 catch (std::ios_base::failure&) {
185 /* flag as external address if we can't read the internal boolean
186 (this will be the case for any wallet before the HD chain split version) */
187 fInternal = false;
188 }
189 try {
190 READWRITE(m_pre_split);
191 }
192 catch (std::ios_base::failure&) {
193 /* flag as postsplit address if we can't read the m_pre_split boolean
194 (this will be the case for any wallet that upgrades to HD chain split)*/
195 m_pre_split = false;
196 }
197 }
198 else {
199 READWRITE(fInternal);
200 READWRITE(m_pre_split);
201 }
202 }
203 };
204
205 /** Address book data */
206 class CAddressBookData
207 {
208 public:
209 std::string name;
210 std::string purpose;
211
CAddressBookData()212 CAddressBookData() : purpose("unknown") {}
213
214 typedef std::map<std::string, std::string> StringMap;
215 StringMap destdata;
216 };
217
218 struct CRecipient
219 {
220 CScript scriptPubKey;
221 CAmount nAmount;
222 bool fSubtractFeeFromAmount;
223 };
224
225 typedef std::map<std::string, std::string> mapValue_t;
226
227
ReadOrderPos(int64_t & nOrderPos,mapValue_t & mapValue)228 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
229 {
230 if (!mapValue.count("n"))
231 {
232 nOrderPos = -1; // TODO: calculate elsewhere
233 return;
234 }
235 nOrderPos = atoi64(mapValue["n"].c_str());
236 }
237
238
WriteOrderPos(const int64_t & nOrderPos,mapValue_t & mapValue)239 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
240 {
241 if (nOrderPos == -1)
242 return;
243 mapValue["n"] = i64tostr(nOrderPos);
244 }
245
246 struct COutputEntry
247 {
248 CTxDestination destination;
249 CAmount amount;
250 int vout;
251 };
252
253 /** A transaction with a merkle branch linking it to the block chain. */
254 class CMerkleTx
255 {
256 private:
257 /** Constant used in hashBlock to indicate tx has been abandoned */
258 static const uint256 ABANDON_HASH;
259
260 public:
261 CTransactionRef tx;
262 uint256 hashBlock;
263
264 /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
265 * block in the chain we know this or any in-wallet dependency conflicts
266 * with. Older clients interpret nIndex == -1 as unconfirmed for backward
267 * compatibility.
268 */
269 int nIndex;
270
CMerkleTx()271 CMerkleTx()
272 {
273 SetTx(MakeTransactionRef());
274 Init();
275 }
276
CMerkleTx(CTransactionRef arg)277 explicit CMerkleTx(CTransactionRef arg)
278 {
279 SetTx(std::move(arg));
280 Init();
281 }
282
Init()283 void Init()
284 {
285 hashBlock = uint256();
286 nIndex = -1;
287 }
288
SetTx(CTransactionRef arg)289 void SetTx(CTransactionRef arg)
290 {
291 tx = std::move(arg);
292 }
293
294 ADD_SERIALIZE_METHODS;
295
296 template <typename Stream, typename Operation>
SerializationOp(Stream & s,Operation ser_action)297 inline void SerializationOp(Stream& s, Operation ser_action) {
298 std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
299 READWRITE(tx);
300 READWRITE(hashBlock);
301 READWRITE(vMerkleBranch);
302 READWRITE(nIndex);
303 }
304
305 void SetMerkleBranch(const uint256& block_hash, int posInBlock);
306
307 /**
308 * Return depth of transaction in blockchain:
309 * <0 : conflicts with a transaction this deep in the blockchain
310 * 0 : in memory pool, waiting to be included in a block
311 * >=1 : this many blocks deep in the main chain
312 */
313 int GetDepthInMainChain(interfaces::Chain::Lock& locked_chain) const;
IsInMainChain(interfaces::Chain::Lock & locked_chain)314 bool IsInMainChain(interfaces::Chain::Lock& locked_chain) const { return GetDepthInMainChain(locked_chain) > 0; }
315
316 /**
317 * @return number of blocks to maturity for this transaction:
318 * 0 : is not a coinbase transaction, or is a mature coinbase transaction
319 * >0 : is a coinbase transaction which matures in this many blocks
320 */
321 int GetBlocksToMaturity(interfaces::Chain::Lock& locked_chain) const;
hashUnset()322 bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
isAbandoned()323 bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
setAbandoned()324 void setAbandoned() { hashBlock = ABANDON_HASH; }
325
GetHash()326 const uint256& GetHash() const { return tx->GetHash(); }
IsCoinBase()327 bool IsCoinBase() const { return tx->IsCoinBase(); }
328 bool IsImmatureCoinBase(interfaces::Chain::Lock& locked_chain) const;
329 };
330
331 //Get the marginal bytes of spending the specified output
332 int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, bool use_max_sig = false);
333
334 /**
335 * A transaction with a bunch of additional info that only the owner cares about.
336 * It includes any unrecorded transactions needed to link it back to the block chain.
337 */
338 class CWalletTx : public CMerkleTx
339 {
340 private:
341 const CWallet* pwallet;
342
343 public:
344 /**
345 * Key/value map with information about the transaction.
346 *
347 * The following keys can be read and written through the map and are
348 * serialized in the wallet database:
349 *
350 * "comment", "to" - comment strings provided to sendtoaddress,
351 * and sendmany wallet RPCs
352 * "replaces_txid" - txid (as HexStr) of transaction replaced by
353 * bumpfee on transaction created by bumpfee
354 * "replaced_by_txid" - txid (as HexStr) of transaction created by
355 * bumpfee on transaction replaced by bumpfee
356 * "from", "message" - obsolete fields that could be set in UI prior to
357 * 2011 (removed in commit 4d9b223)
358 *
359 * The following keys are serialized in the wallet database, but shouldn't
360 * be read or written through the map (they will be temporarily added and
361 * removed from the map during serialization):
362 *
363 * "fromaccount" - serialized strFromAccount value
364 * "n" - serialized nOrderPos value
365 * "timesmart" - serialized nTimeSmart value
366 * "spent" - serialized vfSpent value that existed prior to
367 * 2014 (removed in commit 93a18a3)
368 */
369 mapValue_t mapValue;
370 std::vector<std::pair<std::string, std::string> > vOrderForm;
371 unsigned int fTimeReceivedIsTxTime;
372 unsigned int nTimeReceived; //!< time received by this node
373 /**
374 * Stable timestamp that never changes, and reflects the order a transaction
375 * was added to the wallet. Timestamp is based on the block time for a
376 * transaction added as part of a block, or else the time when the
377 * transaction was received if it wasn't part of a block, with the timestamp
378 * adjusted in both cases so timestamp order matches the order transactions
379 * were added to the wallet. More details can be found in
380 * CWallet::ComputeTimeSmart().
381 */
382 unsigned int nTimeSmart;
383 /**
384 * From me flag is set to 1 for transactions that were created by the wallet
385 * on this bitcoin node, and set to 0 for transactions that were created
386 * externally and came in through the network or sendrawtransaction RPC.
387 */
388 char fFromMe;
389 int64_t nOrderPos; //!< position in ordered transaction list
390 std::multimap<int64_t, CWalletTx*>::const_iterator m_it_wtxOrdered;
391
392 // memory only
393 mutable bool fDebitCached;
394 mutable bool fCreditCached;
395 mutable bool fImmatureCreditCached;
396 mutable bool fAvailableCreditCached;
397 mutable bool fWatchDebitCached;
398 mutable bool fWatchCreditCached;
399 mutable bool fImmatureWatchCreditCached;
400 mutable bool fAvailableWatchCreditCached;
401 mutable bool fChangeCached;
402 mutable bool fInMempool;
403 mutable CAmount nDebitCached;
404 mutable CAmount nCreditCached;
405 mutable CAmount nImmatureCreditCached;
406 mutable CAmount nAvailableCreditCached;
407 mutable CAmount nWatchDebitCached;
408 mutable CAmount nWatchCreditCached;
409 mutable CAmount nImmatureWatchCreditCached;
410 mutable CAmount nAvailableWatchCreditCached;
411 mutable CAmount nChangeCached;
412
CWalletTx(const CWallet * pwalletIn,CTransactionRef arg)413 CWalletTx(const CWallet* pwalletIn, CTransactionRef arg) : CMerkleTx(std::move(arg))
414 {
415 Init(pwalletIn);
416 }
417
Init(const CWallet * pwalletIn)418 void Init(const CWallet* pwalletIn)
419 {
420 pwallet = pwalletIn;
421 mapValue.clear();
422 vOrderForm.clear();
423 fTimeReceivedIsTxTime = false;
424 nTimeReceived = 0;
425 nTimeSmart = 0;
426 fFromMe = false;
427 fDebitCached = false;
428 fCreditCached = false;
429 fImmatureCreditCached = false;
430 fAvailableCreditCached = false;
431 fWatchDebitCached = false;
432 fWatchCreditCached = false;
433 fImmatureWatchCreditCached = false;
434 fAvailableWatchCreditCached = false;
435 fChangeCached = false;
436 fInMempool = false;
437 nDebitCached = 0;
438 nCreditCached = 0;
439 nImmatureCreditCached = 0;
440 nAvailableCreditCached = 0;
441 nWatchDebitCached = 0;
442 nWatchCreditCached = 0;
443 nAvailableWatchCreditCached = 0;
444 nImmatureWatchCreditCached = 0;
445 nChangeCached = 0;
446 nOrderPos = -1;
447 }
448
449 template<typename Stream>
Serialize(Stream & s)450 void Serialize(Stream& s) const
451 {
452 char fSpent = false;
453 mapValue_t mapValueCopy = mapValue;
454
455 mapValueCopy["fromaccount"] = "";
456 WriteOrderPos(nOrderPos, mapValueCopy);
457 if (nTimeSmart) {
458 mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
459 }
460
461 s << static_cast<const CMerkleTx&>(*this);
462 std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
463 s << vUnused << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << fSpent;
464 }
465
466 template<typename Stream>
Unserialize(Stream & s)467 void Unserialize(Stream& s)
468 {
469 Init(nullptr);
470 char fSpent;
471
472 s >> static_cast<CMerkleTx&>(*this);
473 std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
474 s >> vUnused >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> fSpent;
475
476 ReadOrderPos(nOrderPos, mapValue);
477 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
478
479 mapValue.erase("fromaccount");
480 mapValue.erase("spent");
481 mapValue.erase("n");
482 mapValue.erase("timesmart");
483 }
484
485 //! make sure balances are recalculated
MarkDirty()486 void MarkDirty()
487 {
488 fCreditCached = false;
489 fAvailableCreditCached = false;
490 fImmatureCreditCached = false;
491 fWatchDebitCached = false;
492 fWatchCreditCached = false;
493 fAvailableWatchCreditCached = false;
494 fImmatureWatchCreditCached = false;
495 fDebitCached = false;
496 fChangeCached = false;
497 }
498
BindWallet(CWallet * pwalletIn)499 void BindWallet(CWallet *pwalletIn)
500 {
501 pwallet = pwalletIn;
502 MarkDirty();
503 }
504
505 //! filter decides which addresses will count towards the debit
506 CAmount GetDebit(const isminefilter& filter) const;
507 CAmount GetCredit(interfaces::Chain::Lock& locked_chain, const isminefilter& filter) const;
508 CAmount GetImmatureCredit(interfaces::Chain::Lock& locked_chain, bool fUseCache=true) const;
509 // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
510 // annotation "EXCLUSIVE_LOCKS_REQUIRED(cs_main, pwallet->cs_wallet)". The
511 // annotation "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid
512 // having to resolve the issue of member access into incomplete type CWallet.
513 CAmount GetAvailableCredit(interfaces::Chain::Lock& locked_chain, bool fUseCache=true, const isminefilter& filter=ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS;
514 CAmount GetImmatureWatchOnlyCredit(interfaces::Chain::Lock& locked_chain, const bool fUseCache=true) const;
515 CAmount GetChange() const;
516
517 // Get the marginal bytes if spending the specified output from this transaction
518 int GetSpendSize(unsigned int out, bool use_max_sig = false) const
519 {
520 return CalculateMaximumSignedInputSize(tx->vout[out], pwallet, use_max_sig);
521 }
522
523 void GetAmounts(std::list<COutputEntry>& listReceived,
524 std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const;
525
IsFromMe(const isminefilter & filter)526 bool IsFromMe(const isminefilter& filter) const
527 {
528 return (GetDebit(filter) > 0);
529 }
530
531 // True if only scriptSigs are different
532 bool IsEquivalentTo(const CWalletTx& tx) const;
533
534 bool InMempool() const;
535 bool IsTrusted(interfaces::Chain::Lock& locked_chain) const;
536
537 int64_t GetTxTime() const;
538
539 // RelayWalletTransaction may only be called if fBroadcastTransactions!
540 bool RelayWalletTransaction(interfaces::Chain::Lock& locked_chain, CConnman* connman);
541
542 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
543 bool AcceptToMemoryPool(interfaces::Chain::Lock& locked_chain, const CAmount& nAbsurdFee, CValidationState& state);
544
545 // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
546 // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
547 // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
548 // resolve the issue of member access into incomplete type CWallet. Note
549 // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
550 // in place.
551 std::set<uint256> GetConflicts() const NO_THREAD_SAFETY_ANALYSIS;
552 };
553
554 class COutput
555 {
556 public:
557 const CWalletTx *tx;
558 int i;
559 int nDepth;
560
561 /** Pre-computed estimated size of this output as a fully-signed input in a transaction. Can be -1 if it could not be calculated */
562 int nInputBytes;
563
564 /** Whether we have the private keys to spend this output */
565 bool fSpendable;
566
567 /** Whether we know how to spend this output, ignoring the lack of keys */
568 bool fSolvable;
569
570 /** 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 */
571 bool use_max_sig;
572
573 /**
574 * Whether this output is considered safe to spend. Unconfirmed transactions
575 * from outside keys and unconfirmed replacement transactions are considered
576 * unsafe and will not be used to fund new spending transactions.
577 */
578 bool fSafe;
579
580 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in = false)
581 {
582 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn; nInputBytes = -1; use_max_sig = use_max_sig_in;
583 // If known and signable by the given wallet, compute nInputBytes
584 // Failure will keep this value -1
585 if (fSpendable && tx) {
586 nInputBytes = tx->GetSpendSize(i, use_max_sig);
587 }
588 }
589
590 std::string ToString() const;
591
GetInputCoin()592 inline CInputCoin GetInputCoin() const
593 {
594 return CInputCoin(tx->tx, i, nInputBytes);
595 }
596 };
597
598 /** Private key that includes an expiration date in case it never gets used. */
599 class CWalletKey
600 {
601 public:
602 CPrivKey vchPrivKey;
603 int64_t nTimeCreated;
604 int64_t nTimeExpires;
605 std::string strComment;
606 // todo: add something to note what created it (user, getnewaddress, change)
607 // maybe should have a map<string, string> property map
608
609 explicit CWalletKey(int64_t nExpires=0);
610
611 ADD_SERIALIZE_METHODS;
612
613 template <typename Stream, typename Operation>
SerializationOp(Stream & s,Operation ser_action)614 inline void SerializationOp(Stream& s, Operation ser_action) {
615 int nVersion = s.GetVersion();
616 if (!(s.GetType() & SER_GETHASH))
617 READWRITE(nVersion);
618 READWRITE(vchPrivKey);
619 READWRITE(nTimeCreated);
620 READWRITE(nTimeExpires);
621 READWRITE(LIMITED_STRING(strComment, 65536));
622 }
623 };
624
625 struct CoinSelectionParams
626 {
627 bool use_bnb = true;
628 size_t change_output_size = 0;
629 size_t change_spend_size = 0;
630 CFeeRate effective_fee = CFeeRate(0);
631 size_t tx_noinputs_size = 0;
632
CoinSelectionParamsCoinSelectionParams633 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) {}
CoinSelectionParamsCoinSelectionParams634 CoinSelectionParams() {}
635 };
636
637 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
638 /**
639 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
640 * and provides the ability to create new transactions.
641 */
642 class CWallet final : public CCryptoKeyStore, public CValidationInterface
643 {
644 private:
645 std::atomic<bool> fAbortRescan{false};
646 std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
647 std::mutex mutexScanning;
648 friend class WalletRescanReserver;
649
650 WalletBatch *encrypted_batch GUARDED_BY(cs_wallet) = nullptr;
651
652 //! the current wallet version: clients below this version are not able to load the wallet
653 int nWalletVersion = FEATURE_BASE;
654
655 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
656 int nWalletMaxVersion GUARDED_BY(cs_wallet) = FEATURE_BASE;
657
658 int64_t nNextResend = 0;
659 int64_t nLastResend = 0;
660 bool fBroadcastTransactions = false;
661
662 /**
663 * Used to keep track of spent outpoints, and
664 * detect and report conflicts (double-spends or
665 * mutated transactions where the mutant gets mined).
666 */
667 typedef std::multimap<COutPoint, uint256> TxSpends;
668 TxSpends mapTxSpends GUARDED_BY(cs_wallet);
669 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
670 void AddToSpends(const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
671
672 /**
673 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
674 * be set when the transaction was known to be included in a block. When
675 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
676 * notifications happen and cached balances are marked dirty.
677 *
678 * If fUpdate is true, existing transactions will be updated.
679 * TODO: One exception to this is that the abandoned state is cleared under the
680 * assumption that any further notification of a transaction that was considered
681 * abandoned is an indication that it is not safe to be considered abandoned.
682 * Abandoned state should probably be more carefully tracked via different
683 * posInBlock signals or by checking mempool presence when necessary.
684 */
685 bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const uint256& block_hash, int posInBlock, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
686
687 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
688 void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
689
690 /* Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
691 void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
692
693 void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
694
695 /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
696 * Should be called with non-zero block_hash and posInBlock if this is for a transaction that is included in a block. */
697 void SyncTransaction(const CTransactionRef& tx, const uint256& block_hash, int posInBlock = 0, bool update_tx = true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
698
699 /* the HD chain data model (external chain counters) */
700 CHDChain hdChain;
701
702 /* HD derive new child key (on internal or external chain) */
703 void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
704
705 std::set<int64_t> setInternalKeyPool;
706 std::set<int64_t> setExternalKeyPool GUARDED_BY(cs_wallet);
707 std::set<int64_t> set_pre_split_keypool;
708 int64_t m_max_keypool_index GUARDED_BY(cs_wallet) = 0;
709 std::map<CKeyID, int64_t> m_pool_key_to_index;
710 std::atomic<uint64_t> m_wallet_flags{0};
711
712 int64_t nTimeFirstKey GUARDED_BY(cs_wallet) = 0;
713
714 /**
715 * Private version of AddWatchOnly method which does not accept a
716 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
717 * the watch key did not previously have a timestamp associated with it.
718 * Because this is an inherited virtual method, it is accessible despite
719 * being marked private, but it is marked private anyway to encourage use
720 * of the other AddWatchOnly which accepts a timestamp and sets
721 * nTimeFirstKey more intelligently for more efficient rescans.
722 */
723 bool AddWatchOnly(const CScript& dest) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
724
725 /** Interface for accessing chain state. */
726 interfaces::Chain& m_chain;
727
728 /** Wallet location which includes wallet name (see WalletLocation). */
729 WalletLocation m_location;
730
731 /** Internal database handle. */
732 std::unique_ptr<WalletDatabase> database;
733
734 /**
735 * The following is used to keep track of how far behind the wallet is
736 * from the chain sync, and to allow clients to block on us being caught up.
737 *
738 * Note that this is *not* how far we've processed, we may need some rescan
739 * to have seen all transactions in the chain, but is only used to track
740 * live BlockConnected callbacks.
741 */
742 uint256 m_last_block_processed;
743
744 public:
745 /*
746 * Main wallet lock.
747 * This lock protects all the fields added by CWallet.
748 */
749 mutable CCriticalSection cs_wallet;
750
751 /** Get database handle used by this wallet. Ideally this function would
752 * not be necessary.
753 */
GetDBHandle()754 WalletDatabase& GetDBHandle()
755 {
756 return *database;
757 }
758
759 /**
760 * Select a set of coins such that nValueRet >= nTargetValue and at least
761 * all coins from coinControl are selected; Never select unconfirmed coins
762 * if they are not ours
763 */
764 bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet,
765 const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
766
GetLocation()767 const WalletLocation& GetLocation() const { return m_location; }
768
769 /** Get a name for this wallet for logging/debugging purposes.
770 */
GetName()771 const std::string& GetName() const { return m_location.GetName(); }
772
773 void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
774 void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
775
776 // Map from Key ID to key metadata.
777 std::map<CKeyID, CKeyMetadata> mapKeyMetadata GUARDED_BY(cs_wallet);
778
779 // Map from Script ID to key metadata (for watch-only keys).
780 std::map<CScriptID, CKeyMetadata> m_script_metadata GUARDED_BY(cs_wallet);
781
782 bool WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, bool overwrite);
783
784 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
785 MasterKeyMap mapMasterKeys;
786 unsigned int nMasterKeyMaxID = 0;
787
788 /** Construct wallet with specified name and database implementation. */
CWallet(interfaces::Chain & chain,const WalletLocation & location,std::unique_ptr<WalletDatabase> database)789 CWallet(interfaces::Chain& chain, const WalletLocation& location, std::unique_ptr<WalletDatabase> database) : m_chain(chain), m_location(location), database(std::move(database))
790 {
791 }
792
~CWallet()793 ~CWallet()
794 {
795 // Should not have slots connected at this point.
796 assert(NotifyUnload.empty());
797 delete encrypted_batch;
798 encrypted_batch = nullptr;
799 }
800
801 std::map<uint256, CWalletTx> mapWallet GUARDED_BY(cs_wallet);
802
803 typedef std::multimap<int64_t, CWalletTx*> TxItems;
804 TxItems wtxOrdered;
805
806 int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
807 uint64_t nAccountingEntryNumber = 0;
808
809 std::map<CTxDestination, CAddressBookData> mapAddressBook GUARDED_BY(cs_wallet);
810
811 std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
812
813 /** Interface for accessing chain state. */
chain()814 interfaces::Chain& chain() const { return m_chain; }
815
816 const CWalletTx* GetWalletTx(const uint256& hash) const;
817
818 //! check whether we are allowed to upgrade (or already support) to the named feature
CanSupportFeature(enum WalletFeature wf)819 bool CanSupportFeature(enum WalletFeature wf) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
820
821 /**
822 * populate vCoins with vector of available COutputs.
823 */
824 void AvailableCoins(interfaces::Chain::Lock& locked_chain, 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 int nMinDepth = 0, const int nMaxDepth = 9999999) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
825
826 /**
827 * Return list of available coins and locked coins grouped by non-change output address.
828 */
829 std::map<CTxDestination, std::vector<COutput>> ListCoins(interfaces::Chain::Lock& locked_chain) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
830
831 /**
832 * Find non-change parent output.
833 */
834 const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
835
836 /**
837 * Shuffle and select coins until nTargetValue is reached while avoiding
838 * small change; This method is stochastic for some inputs and upon
839 * completion the coin set and corresponding actual target value is
840 * assembled
841 */
842 bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
843 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const;
844
845 bool IsSpent(interfaces::Chain::Lock& locked_chain, const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
846 std::vector<OutputGroup> GroupOutputs(const std::vector<COutput>& outputs, bool single_coin) const;
847
848 bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
849 void LockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
850 void UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
851 void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
852 void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
853
854 /*
855 * Rescan abort properties
856 */
AbortRescan()857 void AbortRescan() { fAbortRescan = true; }
IsAbortingRescan()858 bool IsAbortingRescan() { return fAbortRescan; }
IsScanning()859 bool IsScanning() { return fScanningWallet; }
860
861 /**
862 * keystore implementation
863 * Generate a new key
864 */
865 CPubKey GenerateNewKey(WalletBatch& batch, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
866 //! Adds a key to the store, and saves it to disk.
867 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
868 bool AddKeyPubKeyWithDB(WalletBatch &batch,const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
869 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
LoadKey(const CKey & key,const CPubKey & pubkey)870 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
871 //! Load metadata (used by LoadWallet)
872 void LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &metadata) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
873 void LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &metadata) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
874 //! Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo
875 void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
876
LoadMinVersion(int nVersion)877 bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
878 void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
879
880 //! Adds an encrypted key to the store, and saves it to disk.
881 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) override;
882 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
883 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
884 bool AddCScript(const CScript& redeemScript) override;
885 bool LoadCScript(const CScript& redeemScript);
886
887 //! Adds a destination data tuple to the store, and saves it to disk
888 bool AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
889 //! Erases a destination data tuple in the store and on disk
890 bool EraseDestData(const CTxDestination& dest, const std::string& key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
891 //! Adds a destination data tuple to the store, without saving it to disk
892 void LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
893 //! Look up a destination data tuple in the store, return true if found false otherwise
894 bool GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
895 //! Get all destination values matching a prefix.
896 std::vector<std::string> GetDestValues(const std::string& prefix) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
897
898 //! Adds a watch-only address to the store, and saves it to disk.
899 bool AddWatchOnly(const CScript& dest, int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
900 bool RemoveWatchOnly(const CScript &dest) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
901 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
902 bool LoadWatchOnly(const CScript &dest);
903
904 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
905 int64_t nRelockTime = 0;
906
907 bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
908 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
909 bool EncryptWallet(const SecureString& strWalletPassphrase);
910
911 void GetKeyBirthTimes(interfaces::Chain::Lock& locked_chain, std::map<CTxDestination, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
912 unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
913
914 /**
915 * Increment the next transaction order id
916 * @return next transaction order id
917 */
918 int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
919 DBErrors ReorderTransactions();
920
921 void MarkDirty();
922 bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
923 void LoadToWallet(const CWalletTx& wtxIn) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
924 void TransactionAddedToMempool(const CTransactionRef& tx) override;
925 void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) override;
926 void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override;
927 int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
928
929 struct ScanResult {
930 enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
931
932 //! Hash and height of most recent block that was successfully scanned.
933 //! Unset if no blocks were scanned due to read errors or the chain
934 //! being empty.
935 uint256 last_scanned_block;
936 Optional<int> last_scanned_height;
937
938 //! Height of the most recent block that could not be scanned due to
939 //! read errors or pruning. Will be set if status is FAILURE, unset if
940 //! status is SUCCESS, and may or may not be set if status is
941 //! USER_ABORT.
942 uint256 last_failed_block;
943 };
944 ScanResult ScanForWalletTransactions(const uint256& first_block, const uint256& last_block, const WalletRescanReserver& reserver, bool fUpdate);
945 void TransactionRemovedFromMempool(const CTransactionRef &ptx) override;
946 void ReacceptWalletTransactions(interfaces::Chain::Lock& locked_chain) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
947 void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) override EXCLUSIVE_LOCKS_REQUIRED(cs_main);
948 // ResendWalletTransactionsBefore may only be called if fBroadcastTransactions!
949 std::vector<uint256> ResendWalletTransactionsBefore(interfaces::Chain::Lock& locked_chain, int64_t nTime, CConnman* connman);
950 CAmount GetBalance(const isminefilter& filter=ISMINE_SPENDABLE, const int min_depth=0) const;
951 CAmount GetUnconfirmedBalance() const;
952 CAmount GetImmatureBalance() const;
953 CAmount GetUnconfirmedWatchOnlyBalance() const;
954 CAmount GetImmatureWatchOnlyBalance() const;
955 CAmount GetLegacyBalance(const isminefilter& filter, int minDepth) const;
956 CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
957
958 OutputType TransactionChangeType(OutputType change_type, const std::vector<CRecipient>& vecSend);
959
960 /**
961 * Insert additional inputs into the transaction by
962 * calling CreateTransaction();
963 */
964 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
965 bool SignTransaction(CMutableTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
966
967 /**
968 * Create a new transaction paying the recipients with a set of coins
969 * selected by SelectCoins(); Also create the change output, when needed
970 * @note passing nChangePosInOut as -1 will result in setting a random position
971 */
972 bool CreateTransaction(interfaces::Chain::Lock& locked_chain, const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
973 std::string& strFailReason, const CCoinControl& coin_control, bool sign = true);
974 bool CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
975
976 bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, bool use_max_sig = false) const
977 {
978 std::vector<CTxOut> v_txouts(txouts.size());
979 std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
980 return DummySignTx(txNew, v_txouts, use_max_sig);
981 }
982 bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig = false) const;
983 bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig = false) const;
984
985 CFeeRate m_pay_tx_fee{DEFAULT_PAY_TX_FEE};
986 unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
987 bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
988 bool m_signal_rbf{DEFAULT_WALLET_RBF};
989 bool m_allow_fallback_fee{true}; //!< will be defined via chainparams
990 CFeeRate m_min_fee{DEFAULT_TRANSACTION_MINFEE}; //!< Override with -mintxfee
991 /**
992 * If fee estimation does not have enough data to provide estimates, use this fee instead.
993 * Has no effect if not using fee estimation
994 * Override with -fallbackfee
995 */
996 CFeeRate m_fallback_fee{DEFAULT_FALLBACK_FEE};
997 CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
998 OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
999 OutputType m_default_change_type{DEFAULT_CHANGE_TYPE};
1000
1001 bool NewKeyPool();
1002 size_t KeypoolCountExternalKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1003 bool TopUpKeyPool(unsigned int kpSize = 0);
1004 void AddKeypoolPubkey(const CPubKey& pubkey, const bool internal);
1005 void AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch);
1006
1007 /**
1008 * Reserves a key from the keypool and sets nIndex to its index
1009 *
1010 * @param[out] nIndex the index of the key in keypool
1011 * @param[out] keypool the keypool the key was drawn from, which could be the
1012 * the pre-split pool if present, or the internal or external pool
1013 * @param fRequestedInternal true if the caller would like the key drawn
1014 * from the internal keypool, false if external is preferred
1015 *
1016 * @return true if succeeded, false if failed due to empty keypool
1017 * @throws std::runtime_error if keypool read failed, key was invalid,
1018 * was not found in the wallet, or was misclassified in the internal
1019 * or external keypool
1020 */
1021 bool ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
1022 void KeepKey(int64_t nIndex);
1023 void ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey);
1024 bool GetKeyFromPool(CPubKey &key, bool internal = false);
1025 int64_t GetOldestKeyPoolTime();
1026 /**
1027 * Marks all keys in the keypool up to and including reserve_key as used.
1028 */
1029 void MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
GetAllReserveKeys()1030 const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }
1031
1032 std::set<std::set<CTxDestination>> GetAddressGroupings() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1033 std::map<CTxDestination, CAmount> GetAddressBalances(interfaces::Chain::Lock& locked_chain);
1034
1035 std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
1036
1037 isminetype IsMine(const CTxIn& txin) const;
1038 /**
1039 * Returns amount of debit if the input matches the
1040 * filter, otherwise returns 0
1041 */
1042 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1043 isminetype IsMine(const CTxOut& txout) const;
1044 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1045 bool IsChange(const CTxOut& txout) const;
1046 bool IsChange(const CScript& script) const;
1047 CAmount GetChange(const CTxOut& txout) const;
1048 bool IsMine(const CTransaction& tx) const;
1049 /** should probably be renamed to IsRelevantToMe */
1050 bool IsFromMe(const CTransaction& tx) const;
1051 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1052 /** Returns whether all of the inputs match the filter */
1053 bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1054 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1055 CAmount GetChange(const CTransaction& tx) const;
1056 void ChainStateFlushed(const CBlockLocator& loc) override;
1057
1058 DBErrors LoadWallet(bool& fFirstRunRet);
1059 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1060 DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1061
1062 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1063
1064 bool DelAddressBook(const CTxDestination& address);
1065
1066 const std::string& GetLabelName(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1067
1068 void GetScriptForMining(std::shared_ptr<CReserveScript> &script);
1069
GetKeyPoolSize()1070 unsigned int GetKeyPoolSize() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1071 {
1072 AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool
1073 return setInternalKeyPool.size() + setExternalKeyPool.size();
1074 }
1075
1076 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1077 void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr, bool fExplicit = false);
1078
1079 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1080 bool SetMaxVersion(int nVersion);
1081
1082 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
GetVersion()1083 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1084
1085 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1086 std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1087
1088 //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
1089 bool HasWalletSpend(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1090
1091 //! Flush wallet (bitdb flush)
1092 void Flush(bool shutdown=false);
1093
1094 /** Wallet is about to be unloaded */
1095 boost::signals2::signal<void ()> NotifyUnload;
1096
1097 /**
1098 * Address book entry changed.
1099 * @note called with lock cs_wallet held.
1100 */
1101 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1102 &address, const std::string &label, bool isMine,
1103 const std::string &purpose,
1104 ChangeType status)> NotifyAddressBookChanged;
1105
1106 /**
1107 * Wallet transaction added, removed or updated.
1108 * @note called with lock cs_wallet held.
1109 */
1110 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1111 ChangeType status)> NotifyTransactionChanged;
1112
1113 /** Show progress e.g. for rescan */
1114 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1115
1116 /** Watch-only address added */
1117 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1118
1119 /** Keypool has new keys */
1120 boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
1121
1122 /** Inquire whether this wallet broadcasts transactions. */
GetBroadcastTransactions()1123 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1124 /** Set whether this wallet broadcasts transactions. */
SetBroadcastTransactions(bool broadcast)1125 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1126
1127 /** Return whether transaction can be abandoned */
1128 bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1129
1130 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1131 bool AbandonTransaction(interfaces::Chain::Lock& locked_chain, const uint256& hashTx);
1132
1133 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1134 bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1135
1136 //! Verify wallet naming and perform salvage on the wallet if required
1137 static bool Verify(interfaces::Chain& chain, const WalletLocation& location, bool salvage_wallet, std::string& error_string, std::string& warning_string);
1138
1139 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1140 static std::shared_ptr<CWallet> CreateWalletFromFile(interfaces::Chain& chain, const WalletLocation& location, uint64_t wallet_creation_flags = 0);
1141
1142 /**
1143 * Wallet post-init setup
1144 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1145 */
1146 void postInitProcess();
1147
1148 bool BackupWallet(const std::string& strDest);
1149
1150 /* Set the HD chain model (chain child index counters) */
1151 void SetHDChain(const CHDChain& chain, bool memonly);
GetHDChain()1152 const CHDChain& GetHDChain() const { return hdChain; }
1153
1154 /* Returns true if HD is enabled */
1155 bool IsHDEnabled() const;
1156
1157 /* Returns true if the wallet can generate new keys */
1158 bool CanGenerateKeys();
1159
1160 /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
1161 bool CanGetAddresses(bool internal = false);
1162
1163 /* Generates a new HD seed (will not be activated) */
1164 CPubKey GenerateNewSeed();
1165
1166 /* Derives a new HD seed (will not be activated) */
1167 CPubKey DeriveNewSeed(const CKey& key);
1168
1169 /* Set the current HD seed (will reset the chain child index counters)
1170 Sets the seed's version based on the current wallet version (so the
1171 caller must ensure the current wallet version is correct before calling
1172 this function). */
1173 void SetHDSeed(const CPubKey& key);
1174
1175 /**
1176 * Blocks until the wallet state is up-to-date to /at least/ the current
1177 * chain at the time this function is entered
1178 * Obviously holding cs_main/cs_wallet when going into this call may cause
1179 * deadlock
1180 */
1181 void BlockUntilSyncedToCurrentChain() LOCKS_EXCLUDED(cs_main, cs_wallet);
1182
1183 /**
1184 * Explicitly make the wallet learn the related scripts for outputs to the
1185 * given key. This is purely to make the wallet file compatible with older
1186 * software, as CBasicKeyStore automatically does this implicitly for all
1187 * keys now.
1188 */
1189 void LearnRelatedScripts(const CPubKey& key, OutputType);
1190
1191 /**
1192 * Same as LearnRelatedScripts, but when the OutputType is not known (and could
1193 * be anything).
1194 */
1195 void LearnAllRelatedScripts(const CPubKey& key);
1196
1197 /** set a single wallet flag */
1198 void SetWalletFlag(uint64_t flags);
1199
1200 /** Unsets a single wallet flag */
1201 void UnsetWalletFlag(uint64_t flag);
1202
1203 /** check if a certain wallet flag is set */
1204 bool IsWalletFlagSet(uint64_t flag);
1205
1206 /** overwrite all flags by the given uint64_t
1207 returns false if unknown, non-tolerable flags are present */
1208 bool SetWalletFlags(uint64_t overwriteFlags, bool memOnly);
1209
1210 /** Returns a bracketed wallet name for displaying in logs, will return [default wallet] if the wallet has no name */
GetDisplayName()1211 const std::string GetDisplayName() const {
1212 std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
1213 return strprintf("[%s]", wallet_name);
1214 };
1215
1216 /** Prepends the wallet name in logging output to ease debugging in multi-wallet use cases */
1217 template<typename... Params>
WalletLogPrintf(std::string fmt,Params...parameters)1218 void WalletLogPrintf(std::string fmt, Params... parameters) const {
1219 LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
1220 };
1221
1222 /** Implement lookup of key origin information through wallet key metadata. */
1223 bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
1224
1225 /** Add a KeyOriginInfo to the wallet */
1226 bool AddKeyOrigin(const CPubKey& pubkey, const KeyOriginInfo& info);
1227 };
1228
1229 /** A key allocated from the key pool. */
1230 class CReserveKey final : public CReserveScript
1231 {
1232 protected:
1233 CWallet* pwallet;
1234 int64_t nIndex{-1};
1235 CPubKey vchPubKey;
1236 bool fInternal{false};
1237
1238 public:
CReserveKey(CWallet * pwalletIn)1239 explicit CReserveKey(CWallet* pwalletIn)
1240 {
1241 pwallet = pwalletIn;
1242 }
1243
1244 CReserveKey(const CReserveKey&) = delete;
1245 CReserveKey& operator=(const CReserveKey&) = delete;
1246
~CReserveKey()1247 ~CReserveKey()
1248 {
1249 ReturnKey();
1250 }
1251
1252 void ReturnKey();
1253 bool GetReservedKey(CPubKey &pubkey, bool internal = false);
1254 void KeepKey();
KeepScript()1255 void KeepScript() override { KeepKey(); }
1256 };
1257
1258 /** RAII object to check and reserve a wallet rescan */
1259 class WalletRescanReserver
1260 {
1261 private:
1262 CWallet* m_wallet;
1263 bool m_could_reserve;
1264 public:
WalletRescanReserver(CWallet * w)1265 explicit WalletRescanReserver(CWallet* w) : m_wallet(w), m_could_reserve(false) {}
1266
reserve()1267 bool reserve()
1268 {
1269 assert(!m_could_reserve);
1270 std::lock_guard<std::mutex> lock(m_wallet->mutexScanning);
1271 if (m_wallet->fScanningWallet) {
1272 return false;
1273 }
1274 m_wallet->fScanningWallet = true;
1275 m_could_reserve = true;
1276 return true;
1277 }
1278
isReserved()1279 bool isReserved() const
1280 {
1281 return (m_could_reserve && m_wallet->fScanningWallet);
1282 }
1283
~WalletRescanReserver()1284 ~WalletRescanReserver()
1285 {
1286 std::lock_guard<std::mutex> lock(m_wallet->mutexScanning);
1287 if (m_could_reserve) {
1288 m_wallet->fScanningWallet = false;
1289 }
1290 }
1291 };
1292
1293 // Calculate the size of the transaction assuming all signatures are max size
1294 // Use DummySignatureCreator, which inserts 71 byte signatures everywhere.
1295 // NOTE: this requires that all inputs must be in mapWallet (eg the tx should
1296 // be IsAllFromMe).
1297 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig = false) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);
1298 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig = false);
1299 #endif // BITCOIN_WALLET_WALLET_H
1300