Bitcoin ABC  0.22.13
P2P Digital Currency
wallet.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2018-2020 The Bitcoin developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #ifndef BITCOIN_WALLET_WALLET_H
8 #define BITCOIN_WALLET_WALLET_H
9 
10 #include <amount.h>
11 #include <interfaces/chain.h>
12 #include <interfaces/handler.h>
13 #include <outputtype.h>
14 #include <primitives/blockhash.h>
15 #include <psbt.h>
16 #include <tinyformat.h>
17 #include <util/message.h>
18 #include <util/strencodings.h>
19 #include <util/string.h>
20 #include <util/system.h>
21 #include <util/translation.h>
22 #include <util/ui_change_type.h>
23 #include <validationinterface.h>
24 #include <wallet/coinselection.h>
25 #include <wallet/crypter.h>
26 #include <wallet/rpcwallet.h>
27 #include <wallet/scriptpubkeyman.h>
28 #include <wallet/walletdb.h>
29 #include <wallet/walletutil.h>
30 
31 #include <algorithm>
32 #include <atomic>
33 #include <cstdint>
34 #include <map>
35 #include <memory>
36 #include <set>
37 #include <stdexcept>
38 #include <string>
39 #include <utility>
40 #include <vector>
41 
42 #include <boost/signals2/signal.hpp>
43 
44 using LoadWalletFn =
45  std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
46 
47 struct bilingual_str;
48 
54 void UnloadWallet(std::shared_ptr<CWallet> &&wallet);
55 
56 bool AddWallet(const std::shared_ptr<CWallet> &wallet);
57 bool RemoveWallet(const std::shared_ptr<CWallet> &wallet);
58 bool HasWallets();
59 std::vector<std::shared_ptr<CWallet>> GetWallets();
60 std::shared_ptr<CWallet> GetWallet(const std::string &name);
61 std::shared_ptr<CWallet> LoadWallet(const CChainParams &chainParams,
62  interfaces::Chain &chain,
63  const WalletLocation &location,
65  std::vector<bilingual_str> &warnings);
66 std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet);
67 
69 
71  interfaces::Chain &chain,
72  const SecureString &passphrase,
73  uint64_t wallet_creation_flags,
74  const std::string &name, bilingual_str &error,
75  std::vector<bilingual_str> &warnings,
76  std::shared_ptr<CWallet> &result);
95 constexpr Amount HIGH_APS_FEE{COIN / 10000};
97 static const Amount WALLET_INCREMENTAL_RELAY_FEE(5000 * SATOSHI);
99 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
101 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
102 static const bool DEFAULT_WALLETBROADCAST = true;
103 static const bool DEFAULT_DISABLE_WALLET = false;
107 constexpr Amount HIGH_TX_FEE_PER_KB{COIN / 100};
112 static constexpr size_t DUMMY_P2PKH_INPUT_SIZE = 148;
113 
114 class CChainParams;
115 class CCoinControl;
116 class COutput;
117 class CScript;
118 class CTxMemPool;
119 class CWalletTx;
120 class ReserveDestination;
121 
124 
127 
128 static constexpr uint64_t KNOWN_WALLET_FLAGS =
132 
133 static constexpr uint64_t MUTABLE_WALLET_FLAGS = WALLET_FLAG_AVOID_REUSE;
134 
135 static const std::map<std::string, WalletFlags> WALLET_FLAG_MAP{
136  {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
137  {"blank", WALLET_FLAG_BLANK_WALLET},
138  {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
139  {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
140  {"descriptor_wallet", WALLET_FLAG_DESCRIPTORS},
141 };
142 
143 extern const std::map<uint64_t, std::string> WALLET_FLAG_CAVEATS;
144 
162 protected:
164  const CWallet *const pwallet;
167  ScriptPubKeyMan *m_spk_man{nullptr};
170  int64_t nIndex{-1};
174  bool fInternal{false};
175 
176 public:
179  explicit ReserveDestination(CWallet *_pwallet, OutputType _type)
180  : pwallet(_pwallet), type(_type) {}
181 
182  ReserveDestination(const ReserveDestination &) = delete;
183  ReserveDestination &operator=(const ReserveDestination &) = delete;
184 
187  ~ReserveDestination() { ReturnDestination(); }
188 
190  bool GetReservedDestination(CTxDestination &pubkey, bool internal);
192  void ReturnDestination();
195  void KeepDestination();
196 };
197 
200 private:
201  bool m_change{true};
202  std::string m_label;
203 
204 public:
205  std::string purpose;
206 
207  CAddressBookData() : purpose("unknown") {}
208 
209  typedef std::map<std::string, std::string> StringMap;
210  StringMap destdata;
211 
212  bool IsChange() const { return m_change; }
213  const std::string &GetLabel() const { return m_label; }
214  void SetLabel(const std::string &label) {
215  m_change = false;
216  m_label = label;
217  }
218 };
219 
220 struct CRecipient {
224 };
225 
226 typedef std::map<std::string, std::string> mapValue_t;
227 
228 static inline void ReadOrderPos(int64_t &nOrderPos, mapValue_t &mapValue) {
229  if (!mapValue.count("n")) {
230  // TODO: calculate elsewhere
231  nOrderPos = -1;
232  return;
233  }
234 
235  nOrderPos = atoi64(mapValue["n"].c_str());
236 }
237 
238 static inline void WriteOrderPos(const int64_t &nOrderPos,
239  mapValue_t &mapValue) {
240  if (nOrderPos == -1) {
241  return;
242  }
243  mapValue["n"] = ToString(nOrderPos);
244 }
245 
246 struct COutputEntry {
249  int vout;
250 };
251 
259 class CMerkleTx {
260 public:
261  template <typename Stream> void Unserialize(Stream &s) {
262  CTransactionRef tx;
263  BlockHash hashBlock;
264  std::vector<uint256> vMerkleBranch;
265  int nIndex = 0;
266 
267  s >> tx >> hashBlock >> vMerkleBranch >> nIndex;
268  }
269 };
270 
271 // Get the marginal bytes of spending the specified output
272 int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *pwallet,
273  bool use_max_sig = false);
274 
280 class CWalletTx {
281 private:
282  const CWallet *pwallet;
283 
288  static const BlockHash ABANDON_HASH;
289 
290 public:
317  std::vector<std::pair<std::string, std::string>> vOrderForm;
318  unsigned int fTimeReceivedIsTxTime;
320  unsigned int nTimeReceived;
330  unsigned int nTimeSmart;
336  bool fFromMe;
338  int64_t nOrderPos;
339  std::multimap<int64_t, CWalletTx *>::const_iterator m_it_wtxOrdered;
340 
341  // memory only
342  enum AmountType {
347  AMOUNTTYPE_ENUM_ELEMENTS
348  };
349  Amount GetCachableAmount(AmountType type, const isminefilter &filter,
350  bool recalculate = false) const;
351  mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
358  mutable bool m_is_cache_empty{true};
359  mutable bool fChangeCached;
360  mutable bool fInMempool;
362 
363  CWalletTx(const CWallet *pwalletIn, CTransactionRef arg)
364  : tx(std::move(arg)) {
365  Init(pwalletIn);
366  }
367 
368  void Init(const CWallet *pwalletIn) {
369  pwallet = pwalletIn;
370  mapValue.clear();
371  vOrderForm.clear();
372  fTimeReceivedIsTxTime = false;
373  nTimeReceived = 0;
374  nTimeSmart = 0;
375  fFromMe = false;
376  fChangeCached = false;
377  fInMempool = false;
378  nChangeCached = Amount::zero();
379  nOrderPos = -1;
380  m_confirm = Confirmation{};
381  }
382 
384 
395  enum Status { UNCONFIRMED, CONFIRMED, CONFLICTED, ABANDONED };
396 
404  struct Confirmation {
408  int nIndex;
409  Confirmation(Status s = UNCONFIRMED, int b = 0,
410  BlockHash h = BlockHash(), int i = 0)
411  : status(s), block_height(b), hashBlock(h), nIndex(i) {}
412  };
413 
415 
416  template <typename Stream> void Serialize(Stream &s) const {
417  mapValue_t mapValueCopy = mapValue;
418 
419  mapValueCopy["fromaccount"] = "";
420  WriteOrderPos(nOrderPos, mapValueCopy);
421  if (nTimeSmart) {
422  mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
423  }
424 
426  std::vector<char> dummy_vector1;
428  std::vector<char> dummy_vector2;
430  bool dummy_bool = false;
431  uint256 serializedHash =
432  isAbandoned() ? ABANDON_HASH : m_confirm.hashBlock;
433  int serializedIndex =
434  isAbandoned() || isConflicted() ? -1 : m_confirm.nIndex;
435  s << tx << serializedHash << dummy_vector1 << serializedIndex
436  << dummy_vector2 << mapValueCopy << vOrderForm
437  << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << dummy_bool;
438  }
439 
440  template <typename Stream> void Unserialize(Stream &s) {
441  Init(nullptr);
442 
444  std::vector<uint256> dummy_vector1;
446  std::vector<CMerkleTx> dummy_vector2;
448  bool dummy_bool;
449  int serializedIndex;
450  s >> tx >> m_confirm.hashBlock >> dummy_vector1 >> serializedIndex >>
451  dummy_vector2 >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >>
452  nTimeReceived >> fFromMe >> dummy_bool;
453 
454  /*
455  * At serialization/deserialization, an nIndex == -1 means that
456  * hashBlock refers to the earliest block in the chain we know this or
457  * any in-wallet ancestor conflicts with. If nIndex == -1 and hashBlock
458  * is ABANDON_HASH, it means transaction is abandoned. In same context,
459  * an nIndex >= 0 refers to a confirmed transaction (if hashBlock set)
460  * or unconfirmed one. Older clients interpret nIndex == -1 as
461  * unconfirmed for backward compatibility (pre-commit 9ac63d6).
462  */
463  if (serializedIndex == -1 && m_confirm.hashBlock == ABANDON_HASH) {
464  setAbandoned();
465  } else if (serializedIndex == -1) {
466  setConflicted();
467  } else if (!m_confirm.hashBlock.IsNull()) {
468  m_confirm.nIndex = serializedIndex;
469  setConfirmed();
470  }
471 
472  ReadOrderPos(nOrderPos, mapValue);
473  nTimeSmart = mapValue.count("timesmart")
474  ? (unsigned int)atoi64(mapValue["timesmart"])
475  : 0;
476 
477  mapValue.erase("fromaccount");
478  mapValue.erase("spent");
479  mapValue.erase("n");
480  mapValue.erase("timesmart");
481  }
482 
483  void SetTx(CTransactionRef arg) { tx = std::move(arg); }
484 
486  void MarkDirty() {
487  m_amounts[DEBIT].Reset();
488  m_amounts[CREDIT].Reset();
489  m_amounts[IMMATURE_CREDIT].Reset();
490  m_amounts[AVAILABLE_CREDIT].Reset();
491  fChangeCached = false;
492  m_is_cache_empty = true;
493  }
494 
495  void BindWallet(CWallet *pwalletIn) {
496  pwallet = pwalletIn;
497  MarkDirty();
498  }
499 
501  Amount GetDebit(const isminefilter &filter) const;
502  Amount GetCredit(const isminefilter &filter) const;
503  Amount GetImmatureCredit(bool fUseCache = true) const;
504  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
505  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The
506  // annotation "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid
507  // having to resolve the issue of member access into incomplete type
508  // CWallet.
509  Amount GetAvailableCredit(bool fUseCache = true,
510  const isminefilter &filter = ISMINE_SPENDABLE)
512  Amount GetImmatureWatchOnlyCredit(const bool fUseCache = true) const;
513  Amount GetChange() const;
514 
515  // Get the marginal bytes if spending the specified output from this
516  // transaction
517  int GetSpendSize(unsigned int out, bool use_max_sig = false) const {
518  return CalculateMaximumSignedInputSize(tx->vout[out], pwallet,
519  use_max_sig);
520  }
521 
522  void GetAmounts(std::list<COutputEntry> &listReceived,
523  std::list<COutputEntry> &listSent, Amount &nFee,
524  const isminefilter &filter) const;
525 
526  bool IsFromMe(const isminefilter &filter) const {
527  return GetDebit(filter) > Amount::zero();
528  }
529 
530  // True if only scriptSigs are different
531  bool IsEquivalentTo(const CWalletTx &tx) const;
532 
533  bool InMempool() const;
534  bool IsTrusted() const;
535  bool IsTrusted(std::set<TxId> &trusted_parents) const;
536 
537  int64_t GetTxTime() const;
538 
539  // Pass this transaction to node for mempool insertion and relay to peers if
540  // flag set to true
541  bool SubmitMemoryPoolAndRelay(std::string &err_string, bool relay);
542 
543  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
544  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
545  // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
546  // resolve the issue of member access into incomplete type CWallet. Note
547  // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
548  // in place.
549  std::set<TxId> GetConflicts() const NO_THREAD_SAFETY_ANALYSIS;
550 
557  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
558  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
559  // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
560  // resolve the issue of member access into incomplete type CWallet. Note
561  // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
562  // in place.
563  int GetDepthInMainChain() const NO_THREAD_SAFETY_ANALYSIS;
564  bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
565 
571  int GetBlocksToMaturity() const;
572  bool isAbandoned() const {
573  return m_confirm.status == CWalletTx::ABANDONED;
574  }
575  void setAbandoned() {
576  m_confirm.status = CWalletTx::ABANDONED;
577  m_confirm.hashBlock = BlockHash();
578  m_confirm.block_height = 0;
579  m_confirm.nIndex = 0;
580  }
581  bool isConflicted() const {
582  return m_confirm.status == CWalletTx::CONFLICTED;
583  }
585  bool isUnconfirmed() const {
586  return m_confirm.status == CWalletTx::UNCONFIRMED;
587  }
589  bool isConfirmed() const {
590  return m_confirm.status == CWalletTx::CONFIRMED;
591  }
592  void setConfirmed() { m_confirm.status = CWalletTx::CONFIRMED; }
593  TxId GetId() const { return tx->GetId(); }
594  bool IsCoinBase() const { return tx->IsCoinBase(); }
595  bool IsImmatureCoinBase() const;
596 };
597 
598 class COutput {
599 public:
600  const CWalletTx *tx;
601  int i;
602  int nDepth;
603 
609 
612 
614  bool fSolvable;
615 
622 
628  bool fSafe;
629 
630  COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn,
631  bool fSolvableIn, bool fSafeIn, bool use_max_sig_in = false) {
632  tx = txIn;
633  i = iIn;
634  nDepth = nDepthIn;
635  fSpendable = fSpendableIn;
636  fSolvable = fSolvableIn;
637  fSafe = fSafeIn;
638  nInputBytes = -1;
639  use_max_sig = use_max_sig_in;
640  // If known and signable by the given wallet, compute nInputBytes
641  // Failure will keep this value -1
642  if (fSpendable && tx) {
643  nInputBytes = tx->GetSpendSize(i, use_max_sig);
644  }
645  }
646 
647  std::string ToString() const;
648 
649  inline CInputCoin GetInputCoin() const {
650  return CInputCoin(tx->tx, i, nInputBytes);
651  }
652 };
653 
655  bool use_bnb = true;
656  size_t change_output_size = 0;
657  size_t change_spend_size = 0;
658  CFeeRate effective_fee = CFeeRate(Amount::zero());
659  size_t tx_noinputs_size = 0;
661  bool m_subtract_fee_outputs = false;
662 
663  CoinSelectionParams(bool use_bnb_, size_t change_output_size_,
664  size_t change_spend_size_, CFeeRate effective_fee_,
665  size_t tx_noinputs_size_)
666  : use_bnb(use_bnb_), change_output_size(change_output_size_),
667  change_spend_size(change_spend_size_), effective_fee(effective_fee_),
668  tx_noinputs_size(tx_noinputs_size_) {}
670 };
671 
672 // forward declarations for ScanForWalletTransactions/RescanFromTime
674 
679 class CWallet final : public WalletStorage,
681 private:
682  CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
683 
684  bool Unlock(const CKeyingMaterial &vMasterKeyIn,
685  bool accept_no_keys = false);
686 
687  std::atomic<bool> fAbortRescan{false};
688  // controlled by WalletRescanReserver
689  std::atomic<bool> fScanningWallet{false};
690  std::atomic<int64_t> m_scanning_start{0};
691  std::atomic<double> m_scanning_progress{0};
692  friend class WalletRescanReserver;
693 
696  int nWalletVersion GUARDED_BY(cs_wallet) = FEATURE_BASE;
697 
700  int nWalletMaxVersion GUARDED_BY(cs_wallet) = FEATURE_BASE;
701 
702  int64_t nNextResend = 0;
703  bool fBroadcastTransactions = false;
704  // Local time that the tip block was received. Used to schedule wallet
705  // rebroadcasts.
706  std::atomic<int64_t> m_best_block_time{0};
707 
712  typedef std::multimap<COutPoint, TxId> TxSpends;
713  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
714  void AddToSpends(const COutPoint &outpoint, const TxId &wtxid)
715  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
716  void AddToSpends(const TxId &wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
717 
733  bool AddToWalletIfInvolvingMe(const CTransactionRef &tx,
734  CWalletTx::Confirmation confirm, bool fUpdate)
735  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
736 
741  void MarkConflicted(const BlockHash &hashBlock, int conflicting_height,
742  const TxId &txid);
743 
748  void MarkInputsDirty(const CTransactionRef &tx)
749  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
750 
751  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>)
752  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
753 
760  void SyncTransaction(const CTransactionRef &tx,
761  CWalletTx::Confirmation confirm, bool update_tx = true)
762  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
763 
764  std::atomic<uint64_t> m_wallet_flags{0};
765 
766  bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address,
767  const std::string &strName,
768  const std::string &strPurpose);
769 
771  void UnsetWalletFlagWithDB(WalletBatch &batch, uint64_t flag);
772 
774  void UnsetBlankWalletFlag(WalletBatch &batch) override;
775 
778 
783 
785  std::unique_ptr<WalletDatabase> database;
786 
794  BlockHash m_last_block_processed GUARDED_BY(cs_wallet);
795 
796  /* Height of last block processed is used by wallet to know depth of
797  * transactions without relying on Chain interface beyond asynchronous
798  * updates. For safety, we initialize it to -1. Height is a pointer on
799  * node's tip and doesn't imply that the wallet has scanned sequentially all
800  * blocks up to this one.
801  */
802  int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
803 
804  bool CreateTransactionInternal(const std::vector<CRecipient> &vecSend,
805  CTransactionRef &tx, Amount &nFeeRet,
806  int &nChangePosInOut, bilingual_str &error,
807  const CCoinControl &coin_control, bool sign);
808 
809  std::map<OutputType, ScriptPubKeyMan *> m_external_spk_managers;
810  std::map<OutputType, ScriptPubKeyMan *> m_internal_spk_managers;
811 
812  // Indexed by a unique identifier produced by each ScriptPubKeyMan using
813  // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal
814  // structure
815  std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
816 
817 public:
818  /*
819  * Main wallet lock.
820  * This lock protects all the fields added by CWallet.
821  */
823 
828  WalletDatabase &GetDBHandle() { return *database; }
829  WalletDatabase &GetDatabase() override { return *database; }
830 
836  bool SelectCoins(const std::vector<COutput> &vAvailableCoins,
837  const Amount nTargetValue,
838  std::set<CInputCoin> &setCoinsRet, Amount &nValueRet,
839  const CCoinControl &coin_control,
841  bool &bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
842 
843  const WalletLocation &GetLocation() const { return m_location; }
844 
848  const std::string &GetName() const { return m_location.GetName(); }
849 
850  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
851  MasterKeyMap mapMasterKeys;
852  unsigned int nMasterKeyMaxID = 0;
853 
855  CWallet(interfaces::Chain *chain, const WalletLocation &location,
856  std::unique_ptr<WalletDatabase> _database)
857  : m_chain(chain), m_location(location), database(std::move(_database)) {
858  }
859 
861  // Should not have slots connected at this point.
862  assert(NotifyUnload.empty());
863  }
864 
865  /* Returns the chain params used by this wallet. */
866  const CChainParams &GetChainParams() const override;
867 
868  bool IsCrypted() const;
869  bool IsLocked() const override;
870  bool Lock();
871 
873  bool HaveChain() const { return m_chain ? true : false; }
874 
875  std::map<TxId, CWalletTx> mapWallet GUARDED_BY(cs_wallet);
876 
877  typedef std::multimap<int64_t, CWalletTx *> TxItems;
878  TxItems wtxOrdered;
879 
880  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
881  uint64_t nAccountingEntryNumber = 0;
882 
883  std::map<CTxDestination, CAddressBookData>
884  m_address_book GUARDED_BY(cs_wallet);
885  const CAddressBookData *
886  FindAddressBookEntry(const CTxDestination &,
887  bool allow_change = false) const
888  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
889 
890  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
891 
893  std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
894 
896  interfaces::Chain &chain() const {
897  assert(m_chain);
898  return *m_chain;
899  }
900 
901  const CWalletTx *GetWalletTx(const TxId &txid) const;
902 
905  bool CanSupportFeature(enum WalletFeature wf) const override
906  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
907  AssertLockHeld(cs_wallet);
908  return nWalletMaxVersion >= wf;
909  }
910 
914  void AvailableCoins(std::vector<COutput> &vCoins, bool fOnlySafe = true,
915  const CCoinControl *coinControl = nullptr,
916  const Amount nMinimumAmount = SATOSHI,
917  const Amount nMaximumAmount = MAX_MONEY,
918  const Amount nMinimumSumAmount = MAX_MONEY,
919  const uint64_t nMaximumCount = 0) const
920  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
921 
926  std::map<CTxDestination, std::vector<COutput>> ListCoins() const
927  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
928 
932  const CTxOut &FindNonChangeParentOutput(const CTransaction &tx,
933  int output) const
934  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
935 
942  bool SelectCoinsMinConf(const Amount nTargetValue,
943  const CoinEligibilityFilter &eligibility_filter,
944  std::vector<OutputGroup> groups,
945  std::set<CInputCoin> &setCoinsRet,
946  Amount &nValueRet,
947  const CoinSelectionParams &coin_selection_params,
948  bool &bnb_used) const;
949 
950  bool IsSpent(const COutPoint &outpoint) const
951  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
952 
953  // Whether this or any UTXO with the same CTxDestination has been spent.
954  bool IsSpentKey(const TxId &txid, unsigned int n) const
955  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
956  void SetSpentKeyState(WalletBatch &batch, const TxId &txid, unsigned int n,
957  bool used, std::set<CTxDestination> &tx_destinations)
958  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
959 
960  std::vector<OutputGroup> GroupOutputs(const std::vector<COutput> &outputs,
961  bool single_coin,
962  const size_t max_ancestors) const;
963 
964  bool IsLockedCoin(const COutPoint &outpoint) const
965  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
966  void LockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
967  void UnlockCoin(const COutPoint &output)
968  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
969  void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
970  void ListLockedCoins(std::vector<COutPoint> &vOutpts) const
971  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
972 
973  /*
974  * Rescan abort properties
975  */
976  void AbortRescan() { fAbortRescan = true; }
977  bool IsAbortingRescan() const { return fAbortRescan; }
978  bool IsScanning() const { return fScanningWallet; }
979  int64_t ScanningDuration() const {
980  return fScanningWallet ? GetTimeMillis() - m_scanning_start : 0;
981  }
982  double ScanningProgress() const {
983  return fScanningWallet ? double(m_scanning_progress) : 0;
984  }
985 
988  void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
989 
990  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
991  AssertLockHeld(cs_wallet);
992  nWalletVersion = nVersion;
993  nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion);
994  return true;
995  }
996 
1002  bool AddDestData(WalletBatch &batch, const CTxDestination &dest,
1003  const std::string &key, const std::string &value)
1004  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1006  bool EraseDestData(WalletBatch &batch, const CTxDestination &dest,
1007  const std::string &key)
1008  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1010  void LoadDestData(const CTxDestination &dest, const std::string &key,
1011  const std::string &value)
1012  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1015  bool GetDestData(const CTxDestination &dest, const std::string &key,
1016  std::string *value) const
1017  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1019  std::vector<std::string> GetDestValues(const std::string &prefix) const
1020  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1021 
1025  int64_t nRelockTime GUARDED_BY(cs_wallet){0};
1026 
1027  // Used to prevent concurrent calls to walletpassphrase RPC.
1029  bool Unlock(const SecureString &strWalletPassphrase,
1030  bool accept_no_keys = false);
1031  bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase,
1032  const SecureString &strNewWalletPassphrase);
1033  bool EncryptWallet(const SecureString &strWalletPassphrase);
1034 
1035  void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const
1036  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1037  unsigned int ComputeTimeSmart(const CWalletTx &wtx) const;
1038 
1043  int64_t IncOrderPosNext(WalletBatch *batch = nullptr)
1044  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1045  DBErrors ReorderTransactions();
1046 
1047  void MarkDirty();
1048  bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose = true);
1049  void LoadToWallet(CWalletTx &wtxIn) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1050  void transactionAddedToMempool(const CTransactionRef &tx) override;
1051  void blockConnected(const CBlock &block, int height) override;
1052  void blockDisconnected(const CBlock &block, int height) override;
1053  void updatedBlockTip() override;
1054  int64_t RescanFromTime(int64_t startTime,
1055  const WalletRescanReserver &reserver, bool update);
1056 
1057  struct ScanResult {
1058  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
1059 
1064  std::optional<int> last_scanned_height;
1065 
1071  };
1072  ScanResult ScanForWalletTransactions(const BlockHash &start_block,
1073  int start_height,
1074  std::optional<int> max_height,
1075  const WalletRescanReserver &reserver,
1076  bool fUpdate);
1077  void transactionRemovedFromMempool(const CTransactionRef &ptx) override;
1078  void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1079  void ResendWalletTransactions();
1080  struct Balance {
1082  Amount m_mine_trusted{Amount::zero()};
1084  Amount m_mine_untrusted_pending{Amount::zero()};
1086  Amount m_mine_immature{Amount::zero()};
1087  Amount m_watchonly_trusted{Amount::zero()};
1088  Amount m_watchonly_untrusted_pending{Amount::zero()};
1089  Amount m_watchonly_immature{Amount::zero()};
1090  };
1091  Balance GetBalance(int min_depth = 0, bool avoid_reuse = true) const;
1092  Amount GetAvailableBalance(const CCoinControl *coinControl = nullptr) const;
1093 
1094  OutputType TransactionChangeType(OutputType change_type,
1095  const std::vector<CRecipient> &vecSend);
1096 
1101  bool FundTransaction(CMutableTransaction &tx, Amount &nFeeRet,
1102  int &nChangePosInOut, bilingual_str &error,
1103  bool lockUnspents,
1104  const std::set<int> &setSubtractFeeFromOutputs,
1105  CCoinControl coinControl);
1106  // Fetch the inputs and sign with SIGHASH_ALL.
1107  bool SignTransaction(CMutableTransaction &tx) const
1108  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1109  // Sign the tx given the input coins and sighash.
1111  const std::map<COutPoint, Coin> &coins,
1112  SigHashType sighash,
1113  std::map<int, std::string> &input_errors) const;
1114  SigningResult SignMessage(const std::string &message, const PKHash &pkhash,
1115  std::string &str_sig) const;
1116 
1133  FillPSBT(PartiallySignedTransaction &psbtx, bool &complete,
1134  SigHashType sighash_type = SigHashType().withForkId(),
1135  bool sign = true, bool bip32derivs = true) const;
1136 
1143  bool CreateTransaction(const std::vector<CRecipient> &vecSend,
1144  CTransactionRef &tx, Amount &nFeeRet,
1145  int &nChangePosInOut, bilingual_str &error,
1146  const CCoinControl &coin_control, bool sign = true);
1147 
1158  void CommitTransaction(
1159  CTransactionRef tx, mapValue_t mapValue,
1160  std::vector<std::pair<std::string, std::string>> orderForm);
1161 
1162  bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts,
1163  bool use_max_sig = false) const {
1164  std::vector<CTxOut> v_txouts(txouts.size());
1165  std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
1166  return DummySignTx(txNew, v_txouts, use_max_sig);
1167  }
1168  bool DummySignTx(CMutableTransaction &txNew,
1169  const std::vector<CTxOut> &txouts,
1170  bool use_max_sig = false) const;
1171  bool DummySignInput(CTxIn &tx_in, const CTxOut &txout,
1172  bool use_max_sig = false) const;
1173 
1174  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1175  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1176  bool ImportPrivKeys(const std::map<CKeyID, CKey> &privkey_map,
1177  const int64_t timestamp)
1178  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1179  bool ImportPubKeys(
1180  const std::vector<CKeyID> &ordered_pubkeys,
1181  const std::map<CKeyID, CPubKey> &pubkey_map,
1182  const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> &key_origins,
1183  const bool add_keypool, const bool internal, const int64_t timestamp)
1184  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1185  bool ImportScriptPubKeys(const std::string &label,
1186  const std::set<CScript> &script_pub_keys,
1187  const bool have_solving_data,
1188  const bool apply_label, const int64_t timestamp)
1189  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1190 
1192  bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
1194  bool m_allow_fallback_fee{true};
1195  // Override with -mintxfee
1196  CFeeRate m_min_fee{DEFAULT_TRANSACTION_MINFEE_PER_KB};
1202  CFeeRate m_fallback_fee{DEFAULT_FALLBACK_FEE};
1204  Amount m_max_aps_fee{DEFAULT_MAX_AVOIDPARTIALSPEND_FEE};
1205  OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
1206  OutputType m_default_change_type{DEFAULT_CHANGE_TYPE};
1211  Amount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
1212 
1213  size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1214  bool TopUpKeyPool(unsigned int kpSize = 0);
1215 
1216  int64_t GetOldestKeyPoolTime() const;
1217 
1218  std::set<std::set<CTxDestination>> GetAddressGroupings() const
1219  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1220  std::map<CTxDestination, Amount> GetAddressBalances() const;
1221 
1222  std::set<CTxDestination> GetLabelAddresses(const std::string &label) const;
1223 
1228  void MarkDestinationsDirty(const std::set<CTxDestination> &destinations)
1229  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1230 
1231  bool GetNewDestination(const OutputType type, const std::string label,
1232  CTxDestination &dest, std::string &error);
1233  bool GetNewChangeDestination(const OutputType type, CTxDestination &dest,
1234  std::string &error);
1235 
1236  isminetype IsMine(const CTxDestination &dest) const;
1237  isminetype IsMine(const CScript &script) const;
1238  isminetype IsMine(const CTxIn &txin) const;
1243  Amount GetDebit(const CTxIn &txin, const isminefilter &filter) const;
1244  isminetype IsMine(const CTxOut &txout) const;
1245  Amount GetCredit(const CTxOut &txout, const isminefilter &filter) const;
1246  bool IsChange(const CTxOut &txout) const;
1247  bool IsChange(const CScript &script) const;
1248  Amount GetChange(const CTxOut &txout) const;
1249  bool IsMine(const CTransaction &tx) const;
1251  bool IsFromMe(const CTransaction &tx) const;
1252  Amount GetDebit(const CTransaction &tx, const isminefilter &filter) const;
1254  bool IsAllFromMe(const CTransaction &tx, const isminefilter &filter) const;
1255  Amount GetCredit(const CTransaction &tx, const isminefilter &filter) const;
1256  Amount GetChange(const CTransaction &tx) const;
1257  void chainStateFlushed(const CBlockLocator &loc) override;
1258 
1259  DBErrors LoadWallet(bool &fFirstRunRet);
1260  DBErrors ZapWalletTx(std::vector<CWalletTx> &vWtx);
1261  DBErrors ZapSelectTx(std::vector<TxId> &txIdsIn,
1262  std::vector<TxId> &txIdsOut)
1263  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1264 
1265  bool SetAddressBook(const CTxDestination &address,
1266  const std::string &strName, const std::string &purpose);
1267 
1268  bool DelAddressBook(const CTxDestination &address);
1269 
1270  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1271 
1274  void SetMinVersion(enum WalletFeature, WalletBatch *batch_in = nullptr,
1275  bool fExplicit = false) override;
1276 
1279  bool SetMaxVersion(int nVersion);
1280 
1283  int GetVersion() const {
1284  LOCK(cs_wallet);
1285  return nWalletVersion;
1286  }
1287 
1290  std::set<TxId> GetConflicts(const TxId &txid) const
1291  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1292 
1295  bool HasWalletSpend(const TxId &txid) const
1296  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1297 
1299  void Flush(bool shutdown = false);
1300 
1302  boost::signals2::signal<void()> NotifyUnload;
1303 
1308  boost::signals2::signal<void(CWallet *wallet, const CTxDestination &address,
1309  const std::string &label, bool isMine,
1310  const std::string &purpose, ChangeType status)>
1312 
1317  boost::signals2::signal<void(CWallet *wallet, const TxId &txid,
1318  ChangeType status)>
1320 
1322  boost::signals2::signal<void(const std::string &title, int nProgress)>
1324 
1326  boost::signals2::signal<void(bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1327 
1329  boost::signals2::signal<void()> NotifyCanGetAddressesChanged;
1330 
1335  boost::signals2::signal<void(CWallet *wallet)> NotifyStatusChanged;
1336 
1338  bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1340  void SetBroadcastTransactions(bool broadcast) {
1341  fBroadcastTransactions = broadcast;
1342  }
1343 
1345  bool TransactionCanBeAbandoned(const TxId &txid) const;
1346 
1351  bool AbandonTransaction(const TxId &txid);
1352 
1354  static bool Verify(const CChainParams &chainParams,
1355  interfaces::Chain &chain, const WalletLocation &location,
1356  bilingual_str &error_string,
1357  std::vector<bilingual_str> &warnings);
1358 
1363  static std::shared_ptr<CWallet>
1364  CreateWalletFromFile(const CChainParams &chainParams,
1365  interfaces::Chain &chain,
1366  const WalletLocation &location, bilingual_str &error,
1367  std::vector<bilingual_str> &warnings,
1368  uint64_t wallet_creation_flags = 0);
1369 
1375  void postInitProcess();
1376 
1377  bool BackupWallet(const std::string &strDest) const;
1378 
1379  /* Returns true if HD is enabled */
1380  bool IsHDEnabled() const;
1381 
1386  bool CanGetAddresses(bool internal = false) const;
1387 
1394  void BlockUntilSyncedToCurrentChain() const
1396 
1400  void SetWalletFlag(uint64_t flags);
1401 
1405  void UnsetWalletFlag(uint64_t flag);
1406 
1410  bool IsWalletFlagSet(uint64_t flag) const override;
1411 
1416  bool SetWalletFlags(uint64_t overwriteFlags, bool memOnly);
1417 
1419  bool IsLegacy() const;
1420 
1425  const std::string GetDisplayName() const override {
1426  std::string wallet_name =
1427  GetName().length() == 0 ? "default wallet" : GetName();
1428  return strprintf("[%s]", wallet_name);
1429  };
1430 
1435  template <typename... Params>
1436  void WalletLogPrintf(std::string fmt, Params... parameters) const {
1437  LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
1438  };
1439 
1440  template <typename... Params>
1441  void WalletLogPrintfToBeContinued(std::string fmt,
1442  Params... parameters) const {
1443  LogPrintfToBeContinued(("%s " + fmt).c_str(), GetDisplayName(),
1444  parameters...);
1445  };
1446 
1448  bool UpgradeWallet(int version, bilingual_str &error,
1449  std::vector<bilingual_str> &warnings);
1450 
1453  std::set<ScriptPubKeyMan *> GetActiveScriptPubKeyMans() const;
1454 
1456  std::set<ScriptPubKeyMan *> GetAllScriptPubKeyMans() const;
1457 
1460  ScriptPubKeyMan *GetScriptPubKeyMan(const OutputType &type,
1461  bool internal) const;
1462 
1464  ScriptPubKeyMan *GetScriptPubKeyMan(const CScript &script) const;
1466  ScriptPubKeyMan *GetScriptPubKeyMan(const uint256 &id) const;
1467 
1470  std::set<ScriptPubKeyMan *>
1471  GetScriptPubKeyMans(const CScript &script, SignatureData &sigdata) const;
1472 
1474  std::unique_ptr<SigningProvider>
1475  GetSolvingProvider(const CScript &script) const;
1476  std::unique_ptr<SigningProvider>
1477  GetSolvingProvider(const CScript &script, SignatureData &sigdata) const;
1478 
1481  LegacyScriptPubKeyMan *GetLegacyScriptPubKeyMan() const;
1482  LegacyScriptPubKeyMan *GetOrCreateLegacyScriptPubKeyMan();
1483 
1486  void SetupLegacyScriptPubKeyMan();
1487 
1488  const CKeyingMaterial &GetEncryptionKey() const override;
1489  bool HasEncryptionKeys() const override;
1490 
1492  int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1493  AssertLockHeld(cs_wallet);
1494  assert(m_last_block_processed_height >= 0);
1495  return m_last_block_processed_height;
1496  };
1497  BlockHash GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1498  AssertLockHeld(cs_wallet);
1499  assert(m_last_block_processed_height >= 0);
1500  return m_last_block_processed;
1501  }
1503  void SetLastBlockProcessed(int block_height, BlockHash block_hash)
1504  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1505  AssertLockHeld(cs_wallet);
1506  m_last_block_processed_height = block_height;
1507  m_last_block_processed = block_hash;
1508  };
1509 
1511  void ConnectScriptPubKeyManNotifiers();
1512 
1515  void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc);
1516 
1526  void SetActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal,
1527  bool memonly = false);
1528 
1530  void SetupDescriptorScriptPubKeyMans();
1531 
1535  GetDescriptorScriptPubKeyMan(const WalletDescriptor &desc) const;
1536 
1539  ScriptPubKeyMan *
1540  AddWalletDescriptor(WalletDescriptor &desc,
1541  const FlatSigningProvider &signing_provider,
1542  const std::string &label);
1543 };
1544 
1550 void MaybeResendWalletTxs();
1551 
1554 private:
1557 
1558 public:
1560  : m_wallet(w), m_could_reserve(false) {}
1561 
1562  bool reserve() {
1563  assert(!m_could_reserve);
1564  if (m_wallet.fScanningWallet.exchange(true)) {
1565  return false;
1566  }
1567  m_wallet.m_scanning_start = GetTimeMillis();
1568  m_wallet.m_scanning_progress = 0;
1569  m_could_reserve = true;
1570  return true;
1571  }
1572 
1573  bool isReserved() const {
1574  return (m_could_reserve && m_wallet.fScanningWallet);
1575  }
1576 
1578  if (m_could_reserve) {
1579  m_wallet.fScanningWallet = false;
1580  }
1581  }
1582 };
1583 
1584 // Calculate the size of the transaction assuming all signatures are max size
1585 // Use DummySignatureCreator, which inserts 71 byte signatures everywhere.
1586 // NOTE: this requires that all inputs must be in mapWallet (eg the tx should
1587 // be IsAllFromMe).
1588 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx,
1589  const CWallet *wallet,
1590  bool use_max_sig = false)
1592 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx,
1593  const CWallet *wallet,
1594  const std::vector<CTxOut> &txouts,
1595  bool use_max_sig = false);
1596 
1597 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:338
AmountType
Definition: wallet.h:342
void SetLastBlockProcessed(int block_height, BlockHash block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Set last block processed height, currently only use in unit test.
Definition: wallet.h:1503
bool fChangeCached
Definition: wallet.h:359
const CWallet * pwallet
Definition: wallet.h:282
std::atomic< bool > fScanningWallet
Definition: wallet.h:689
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:58
std::multimap< COutPoint, TxId > TxSpends
Used to keep track of spent outpoints, and detect and report conflicts (double-spends or mutated tran...
Definition: wallet.h:712
std::unique_ptr< WalletDatabase > database
Internal database handle.
Definition: wallet.h:785
int i
Definition: wallet.h:601
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:809
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:1311
void BindWallet(CWallet *pwalletIn)
Definition: wallet.h:495
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:39
static constexpr Amount zero()
Definition: amount.h:35
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:226
#define LogPrintfToBeContinued
These are aliases used to explicitly state that the message should not end with a newline character...
Definition: logging.h:204
bool fSolvable
Whether we know how to spend this output, ignoring the lack of keys.
Definition: wallet.h:614
bool isConfirmed() const
Definition: wallet.h:589
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:110
CWallet(interfaces::Chain *chain, const WalletLocation &location, std::unique_ptr< WalletDatabase > _database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:855
CTxDestination address
The destination.
Definition: wallet.h:172
Bilingual messages:
Definition: translation.h:17
Definition: block.h:62
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:59
const std::string & GetLabel() const
Definition: wallet.h:213
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:526
std::vector< uint8_t, secure_allocator< uint8_t > > CKeyingMaterial
Definition: crypter.h:63
std::optional< int > last_scanned_height
Definition: wallet.h:1064
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:1162
constexpr OutputType DEFAULT_CHANGE_TYPE
Default for -changetype.
Definition: wallet.h:126
void setAbandoned()
Definition: wallet.h:575
Amount nChangeCached
Definition: wallet.h:361
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
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(Amount::zero()), 0)
SigningResult
Definition: message.h:47
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:50
TxItems wtxOrdered
Definition: wallet.h:878
const char * prefix
Definition: rest.cpp:754
WalletCreationStatus CreateWallet(const CChainParams &params, interfaces::Chain &chain, const SecureString &passphrase, uint64_t wallet_creation_flags, const std::string &name, bilingual_str &error, std::vector< bilingual_str > &warnings, std::shared_ptr< CWallet > &result)
Definition: dummywallet.cpp:65
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:56
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:1329
Definition: amount.h:17
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:338
bool isConflicted() const
Definition: wallet.h:581
ReserveDestination(CWallet *_pwallet, OutputType _type)
Construct a ReserveDestination object.
Definition: wallet.h:179
An instance of this class represents one database.
Definition: bdb.h:97
bool IsInMainChain() const
Definition: wallet.h:564
static void ReadOrderPos(int64_t &nOrderPos, mapValue_t &mapValue)
Definition: wallet.h:228
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:174
static constexpr Amount SATOSHI
Definition: amount.h:151
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:103
static const Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:165
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:486
bool fSubtractFeeFromAmount
Definition: wallet.h:223
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
A version of CTransaction with the PSBT format.
Definition: psbt.h:335
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:850
constexpr Amount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:107
int nInputBytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: wallet.h:608
bool IsCoinBase() const
Definition: wallet.h:594
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:1063
void WalletLogPrintfToBeContinued(std::string fmt, Params... parameters) const
Definition: wallet.h:1441
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:129
int64_t ScanningDuration() const
Definition: wallet.h:979
WalletCreationStatus
Definition: wallet.h:68
CWallet & m_wallet
Definition: wallet.h:1555
bool isUnconfirmed() const
Definition: wallet.h:585
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:49
bool fSpendable
Whether we have the private keys to spend this output.
Definition: wallet.h:611
BlockHash last_failed_block
Hash of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:1070
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:1492
bool IsNull() const
Definition: uint256.h:26
std::string purpose
Definition: wallet.h:205
constexpr Amount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:95
OutputType
Definition: outputtype.h:17
bool fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node...
Definition: wallet.h:336
Coin Control Features.
Definition: coincontrol.h:19
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:14
double ScanningProgress() const
Definition: wallet.h:982
WalletDatabase & GetDatabase() override
Definition: wallet.h:829
Access to the wallet database.
Definition: walletdb.h:183
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:316
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: dummywallet.cpp:78
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:1340
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:67
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in=false)
Definition: wallet.h:630
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:1335
constexpr Amount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:110
void Unserialize(Stream &s)
Definition: wallet.h:440
CScript scriptPubKey
Definition: wallet.h:221
A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet...
Mutex m_unlock_mutex
Definition: wallet.h:1025
static const Amount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:80
int nDepth
Definition: wallet.h:602
static constexpr Amount COIN
Definition: amount.h:153
const std::string & GetName() const
Get wallet name.
Definition: walletutil.h:89
Confirmation m_confirm
Definition: wallet.h:414
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:1436
Amount nAmount
Definition: wallet.h:222
constexpr Amount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:78
An input of a transaction.
Definition: transaction.h:67
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *pwallet, bool use_max_sig=false)
Definition: wallet.cpp:1650
#define LOCK(cs)
Definition: sync.h:230
const char * name
Definition: rest.cpp:43
void SetTx(CTransactionRef arg)
Definition: wallet.h:483
static const BlockHash ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned, only used at serialization/deserializat...
Definition: wallet.h:288
bool IsChange() const
Definition: wallet.h:212
Chain notifications.
Definition: chain.h:270
bool fSafe
Whether this output is considered safe to spend.
Definition: wallet.h:628
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:777
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:102
std::map< std::string, std::string > StringMap
Definition: wallet.h:209
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: walletutil.h:67
uint8_t isminefilter
Definition: wallet.h:38
WalletDatabase & GetDBHandle()
Get database handle used by this wallet.
Definition: wallet.h:828
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:95
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:873
Status
New transactions start as UNCONFIRMED.
Definition: wallet.h:395
void setConflicted()
Definition: wallet.h:584
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:99
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:123
isminetype
IsMine() return codes.
Definition: ismine.h:18
An output of a transaction.
Definition: transaction.h:141
const WalletLocation & GetLocation() const
Definition: wallet.h:843
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:87
Descriptor with some wallet metadata.
Definition: walletutil.h:99
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: dummywallet.cpp:76
BlockHash hashBlock
Definition: wallet.h:407
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
std::string m_label
Definition: wallet.h:202
void FundTransaction(CWallet *const pwallet, CMutableTransaction &tx, Amount &fee_out, int &change_position, UniValue options, CCoinControl &coinControl)
Definition: rpcwallet.cpp:3711
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: wallet.h:339
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:318
Special output type for change outputs only.
~ReserveDestination()
Destructor.
Definition: wallet.h:187
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1553
bool HasWallets()
Definition: wallet.cpp:77
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:280
OutputType const type
Definition: wallet.h:168
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:815
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:1338
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:133
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:63
void Serialize(Stream &s) const
Definition: wallet.h:416
int flags
Definition: bitcoin-tx.cpp:529
bool fInMempool
Definition: wallet.h:360
void setConfirmed()
Definition: wallet.h:592
Amount amount
Definition: wallet.h:248
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:101
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:135
static void NotifyUnload(WalletModel *walletModel)
256-bit opaque blob.
Definition: uint256.h:120
void Init(const CWallet *pwalletIn)
Definition: wallet.h:368
void setUnconfirmed()
Definition: wallet.h:588
int64_t atoi64(const char *psz)
CWalletTx(const CWallet *pwalletIn, CTransactionRef arg)
Definition: wallet.h:363
Cachable amount subdivided into watchonly and spendable parts.
Definition: ismine.h:34
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
WalletLocation m_location
Wallet location which includes wallet name (see WalletLocation).
Definition: wallet.h:782
static void WriteOrderPos(const int64_t &nOrderPos, mapValue_t &mapValue)
Definition: wallet.h:238
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:468
static const Amount WALLET_INCREMENTAL_RELAY_FEE(5000 *SATOSHI)
minimum recommended increment for BIP 125 replacement txs
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:55
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:848
MasterKeyMap mapMasterKeys
Definition: wallet.h:851
int vout
Definition: wallet.h:249
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:105
Address book data.
Definition: wallet.h:199
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:1283
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:430
StringMap destdata
Definition: wallet.h:210
A TxId is the identifier of a transaction.
Definition: txid.h:14
CTxDestination destination
Definition: wallet.h:247
static const Amount DEFAULT_MAX_AVOIDPARTIALSPEND_FEE
maximum fee increase allowed to do partial spend avoidance, even for nodes with this feature disabled...
Definition: wallet.h:93
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:330
CInputCoin GetInputCoin() const
Definition: wallet.h:649
void Reset()
Definition: ismine.h:38
int GetSpendSize(unsigned int out, bool use_max_sig=false) const
Definition: wallet.h:517
A mutable version of CTransaction.
Definition: transaction.h:297
BlockHash GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:1497
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
void Unserialize(Stream &s)
Definition: wallet.h:261
const CWalletTx * tx
Definition: wallet.h:600
Confirmation(Status s=UNCONFIRMED, int b=0, BlockHash h=BlockHash(), int i=0)
Definition: wallet.h:409
void SetLabel(const std::string &label)
Definition: wallet.h:214
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:679
TransactionError
Definition: error.h:22
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
const std::string GetDisplayName() const override
Returns a bracketed wallet name for displaying in logs, will return [default wallet] if the wallet ha...
Definition: wallet.h:1425
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:2241
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:810
A wrapper to reserve an address from a wallet.
Definition: wallet.h:161
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:877
void AbortRescan()
Definition: wallet.h:976
Definition: wallet.h:246
#define GUARDED_BY(x)
Definition: threadsafety.h:45
RecursiveMutex cs_wallet
Definition: wallet.h:822
boost::signals2::signal< void()> NotifyUnload
Wallet is about to be unloaded.
Definition: wallet.h:1302
bool IsScanning() const
Definition: wallet.h:978
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we are allowed to upgrade (or already support) to the named feature ...
Definition: wallet.h:905
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:990
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:1323
static std::vector< COutput > vCoins
The WalletLocation class provides wallet information.
Definition: walletutil.h:80
std::atomic< int64_t > m_scanning_start
Definition: wallet.h:690
unsigned int nTimeReceived
time received by this node
Definition: wallet.h:320
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:211
bool isAbandoned() const
Definition: wallet.h:572
bool isReserved() const
Definition: wallet.h:1573
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
Definition: wallet.h:404
std::atomic< double > m_scanning_progress
Definition: wallet.h:691
ChangeType
General change type (added, updated, removed).
Definition: ui_change_type.h:9
AssertLockHeld(g_cs_orphans)
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:70
std::shared_ptr< CWallet > LoadWallet(const CChainParams &chainParams, interfaces::Chain &chain, const WalletLocation &location, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:154
boost::signals2::signal< void(CWallet *wallet, const TxId &txid, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:1319
static constexpr size_t DUMMY_P2PKH_INPUT_SIZE
Pre-calculated constants for input size estimation.
Definition: wallet.h:112
constexpr Amount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:105
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:1326
TxId GetId() const
Definition: wallet.h:593
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:663
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:164
WalletRescanReserver(CWallet &w)
Definition: wallet.h:1559
static const Amount DEFAULT_TRANSACTION_MINFEE_PER_KB
-mintxfee default
Definition: wallet.h:82
CTransactionRef tx
Definition: wallet.h:383
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:87
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig=false) EXCLUSIVE_LOCKS_REQUIRED(wallet -> cs_wallet)
Definition: wallet.cpp:1623
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:53
Legacy class used for deserializing vtxPrev for backwards compatibility.
Definition: wallet.h:259
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:128
Signature hash type wrapper class.
Definition: sighashtype.h:37
~CWallet()
Definition: wallet.h:860
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:317
bool IsAbortingRescan() const
Definition: wallet.h:977