Bitcoin Core  0.18.99
P2P Digital Currency
wallet.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 <script/ismine.h>
15 #include <script/sign.h>
16 #include <streams.h>
17 #include <tinyformat.h>
18 #include <ui_interface.h>
19 #include <util/strencodings.h>
20 #include <util/system.h>
21 #include <validationinterface.h>
22 #include <wallet/coinselection.h>
23 #include <wallet/crypter.h>
24 #include <wallet/walletdb.h>
25 #include <wallet/walletutil.h>
26 
27 #include <algorithm>
28 #include <atomic>
29 #include <map>
30 #include <memory>
31 #include <set>
32 #include <stdexcept>
33 #include <stdint.h>
34 #include <string>
35 #include <utility>
36 #include <vector>
37 
43 void UnloadWallet(std::shared_ptr<CWallet>&& wallet);
44 
45 bool AddWallet(const std::shared_ptr<CWallet>& wallet);
46 bool RemoveWallet(const std::shared_ptr<CWallet>& wallet);
47 bool HasWallets();
48 std::vector<std::shared_ptr<CWallet>> GetWallets();
49 std::shared_ptr<CWallet> GetWallet(const std::string& name);
50 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const WalletLocation& location, std::string& error, std::string& warning);
51 
53 static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
57 static const CAmount DEFAULT_FALLBACK_FEE = 20000;
59 static const CAmount DEFAULT_DISCARD_FEE = 10000;
61 static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
63 static const CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000;
65 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
67 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
69 static const bool DEFAULT_AVOIDPARTIALSPENDS = false;
71 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
73 static const bool DEFAULT_WALLET_RBF = false;
74 static const bool DEFAULT_WALLETBROADCAST = true;
75 static const bool DEFAULT_DISABLE_WALLET = false;
77 constexpr CAmount DEFAULT_TRANSACTION_MAXFEE{COIN / 10};
79 constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
82 
84 static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
85 
86 class CCoinControl;
87 class COutput;
88 class CReserveKey;
89 class CScript;
90 class CWalletTx;
91 struct FeeCalculation;
92 enum class FeeEstimateMode;
93 
96 {
97  FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getwalletinfo's clientversion output)
98 
99  FEATURE_WALLETCRYPT = 40000, // wallet encryption
100  FEATURE_COMPRPUBKEY = 60000, // compressed public keys
101 
102  FEATURE_HD = 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
103 
104  FEATURE_HD_SPLIT = 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
105 
106  FEATURE_NO_DEFAULT_KEY = 159900, // Wallet without a default key written
107 
108  FEATURE_PRE_SPLIT_KEYPOOL = 169900, // Upgraded to HD SPLIT and can have a pre-split keypool
109 
111 };
112 
115 
118 
119 enum WalletFlags : uint64_t {
120  // wallet flags in the upper section (> 1 << 31) will lead to not opening the wallet if flag is unknown
121  // unknown wallet flags in the lower section <= (1 << 31) will be tolerated
122 
123  // Indicates that the metadata has already been upgraded to contain key origins
125 
126  // will enforce the rule that the wallet can't contain any private keys (only watch-only/pubkeys)
128 
139  WALLET_FLAG_BLANK_WALLET = (1ULL << 33),
140 };
141 
142 static constexpr uint64_t g_known_wallet_flags = WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET | WALLET_FLAG_KEY_ORIGIN_METADATA;
143 
188 class CKeyPool
189 {
190 public:
192  int64_t nTime;
196  bool fInternal;
199 
200  CKeyPool();
201  CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn);
202 
204 
205  template <typename Stream, typename Operation>
206  inline void SerializationOp(Stream& s, Operation ser_action) {
207  int nVersion = s.GetVersion();
208  if (!(s.GetType() & SER_GETHASH))
209  READWRITE(nVersion);
210  READWRITE(nTime);
211  READWRITE(vchPubKey);
212  if (ser_action.ForRead()) {
213  try {
214  READWRITE(fInternal);
215  }
216  catch (std::ios_base::failure&) {
217  /* flag as external address if we can't read the internal boolean
218  (this will be the case for any wallet before the HD chain split version) */
219  fInternal = false;
220  }
221  try {
222  READWRITE(m_pre_split);
223  }
224  catch (std::ios_base::failure&) {
225  /* flag as postsplit address if we can't read the m_pre_split boolean
226  (this will be the case for any wallet that upgrades to HD chain split)*/
227  m_pre_split = false;
228  }
229  }
230  else {
231  READWRITE(fInternal);
232  READWRITE(m_pre_split);
233  }
234  }
235 };
236 
253 {
254 protected:
258  int64_t nIndex{-1};
262  bool fInternal{false};
263 
264 public:
266  explicit CReserveKey(CWallet* pwalletIn)
267  {
268  pwallet = pwalletIn;
269  }
270 
271  CReserveKey(const CReserveKey&) = delete;
272  CReserveKey& operator=(const CReserveKey&) = delete;
273 
276  {
277  ReturnKey();
278  }
279 
281  bool GetReservedKey(CPubKey &pubkey, bool internal = false);
283  void ReturnKey();
285  void KeepKey();
286 };
287 
290 {
291 public:
292  std::string name;
293  std::string purpose;
294 
295  CAddressBookData() : purpose("unknown") {}
296 
297  typedef std::map<std::string, std::string> StringMap;
298  StringMap destdata;
299 };
300 
302 {
306 };
307 
308 typedef std::map<std::string, std::string> mapValue_t;
309 
310 
311 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
312 {
313  if (!mapValue.count("n"))
314  {
315  nOrderPos = -1; // TODO: calculate elsewhere
316  return;
317  }
318  nOrderPos = atoi64(mapValue["n"].c_str());
319 }
320 
321 
322 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
323 {
324  if (nOrderPos == -1)
325  return;
326  mapValue["n"] = i64tostr(nOrderPos);
327 }
328 
330 {
333  int vout;
334 };
335 
338 {
339 private:
341  static const uint256 ABANDON_HASH;
342 
343 public:
346 
347  /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
348  * block in the chain we know this or any in-wallet dependency conflicts
349  * with. Older clients interpret nIndex == -1 as unconfirmed for backward
350  * compatibility.
351  */
352  int nIndex;
353 
355  {
356  SetTx(MakeTransactionRef());
357  Init();
358  }
359 
361  {
362  SetTx(std::move(arg));
363  Init();
364  }
365 
366  void Init()
367  {
368  hashBlock = uint256();
369  nIndex = -1;
370  }
371 
373  {
374  tx = std::move(arg);
375  }
376 
378 
379  template <typename Stream, typename Operation>
380  inline void SerializationOp(Stream& s, Operation ser_action) {
381  std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
382  READWRITE(tx);
383  READWRITE(hashBlock);
384  READWRITE(vMerkleBranch);
385  READWRITE(nIndex);
386  }
387 
388  void SetMerkleBranch(const uint256& block_hash, int posInBlock);
389 
396  int GetDepthInMainChain(interfaces::Chain::Lock& locked_chain) const;
397  bool IsInMainChain(interfaces::Chain::Lock& locked_chain) const { return GetDepthInMainChain(locked_chain) > 0; }
398 
404  int GetBlocksToMaturity(interfaces::Chain::Lock& locked_chain) const;
405  bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
406  bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
407  void setAbandoned() { hashBlock = ABANDON_HASH; }
408 
409  const uint256& GetHash() const { return tx->GetHash(); }
410  bool IsCoinBase() const { return tx->IsCoinBase(); }
411  bool IsImmatureCoinBase(interfaces::Chain::Lock& locked_chain) const;
412 };
413 
414 //Get the marginal bytes of spending the specified output
415 int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, bool use_max_sig = false);
416 
421 class CWalletTx : public CMerkleTx
422 {
423 private:
424  const CWallet* pwallet;
425 
426 public:
452  mapValue_t mapValue;
453  std::vector<std::pair<std::string, std::string> > vOrderForm;
454  unsigned int fTimeReceivedIsTxTime;
455  unsigned int nTimeReceived;
456 
465  unsigned int nTimeSmart;
471  char fFromMe;
472  int64_t nOrderPos;
473  std::multimap<int64_t, CWalletTx*>::const_iterator m_it_wtxOrdered;
474 
475  // memory only
476  enum AmountType { DEBIT, CREDIT, IMMATURE_CREDIT, AVAILABLE_CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
477  CAmount GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate = false) const;
478  mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
479  mutable bool fChangeCached;
480  mutable bool fInMempool;
482 
483  CWalletTx(const CWallet* pwalletIn, CTransactionRef arg) : CMerkleTx(std::move(arg))
484  {
485  Init(pwalletIn);
486  }
487 
488  void Init(const CWallet* pwalletIn)
489  {
490  pwallet = pwalletIn;
491  mapValue.clear();
492  vOrderForm.clear();
493  fTimeReceivedIsTxTime = false;
494  nTimeReceived = 0;
495  nTimeSmart = 0;
496  fFromMe = false;
497  fChangeCached = false;
498  fInMempool = false;
499  nChangeCached = 0;
500  nOrderPos = -1;
501  }
502 
503  template<typename Stream>
504  void Serialize(Stream& s) const
505  {
506  char fSpent = false;
507  mapValue_t mapValueCopy = mapValue;
508 
509  mapValueCopy["fromaccount"] = "";
510  WriteOrderPos(nOrderPos, mapValueCopy);
511  if (nTimeSmart) {
512  mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
513  }
514 
515  s << static_cast<const CMerkleTx&>(*this);
516  std::vector<CMerkleTx> vUnused;
517  s << vUnused << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << fSpent;
518  }
519 
520  template<typename Stream>
521  void Unserialize(Stream& s)
522  {
523  Init(nullptr);
524  char fSpent;
525 
526  s >> static_cast<CMerkleTx&>(*this);
527  std::vector<CMerkleTx> vUnused;
528  s >> vUnused >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> fSpent;
529 
530  ReadOrderPos(nOrderPos, mapValue);
531  nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
532 
533  mapValue.erase("fromaccount");
534  mapValue.erase("spent");
535  mapValue.erase("n");
536  mapValue.erase("timesmart");
537  }
538 
540  void MarkDirty()
541  {
542  m_amounts[DEBIT].Reset();
543  m_amounts[CREDIT].Reset();
544  m_amounts[IMMATURE_CREDIT].Reset();
545  m_amounts[AVAILABLE_CREDIT].Reset();
546  fChangeCached = false;
547  }
548 
549  void BindWallet(CWallet *pwalletIn)
550  {
551  pwallet = pwalletIn;
552  MarkDirty();
553  }
554 
556  CAmount GetDebit(const isminefilter& filter) const;
557  CAmount GetCredit(interfaces::Chain::Lock& locked_chain, const isminefilter& filter) const;
558  CAmount GetImmatureCredit(interfaces::Chain::Lock& locked_chain, bool fUseCache=true) const;
559  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
560  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The
561  // annotation "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid
562  // having to resolve the issue of member access into incomplete type CWallet.
563  CAmount GetAvailableCredit(interfaces::Chain::Lock& locked_chain, bool fUseCache=true, const isminefilter& filter=ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS;
564  CAmount GetImmatureWatchOnlyCredit(interfaces::Chain::Lock& locked_chain, const bool fUseCache=true) const;
565  CAmount GetChange() const;
566 
567  // Get the marginal bytes if spending the specified output from this transaction
568  int GetSpendSize(unsigned int out, bool use_max_sig = false) const
569  {
570  return CalculateMaximumSignedInputSize(tx->vout[out], pwallet, use_max_sig);
571  }
572 
573  void GetAmounts(std::list<COutputEntry>& listReceived,
574  std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const;
575 
576  bool IsFromMe(const isminefilter& filter) const
577  {
578  return (GetDebit(filter) > 0);
579  }
580 
581  // True if only scriptSigs are different
582  bool IsEquivalentTo(const CWalletTx& tx) const;
583 
584  bool InMempool() const;
585  bool IsTrusted(interfaces::Chain::Lock& locked_chain) const;
586 
587  int64_t GetTxTime() const;
588 
589  // Pass this transaction to the node to relay to its peers
590  bool RelayWalletTransaction(interfaces::Chain::Lock& locked_chain);
591 
593  bool AcceptToMemoryPool(interfaces::Chain::Lock& locked_chain, CValidationState& state);
594 
595  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
596  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
597  // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
598  // resolve the issue of member access into incomplete type CWallet. Note
599  // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
600  // in place.
601  std::set<uint256> GetConflicts() const NO_THREAD_SAFETY_ANALYSIS;
602 };
603 
604 class COutput
605 {
606 public:
607  const CWalletTx *tx;
608  int i;
609  int nDepth;
610 
613 
616 
618  bool fSolvable;
619 
622 
628  bool fSafe;
629 
630  COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in = false)
631  {
632  tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn; nInputBytes = -1; use_max_sig = use_max_sig_in;
633  // If known and signable by the given wallet, compute nInputBytes
634  // Failure will keep this value -1
635  if (fSpendable && tx) {
636  nInputBytes = tx->GetSpendSize(i, use_max_sig);
637  }
638  }
639 
640  std::string ToString() const;
641 
642  inline CInputCoin GetInputCoin() const
643  {
644  return CInputCoin(tx->tx, i, nInputBytes);
645  }
646 };
647 
650 {
651 public:
653  int64_t nTimeCreated;
654  int64_t nTimeExpires;
655  std::string strComment;
656  // todo: add something to note what created it (user, getnewaddress, change)
657  // maybe should have a map<string, string> property map
658 
659  explicit CWalletKey(int64_t nExpires=0);
660 
662 
663  template <typename Stream, typename Operation>
664  inline void SerializationOp(Stream& s, Operation ser_action) {
665  int nVersion = s.GetVersion();
666  if (!(s.GetType() & SER_GETHASH))
667  READWRITE(nVersion);
668  READWRITE(vchPrivKey);
669  READWRITE(nTimeCreated);
670  READWRITE(nTimeExpires);
671  READWRITE(LIMITED_STRING(strComment, 65536));
672  }
673 };
674 
676 {
677  bool use_bnb = true;
678  size_t change_output_size = 0;
679  size_t change_spend_size = 0;
680  CFeeRate effective_fee = CFeeRate(0);
681  size_t tx_noinputs_size = 0;
682 
683  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) {}
685 };
686 
687 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
693 {
694 private:
695  std::atomic<bool> fAbortRescan{false};
696  std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
697  std::atomic<int64_t> m_scanning_start{0};
698  std::atomic<double> m_scanning_progress{0};
699  std::mutex mutexScanning;
700  friend class WalletRescanReserver;
701 
702  WalletBatch *encrypted_batch GUARDED_BY(cs_wallet) = nullptr;
703 
705  int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
706 
708  int nWalletMaxVersion GUARDED_BY(cs_wallet) = FEATURE_BASE;
709 
710  int64_t nNextResend = 0;
711  int64_t nLastResend = 0;
712  bool fBroadcastTransactions = false;
713  // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
714  std::atomic<int64_t> m_best_block_time {0};
715 
721  typedef std::multimap<COutPoint, uint256> TxSpends;
722  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
723  void AddToSpends(const COutPoint& outpoint, const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
724  void AddToSpends(const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
725 
739  bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const uint256& block_hash, int posInBlock, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
740 
741  /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
742  void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
743 
744  /* Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
745  void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
746 
747  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
748 
749  /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
750  * Should be called with non-zero block_hash and posInBlock if this is for a transaction that is included in a block. */
751  void SyncTransaction(const CTransactionRef& tx, const uint256& block_hash, int posInBlock = 0, bool update_tx = true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
752 
753  /* the HD chain data model (external chain counters) */
754  CHDChain hdChain;
755 
756  /* HD derive new child key (on internal or external chain) */
757  void DeriveNewChildKey(WalletBatch& batch, CKeyMetadata& metadata, CKey& secret, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
758 
759  std::set<int64_t> setInternalKeyPool GUARDED_BY(cs_wallet);
760  std::set<int64_t> setExternalKeyPool GUARDED_BY(cs_wallet);
761  std::set<int64_t> set_pre_split_keypool GUARDED_BY(cs_wallet);
762  int64_t m_max_keypool_index GUARDED_BY(cs_wallet) = 0;
763  std::map<CKeyID, int64_t> m_pool_key_to_index;
764  std::atomic<uint64_t> m_wallet_flags{0};
765 
766  int64_t nTimeFirstKey GUARDED_BY(cs_wallet) = 0;
767 
777  bool AddWatchOnly(const CScript& dest) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
778 
781 
784 
786  std::unique_ptr<WalletDatabase> database;
787 
796  uint256 m_last_block_processed GUARDED_BY(cs_wallet);
797 
798 public:
799  /*
800  * Main wallet lock.
801  * This lock protects all the fields added by CWallet.
802  */
804 
809  {
810  return *database;
811  }
812 
818  bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet,
819  const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
820 
821  const WalletLocation& GetLocation() const { return m_location; }
822 
825  const std::string& GetName() const { return m_location.GetName(); }
826 
827  void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
828  void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
829 
830  // Map from Key ID to key metadata.
831  std::map<CKeyID, CKeyMetadata> mapKeyMetadata GUARDED_BY(cs_wallet);
832 
833  // Map from Script ID to key metadata (for watch-only keys).
834  std::map<CScriptID, CKeyMetadata> m_script_metadata GUARDED_BY(cs_wallet);
835 
836  bool WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, bool overwrite);
837 
838  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
839  MasterKeyMap mapMasterKeys;
840  unsigned int nMasterKeyMaxID = 0;
841 
843  CWallet(interfaces::Chain* chain, const WalletLocation& location, std::unique_ptr<WalletDatabase> database)
844  : m_chain(chain),
845  m_location(location),
846  database(std::move(database))
847  {
848  }
849 
851  {
852  // Should not have slots connected at this point.
853  assert(NotifyUnload.empty());
854  delete encrypted_batch;
855  encrypted_batch = nullptr;
856  }
857 
858  std::map<uint256, CWalletTx> mapWallet GUARDED_BY(cs_wallet);
859 
860  typedef std::multimap<int64_t, CWalletTx*> TxItems;
861  TxItems wtxOrdered;
862 
863  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
864  uint64_t nAccountingEntryNumber = 0;
865 
866  std::map<CTxDestination, CAddressBookData> mapAddressBook GUARDED_BY(cs_wallet);
867 
868  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
869 
871  std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
872 
874  void handleNotifications();
875 
877  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
878 
879  const CWalletTx* GetWalletTx(const uint256& hash) const;
880 
882  bool CanSupportFeature(enum WalletFeature wf) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
883 
887  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);
888 
892  std::map<CTxDestination, std::vector<COutput>> ListCoins(interfaces::Chain::Lock& locked_chain) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
893 
897  const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
898 
905  bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
906  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const;
907 
908  bool IsSpent(interfaces::Chain::Lock& locked_chain, const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
909  std::vector<OutputGroup> GroupOutputs(const std::vector<COutput>& outputs, bool single_coin) const;
910 
911  bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
912  void LockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
913  void UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
914  void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
915  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
916 
917  /*
918  * Rescan abort properties
919  */
920  void AbortRescan() { fAbortRescan = true; }
921  bool IsAbortingRescan() { return fAbortRescan; }
922  bool IsScanning() { return fScanningWallet; }
923  int64_t ScanningDuration() const { return fScanningWallet ? GetTimeMillis() - m_scanning_start : 0; }
924  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
925 
930  CPubKey GenerateNewKey(WalletBatch& batch, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
932  bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
933  bool AddKeyPubKeyWithDB(WalletBatch &batch,const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
935  bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
937  void LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &metadata) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
938  void LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &metadata) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
940  void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
941 
942  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
943  void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
944 
946  bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) override;
948  bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
949  bool AddCScript(const CScript& redeemScript) override;
950  bool LoadCScript(const CScript& redeemScript);
951 
953  bool AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
955  bool EraseDestData(const CTxDestination& dest, const std::string& key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
957  void LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
959  bool GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
961  std::vector<std::string> GetDestValues(const std::string& prefix) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
962 
964  bool AddWatchOnly(const CScript& dest, int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
965  bool RemoveWatchOnly(const CScript &dest) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
967  bool LoadWatchOnly(const CScript &dest);
968 
970  int64_t nRelockTime = 0;
971 
972  bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
973  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
974  bool EncryptWallet(const SecureString& strWalletPassphrase);
975 
976  void GetKeyBirthTimes(interfaces::Chain::Lock& locked_chain, std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
977  unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
978 
983  int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
984  DBErrors ReorderTransactions();
985 
986  void MarkDirty();
987  bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
988  void LoadToWallet(const CWalletTx& wtxIn) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
989  void TransactionAddedToMempool(const CTransactionRef& tx) override;
990  void BlockConnected(const CBlock& block, const std::vector<CTransactionRef>& vtxConflicted) override;
991  void BlockDisconnected(const CBlock& block) override;
992  void UpdatedBlockTip() override;
993  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
994 
995  struct ScanResult {
996  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
997 
1003 
1009  };
1010  ScanResult ScanForWalletTransactions(const uint256& first_block, const uint256& last_block, const WalletRescanReserver& reserver, bool fUpdate);
1011  void TransactionRemovedFromMempool(const CTransactionRef &ptx) override;
1012  void ReacceptWalletTransactions(interfaces::Chain::Lock& locked_chain) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1013  void ResendWalletTransactions();
1014  struct Balance {
1015  CAmount m_mine_trusted{0};
1016  CAmount m_mine_untrusted_pending{0};
1017  CAmount m_mine_immature{0};
1018  CAmount m_watchonly_trusted{0};
1019  CAmount m_watchonly_untrusted_pending{0};
1020  CAmount m_watchonly_immature{0};
1021  };
1022  Balance GetBalance(int min_depth = 0) const;
1023  CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
1024 
1025  OutputType TransactionChangeType(OutputType change_type, const std::vector<CRecipient>& vecSend);
1026 
1031  bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
1033 
1039  bool CreateTransaction(interfaces::Chain::Lock& locked_chain, const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
1040  std::string& strFailReason, const CCoinControl& coin_control, bool sign = true);
1041  bool CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm, CReserveKey& reservekey, CValidationState& state);
1042 
1043  bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, bool use_max_sig = false) const
1044  {
1045  std::vector<CTxOut> v_txouts(txouts.size());
1046  std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
1047  return DummySignTx(txNew, v_txouts, use_max_sig);
1048  }
1049  bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig = false) const;
1050  bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig = false) const;
1051 
1053  unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
1054  bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
1055  bool m_signal_rbf{DEFAULT_WALLET_RBF};
1056  bool m_allow_fallback_fee{true};
1057  CFeeRate m_min_fee{DEFAULT_TRANSACTION_MINFEE};
1058 
1063  CFeeRate m_fallback_fee{DEFAULT_FALLBACK_FEE};
1064  CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
1065  OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
1066  OutputType m_default_change_type{DEFAULT_CHANGE_TYPE};
1068  CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
1069 
1070  bool NewKeyPool();
1071  size_t KeypoolCountExternalKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1072  bool TopUpKeyPool(unsigned int kpSize = 0);
1073  void AddKeypoolPubkey(const CPubKey& pubkey, const bool internal);
1074  void AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch);
1075 
1090  bool ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
1091  void KeepKey(int64_t nIndex);
1092  void ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey);
1093  bool GetKeyFromPool(CPubKey &key, bool internal = false);
1094  int64_t GetOldestKeyPoolTime();
1098  void MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1099  const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }
1100 
1101  std::set<std::set<CTxDestination>> GetAddressGroupings() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1102  std::map<CTxDestination, CAmount> GetAddressBalances(interfaces::Chain::Lock& locked_chain);
1103 
1104  std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
1105 
1106  isminetype IsMine(const CTxIn& txin) const;
1111  CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1112  isminetype IsMine(const CTxOut& txout) const;
1113  CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1114  bool IsChange(const CTxOut& txout) const;
1115  bool IsChange(const CScript& script) const;
1116  CAmount GetChange(const CTxOut& txout) const;
1117  bool IsMine(const CTransaction& tx) const;
1119  bool IsFromMe(const CTransaction& tx) const;
1120  CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1122  bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1123  CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1124  CAmount GetChange(const CTransaction& tx) const;
1125  void ChainStateFlushed(const CBlockLocator& loc) override;
1126 
1127  DBErrors LoadWallet(bool& fFirstRunRet);
1128  DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1129  DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1130 
1131  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1132 
1133  bool DelAddressBook(const CTxDestination& address);
1134 
1135  const std::string& GetLabelName(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1136 
1137  unsigned int GetKeyPoolSize() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1138  {
1139  AssertLockHeld(cs_wallet);
1140  return setInternalKeyPool.size() + setExternalKeyPool.size();
1141  }
1142 
1144  void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr, bool fExplicit = false);
1145 
1147  bool SetMaxVersion(int nVersion);
1148 
1150  int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1151 
1153  std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1154 
1156  bool HasWalletSpend(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1157 
1159  void Flush(bool shutdown=false);
1160 
1162  boost::signals2::signal<void ()> NotifyUnload;
1163 
1168  boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1169  &address, const std::string &label, bool isMine,
1170  const std::string &purpose,
1172 
1177  boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1179 
1181  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1182 
1184  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1185 
1187  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
1188 
1190  bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1192  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1193 
1195  bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1196 
1197  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1198  bool AbandonTransaction(interfaces::Chain::Lock& locked_chain, const uint256& hashTx);
1199 
1201  bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1202 
1204  static bool Verify(interfaces::Chain& chain, const WalletLocation& location, bool salvage_wallet, std::string& error_string, std::string& warning_string);
1205 
1206  /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1207  static std::shared_ptr<CWallet> CreateWalletFromFile(interfaces::Chain& chain, const WalletLocation& location, uint64_t wallet_creation_flags = 0);
1208 
1213  void postInitProcess();
1214 
1215  bool BackupWallet(const std::string& strDest);
1216 
1217  /* Set the HD chain model (chain child index counters) */
1218  void SetHDChain(const CHDChain& chain, bool memonly);
1219  const CHDChain& GetHDChain() const { return hdChain; }
1220 
1221  /* Returns true if HD is enabled */
1222  bool IsHDEnabled() const;
1223 
1224  /* Returns true if the wallet can generate new keys */
1225  bool CanGenerateKeys();
1226 
1227  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
1228  bool CanGetAddresses(bool internal = false);
1229 
1230  /* Generates a new HD seed (will not be activated) */
1231  CPubKey GenerateNewSeed();
1232 
1233  /* Derives a new HD seed (will not be activated) */
1234  CPubKey DeriveNewSeed(const CKey& key);
1235 
1236  /* Set the current HD seed (will reset the chain child index counters)
1237  Sets the seed's version based on the current wallet version (so the
1238  caller must ensure the current wallet version is correct before calling
1239  this function). */
1240  void SetHDSeed(const CPubKey& key);
1241 
1248  void BlockUntilSyncedToCurrentChain() LOCKS_EXCLUDED(cs_main, cs_wallet);
1249 
1256  void LearnRelatedScripts(const CPubKey& key, OutputType);
1257 
1262  void LearnAllRelatedScripts(const CPubKey& key);
1263 
1265  void SetWalletFlag(uint64_t flags);
1266 
1268  void UnsetWalletFlag(uint64_t flag);
1269 
1271  bool IsWalletFlagSet(uint64_t flag);
1272 
1275  bool SetWalletFlags(uint64_t overwriteFlags, bool memOnly);
1276 
1278  const std::string GetDisplayName() const {
1279  std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
1280  return strprintf("[%s]", wallet_name);
1281  };
1282 
1284  template<typename... Params>
1285  void WalletLogPrintf(std::string fmt, Params... parameters) const {
1286  LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
1287  };
1288 
1290  bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;
1291 
1293  bool AddKeyOrigin(const CPubKey& pubkey, const KeyOriginInfo& info);
1294 };
1295 
1300 void MaybeResendWalletTxs();
1301 
1304 {
1305 private:
1308 public:
1309  explicit WalletRescanReserver(CWallet* w) : m_wallet(w), m_could_reserve(false) {}
1310 
1311  bool reserve()
1312  {
1313  assert(!m_could_reserve);
1314  std::lock_guard<std::mutex> lock(m_wallet->mutexScanning);
1315  if (m_wallet->fScanningWallet) {
1316  return false;
1317  }
1318  m_wallet->m_scanning_start = GetTimeMillis();
1319  m_wallet->m_scanning_progress = 0;
1320  m_wallet->fScanningWallet = true;
1321  m_could_reserve = true;
1322  return true;
1323  }
1324 
1325  bool isReserved() const
1326  {
1327  return (m_could_reserve && m_wallet->fScanningWallet);
1328  }
1329 
1331  {
1332  std::lock_guard<std::mutex> lock(m_wallet->mutexScanning);
1333  if (m_could_reserve) {
1334  m_wallet->fScanningWallet = false;
1335  }
1336  }
1337 };
1338 
1339 // Calculate the size of the transaction assuming all signatures are max size
1340 // Use DummySignatureCreator, which inserts 71 byte signatures everywhere.
1341 // NOTE: this requires that all inputs must be in mapWallet (eg the tx should
1342 // be IsAllFromMe).
1343 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig = false) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);
1344 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig = false);
1345 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:408
AmountType
Definition: wallet.h:476
int64_t nTimeCreated
Definition: wallet.h:653
bool fChangeCached
Definition: wallet.h:479
const CWallet * pwallet
Definition: wallet.h:424
std::atomic< bool > fScanningWallet
Definition: wallet.h:696
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:53
CWallet * pwallet
The wallet to reserve the keypool key from.
Definition: wallet.h:256
void SetTx(CTransactionRef arg)
Definition: wallet.h:372
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned.
Definition: wallet.h:341
std::unique_ptr< WalletDatabase > database
Internal database handle.
Definition: wallet.h:786
void SerializationOp(Stream &s, Operation ser_action)
Definition: wallet.h:664
int i
Definition: wallet.h:608
void BindWallet(CWallet *pwalletIn)
Definition: wallet.h:549
UniValue SignTransaction(CMutableTransaction &mtx, const UniValue &prevTxsUnival, CBasicKeyStore *keystore, std::map< COutPoint, Coin > &coins, bool is_temp_keystore, const UniValue &hashType)
Sign a transaction with the given keystore and previous transactions.
std::unique_ptr< interfaces::Handler > m_chain_notifications_handler
Registered interfaces::Chain::Notifications handler.
Definition: wallet.h:871
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:308
bool CanSupportFeature(enum WalletFeature wf) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we are allowed to upgrade (or already support) to the named feature ...
Definition: wallet.h:882
bool fSolvable
Whether we know how to spend this output, ignoring the lack of keys.
Definition: wallet.h:618
CPrivKey vchPrivKey
Definition: wallet.h:652
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:77
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:126
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:1187
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:81
const std::map< CKeyID, int64_t > & GetAllReserveKeys() const
Definition: wallet.h:1099
char fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node...
Definition: wallet.h:471
CAmount nChangeCached
Definition: wallet.h:481
constexpr CAmount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:55
Definition: block.h:72
int64_t GetTimeMillis()
Definition: time.cpp:40
CCriticalSection cs_wallet
Definition: wallet.h:803
#define strprintf
Definition: tinyformat.h:1066
const uint256 & GetHash() const
Definition: wallet.h:409
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:576
int nIndex
Definition: wallet.h:352
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:1043
constexpr OutputType DEFAULT_CHANGE_TYPE
Default for -changetype.
Definition: wallet.h:117
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
Definition: wallet.h:139
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:1001
bool use_max_sig
Whether to use the maximum sized, 72 byte signature when calculating the size of the input spend...
Definition: wallet.h:621
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:49
FeeEstimateMode
Definition: fees.h:50
TxItems wtxOrdered
Definition: wallet.h:861
const char * prefix
Definition: rest.cpp:625
uint256 hashBlock
Definition: wallet.h:345
CWallet(interfaces::Chain *chain, const WalletLocation &location, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:843
std::multimap< COutPoint, uint256 > TxSpends
Used to keep track of spent outpoints, and detect and report conflicts (double-spends or mutated tran...
Definition: wallet.h:721
Interface for querying locked chain state, used by legacy code that assumes state won&#39;t change betwee...
Definition: chain.h:68
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:60
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:472
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const WalletLocation &location, std::string &error, std::string &warning)
Definition: wallet.cpp:138
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: wallet.h:473
An instance of this class represents one database.
Definition: db.h:113
CMerkleTx(CTransactionRef arg)
Definition: wallet.h:360
uint8_t isminefilter
used for bitflags of isminetype
Definition: ismine.h:27
int nWalletVersion GUARDED_BY(cs_wallet)
the current wallet version: clients below this version are not able to load the wallet ...
Definition: wallet.h:705
WalletFeature
(client) version numbers for particular wallet features
Definition: wallet.h:95
CPubKey vchPubKey
The public key.
Definition: wallet.h:260
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:540
bool fSubtractFeeFromAmount
Definition: wallet.h:305
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:838
std::string strComment
Definition: wallet.h:655
std::string name
Definition: wallet.h:292
int nInputBytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: wallet.h:612
~CReserveKey()
Destructor. If a key has been reserved and not KeepKey&#39;ed, it will be returned to the keypool...
Definition: wallet.h:275
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:115
int64_t ScanningDuration() const
Definition: wallet.h:923
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:48
Keystore which keeps the private keys encrypted.
Definition: crypter.h:115
bool fSpendable
Whether we have the private keys to spend this output.
Definition: wallet.h:615
int64_t nTimeExpires
Definition: wallet.h:654
bool IsNull() const
Definition: uint256.h:31
std::string purpose
Definition: wallet.h:293
void Init()
Definition: wallet.h:366
OutputType
Definition: outputtype.h:16
Coin Control Features.
Definition: coincontrol.h:16
double ScanningProgress() const
Definition: wallet.h:924
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee, bool test_accept)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
Definition: validation.cpp:999
Access to the wallet database.
Definition: walletdb.h:150
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:452
std::mutex mutexScanning
Definition: wallet.h:699
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:877
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
boost::signals2::signal< void()> NotifyUnload
Wallet is about to be unloaded.
Definition: wallet.h:1162
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Add a key to the store.
Definition: crypter.cpp:216
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
secure_allocator is defined in allocators.h CPrivKey is a serialized private key, with all parameters...
Definition: key.h:24
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:1178
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:1192
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in=false)
Definition: wallet.h:630
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
Definition: wallet.h:192
void Unserialize(Stream &s)
Definition: wallet.h:521
CScript scriptPubKey
Definition: wallet.h:303
CCriticalSection cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:235
int nDepth
Definition: wallet.h:609
const std::string & GetName() const
Get wallet name.
Definition: walletutil.h:29
ChangeType
General change type (added, updated, removed).
Definition: ui_interface.h:26
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Definition: wallet.h:1285
CTransactionRef tx
Definition: wallet.h:344
Chain & m_chain
Definition: chain.cpp:201
isminetype
IsMine() return codes.
Definition: ismine.h:18
An input of a transaction.
Definition: transaction.h:63
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *pwallet, bool use_max_sig=false)
Definition: wallet.cpp:1638
unsigned int GetKeyPoolSize() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:1137
#define LOCK(cs)
Definition: sync.h:182
const char * name
Definition: rest.cpp:38
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:1150
CKeyPool()
Definition: wallet.cpp:4315
Chain notifications.
Definition: chain.h:228
void SerializationOp(Stream &s, Operation ser_action)
Definition: wallet.h:380
An encapsulated public key.
Definition: pubkey.h:30
bool fSafe
Whether this output is considered safe to spend.
Definition: wallet.h:628
CAmount amount
Definition: wallet.h:332
std::string i64tostr(int64_t n)
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:780
bool IsCoinBase() const
Definition: wallet.h:410
std::map< std::string, std::string > StringMap
Definition: wallet.h:297
WalletDatabase & GetDBHandle()
Get database handle used by this wallet.
Definition: wallet.h:808
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
Definition: wallet.h:935
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
Definition: wallet.h:198
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:114
An output of a transaction.
Definition: transaction.h:133
const WalletLocation & GetLocation() const
Definition: wallet.h:821
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:81
ADD_SERIALIZE_METHODS
Definition: wallet.h:377
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
ADD_SERIALIZE_METHODS
Definition: wallet.h:203
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:454
Special output type for change outputs only.
CAmount nAmount
Definition: wallet.h:304
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1303
bool HasWallets()
Definition: wallet.cpp:69
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:421
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:1190
CWallet * m_wallet
Definition: wallet.h:1306
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:59
void Serialize(Stream &s) const
Definition: wallet.h:504
int flags
Definition: bitcoin-tx.cpp:507
bool fInMempool
Definition: wallet.h:480
Capture information about block/transaction validation.
Definition: validation.h:98
256-bit opaque blob.
Definition: uint256.h:121
void Init(const CWallet *pwalletIn)
Definition: wallet.h:488
CPubKey vchPubKey
The public key.
Definition: wallet.h:194
int64_t atoi64(const char *psz)
CWalletTx(const CWallet *pwalletIn, CTransactionRef arg)
Definition: wallet.h:483
void setAbandoned()
Definition: wallet.h:407
Cachable amount subdivided into watchonly and spendable parts.
Definition: ismine.h:35
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
WalletLocation m_location
Wallet location which includes wallet name (see WalletLocation).
Definition: wallet.h:783
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), 0)
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:50
boost::signals2::signal< void(CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:1171
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:825
MasterKeyMap mapMasterKeys
Definition: wallet.h:839
int vout
Definition: wallet.h:333
A wrapper to reserve a key from a wallet keypool.
Definition: wallet.h:252
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:58
Result CommitTransaction(CWallet *wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< std::string > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:312
Address book data.
Definition: wallet.h:289
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
StringMap destdata
Definition: wallet.h:298
CTxDestination destination
Definition: wallet.h:331
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:465
CInputCoin GetInputCoin() const
Definition: wallet.h:642
void Reset()
Definition: ismine.h:40
int GetSpendSize(unsigned int out, bool use_max_sig=false) const
Definition: wallet.h:568
ADD_SERIALIZE_METHODS
Definition: wallet.h:661
isminetype IsMine(const CKeyStore &keystore, const CScript &scriptPubKey)
Definition: ismine.cpp:175
Private key that includes an expiration date in case it never gets used.
Definition: wallet.h:649
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:20
const CWalletTx * tx
Definition: wallet.h:607
#define LIMITED_STRING(obj, n)
Definition: serialize.h:424
CoinSelectionParams(bool use_bnb, size_t change_output_size, size_t change_spend_size, CFeeRate effective_fee, size_t tx_noinputs_size)
Definition: wallet.h:683
bool IsScanning()
Definition: wallet.h:922
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:692
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:2123
bool IsInMainChain(interfaces::Chain::Lock &locked_chain) const
Definition: wallet.h:397
CReserveKey(CWallet *pwalletIn)
Construct a CReserveKey object. This does NOT reserve a key from the keypool yet. ...
Definition: wallet.h:266
void AbortRescan()
Definition: wallet.h:920
Definition: wallet.h:329
#define GUARDED_BY(x)
Definition: threadsafety.h:38
void FundTransaction(CWallet *const pwallet, CMutableTransaction &tx, CAmount &fee_out, int &change_position, UniValue options)
Definition: rpcwallet.cpp:2986
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:1181
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:22
void SerializationOp(Stream &s, Operation ser_action)
Definition: wallet.h:206
Optional< int > last_scanned_height
Definition: wallet.h:1002
A mutable version of CTransaction.
Definition: transaction.h:366
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:1008
bool IsAbortingRescan()
Definition: wallet.h:921
WalletFlags
Definition: wallet.h:119
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:942
The WalletLocation class provides wallet information.
Definition: walletutil.h:19
CMerkleTx()
Definition: wallet.h:354
std::atomic< int64_t > m_scanning_start
Definition: wallet.h:697
unsigned int nTimeReceived
time received by this node
Definition: wallet.h:455
An encapsulated private key.
Definition: key.h:27
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
bool isReserved() const
Definition: wallet.h:1325
bool hashUnset() const
Definition: wallet.h:405
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:139
std::atomic< double > m_scanning_progress
Definition: wallet.h:698
const CHDChain & GetHDChain() const
Definition: wallet.h:1219
AssertLockHeld(g_cs_orphans)
WalletRescanReserver(CWallet *w)
Definition: wallet.h:1309
#define READWRITE(...)
Definition: serialize.h:184
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:1184
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:860
bool error(const char *fmt, const Args &... args)
Definition: system.h:61
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
Definition: wallet.h:196
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig=false) EXCLUSIVE_LOCKS_REQUIRED(wallet -> cs_wallet)
Definition: wallet.cpp:1609
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:67
A transaction with a merkle branch linking it to the block chain.
Definition: wallet.h:337
~CWallet()
Definition: wallet.h:850
A key from a CWallet&#39;s keypool.
Definition: wallet.h:188
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:79
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:453
bool isAbandoned() const
Definition: wallet.h:406