6 #ifndef BITCOIN_WALLET_WALLET_H 7 #define BITCOIN_WALLET_WALLET_H 30 #include <util/time.h> 50 #include <unordered_map> 54 #include <boost/signals2/signal.hpp> 81 using
LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
92 bool AddWallet(WalletContext& context,
const std::shared_ptr<CWallet>&
wallet);
93 bool RemoveWallet(WalletContext& context,
const std::shared_ptr<CWallet>&
wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
94 bool RemoveWallet(WalletContext& context,
const std::shared_ptr<CWallet>&
wallet, std::optional<bool> load_on_start);
95 std::vector<std::shared_ptr<CWallet>>
GetWallets(WalletContext& context);
97 std::shared_ptr<CWallet>
GetWallet(WalletContext& context,
const std::string&
name);
98 std::shared_ptr<CWallet>
LoadWallet(WalletContext& context,
const std::string&
name, std::optional<bool> load_on_start,
const DatabaseOptions& options,
DatabaseStatus& status,
bilingual_str& error, std::vector<bilingual_str>& warnings);
99 std::shared_ptr<CWallet>
CreateWallet(WalletContext& context,
const std::string&
name, std::optional<bool> load_on_start, DatabaseOptions& options,
DatabaseStatus& status,
bilingual_str& error, std::vector<bilingual_str>& warnings);
100 std::shared_ptr<CWallet>
RestoreWallet(WalletContext& context,
const fs::path& backup_file,
const std::string& wallet_name, std::optional<bool> load_on_start,
DatabaseStatus& status,
bilingual_str& error, std::vector<bilingual_str>& warnings,
bool load_after_restore =
true,
bool allow_unnamed =
false);
210 bool fInternal{
false};
230 void ReturnDestination();
232 void KeepDestination();
263 bool previously_spent{
false};
272 std::map<std::string, std::string> receive_requests{};
275 bool IsChange()
const {
return !label.has_value(); }
276 std::string
GetLabel()
const {
return label ? *label : std::string{}; }
316 std::atomic<bool> fAbortRescan{
false};
317 std::atomic<bool> fScanningWallet{
false};
318 std::atomic<bool> m_scanning_with_passphrase{
false};
319 std::atomic<SteadyClock::time_point> m_scanning_start{SteadyClock::time_point{}};
320 std::atomic<double> m_scanning_progress{0};
327 bool fBroadcastTransactions =
false;
329 std::atomic<int64_t> m_best_block_time {0};
333 std::atomic<int64_t> m_birth_time{std::numeric_limits<int64_t>::max()};
340 typedef std::unordered_multimap<COutPoint, Txid, SaltedOutpointHasher>
TxSpends;
364 void MarkConflicted(
const uint256& hashBlock,
int conflicting_height,
const Txid& hashTx);
366 enum class TxUpdate { UNCHANGED, CHANGED, NOTIFY_CHANGED };
382 std::atomic<uint64_t> m_wallet_flags{0};
384 bool SetAddressBookWithDB(
WalletBatch& batch,
const CTxDestination& address,
const std::string& strName,
const std::optional<AddressPurpose>& strPurpose);
387 void UnsetWalletFlagWithDB(
WalletBatch& batch, uint64_t flag);
390 void UnsetBlankWalletFlag(
WalletBatch& batch)
override;
415 int m_last_block_processed_height
GUARDED_BY(cs_wallet) = -1;
426 void AddScriptPubKeyMan(
const uint256&
id, std::unique_ptr<ScriptPubKeyMan> spkm_man);
438 std::unordered_map<COutPoint, WalletTXO, SaltedOutpointHasher> m_txos
GUARDED_BY(cs_wallet);
464 assert(static_cast<bool>(m_database));
470 const std::string&
GetName()
const {
return m_name; }
474 unsigned int nMasterKeyMaxID = 0;
480 m_database(
std::move(database))
490 bool IsLocked()
const override;
494 bool HaveChain()
const {
return m_chain ? true :
false; }
498 std::unordered_map<Txid, CWalletTx, SaltedTxidHasher> mapWallet
GUARDED_BY(cs_wallet);
500 typedef std::multimap<int64_t, CWalletTx*>
TxItems;
503 int64_t nOrderPosNext
GUARDED_BY(cs_wallet) = 0;
505 std::map<CTxDestination, CAddressBookData> m_address_book
GUARDED_BY(cs_wallet);
576 void AbortRescan() { fAbortRescan =
true; }
580 SteadyClock::duration
ScanningDuration()
const {
return fScanningWallet ? SteadyClock::now() - m_scanning_start.load() : SteadyClock::duration{}; }
581 double ScanningProgress()
const {
return fScanningWallet ? (double) m_scanning_progress : 0; }
595 Mutex m_unlock_mutex;
600 bool ChangeWalletPassphrase(
const SecureString& strOldWalletPassphrase,
const SecureString& strNewWalletPassphrase);
601 bool EncryptWallet(
const SecureString& strWalletPassphrase);
603 unsigned int ComputeTimeSmart(
const CWalletTx& wtx,
bool rescanning_old_block)
const;
629 void blockConnected(const
kernel::ChainstateRole& role, const
interfaces::BlockInfo& block) override;
630 void blockDisconnected(const
interfaces::BlockInfo& block) override;
631 void updatedBlockTip() override;
649 ScanResult ScanForWalletTransactions(
const uint256& start_block,
int start_height, std::optional<int> max_height,
const WalletRescanReserver& reserver,
bool fUpdate,
bool save_progress);
654 bool ShouldResend()
const;
657 OutputType TransactionChangeType(
const std::optional<OutputType>& change_type,
const std::vector<CRecipient>& vecSend)
const;
663 SigningResult SignMessage(
const std::string& message,
const PKHash& pkhash, std::string& str_sig)
const;
682 std::optional<int> sighash_type = std::nullopt,
684 bool bip32derivs =
true,
685 size_t* n_signed =
nullptr,
686 bool finalize =
true)
const;
704 void MaybeUpdateBirthTime(int64_t time);
711 bool m_allow_fallback_fee{
true};
739 std::optional<OutputType> m_default_change_type{};
750 bool TopUpKeyPool(
unsigned int kpSize = 0);
755 std::optional<std::string> m_op_label{std::nullopt};
757 bool ignore_change{
true};
763 std::vector<CTxDestination> ListAddrBookAddresses(
const std::optional<AddrBookFilter>& filter)
const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
768 std::set<std::string> ListAddrBookLabels(std::optional<AddressPurpose> purpose)
const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
774 using ListAddrBookFunc = std::function<void(const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose> purpose)>;
803 bool SetAddressBook(
const CTxDestination& address,
const std::string& strName,
const std::optional<AddressPurpose>& purpose);
834 const
std::
string& label,
bool isMine,
857 bool GetBroadcastTransactions()
const {
return fBroadcastTransactions; }
862 bool TransactionCanBeAbandoned(
const Txid& hashTx)
const;
865 bool AbandonTransaction(
const Txid& hashTx);
869 bool MarkReplaced(
const Txid& originalHash,
const Txid& newHash);
874 static std::shared_ptr<CWallet> CreateNew(
WalletContext& context,
const std::string&
name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags,
bilingual_str& error, std::vector<bilingual_str>& warnings);
877 static std::shared_ptr<CWallet> LoadExisting(
WalletContext& context,
const std::string&
name, std::unique_ptr<WalletDatabase> database,
bilingual_str& error, std::vector<bilingual_str>& warnings);
883 void postInitProcess();
885 bool BackupWallet(
const std::string& strDest)
const;
888 bool IsHDEnabled()
const;
891 bool CanGetAddresses(
bool internal =
false)
const;
905 void SetWalletFlag(uint64_t
flags);
908 void UnsetWalletFlag(uint64_t flag);
911 bool IsWalletFlagSet(uint64_t flag) const override;
916 void InitWalletFlags(uint64_t
flags);
920 uint64_t GetWalletFlags() const;
923 std::
string LogName()
const override 925 std::string
name{GetName()};
926 return name.empty() ?
"default wallet" :
name;
932 std::string
name{GetName()};
933 return name.empty() ?
_(
"default wallet") :
name;
937 template <
typename...
Params>
946 WalletLogPrintf(
"setKeyPool.size() = %u\n", GetKeyPoolSize());
947 WalletLogPrintf(
"mapWallet.size() = %u\n", mapWallet.size());
948 WalletLogPrintf(
"m_address_book.size() = %u\n", m_address_book.size());
952 std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans()
const;
956 std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans()
const;
962 std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(
const CScript&
script)
const;
967 std::unique_ptr<SigningProvider> GetSolvingProvider(
const CScript&
script)
const;
971 std::vector<WalletDescriptor> GetWalletDescriptors(
const CScript&
script)
const;
978 void SetupLegacyScriptPubKeyMan();
980 bool WithEncryptionKey(std::function<
bool (
const CKeyingMaterial&)> cb)
const override;
982 bool HasEncryptionKeys()
const override;
983 bool HaveCryptedKeys()
const;
989 assert(m_last_block_processed_height >= 0);
990 return m_last_block_processed_height;
995 assert(m_last_block_processed_height >= 0);
996 return m_last_block_processed;
1004 void ConnectScriptPubKeyManNotifiers();
1062 bool CanGrindR() const;
1077 void DisconnectChainNotifications();
1090 using Clock = std::chrono::steady_clock;
1091 using NowFn = std::function<Clock::time_point()>;
1093 bool m_could_reserve{
false};
1100 assert(!m_could_reserve);
1101 if (
m_wallet.fScanningWallet.exchange(
true)) {
1104 m_wallet.m_scanning_with_passphrase.exchange(with_passphrase);
1105 m_wallet.m_scanning_start = SteadyClock::now();
1107 m_could_reserve =
true;
1113 return (m_could_reserve &&
m_wallet.fScanningWallet);
1116 Clock::time_point
now()
const {
return m_now ? m_now() : Clock::now(); };
1122 if (m_could_reserve) {
1124 m_wallet.m_scanning_with_passphrase =
false;
1149 #endif // BITCOIN_WALLET_WALLET_H std::shared_ptr< const CTransaction > CTransactionRef
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
static void NotifyTransactionChanged(WalletModel *walletmodel, const Txid &hash, ChangeType status)
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
TxBroadcast
How to broadcast a local transaction.
std::unordered_multimap< COutPoint, Txid, SaltedOutpointHasher > TxSpends
Used to keep track of spent outpoints, and detect and report conflicts (double-spends or mutated tran...
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.
std::chrono::time_point< NodeClock > time_point
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
static const std::map< std::string, WalletFlags > STRING_TO_WALLET_FLAG
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Never set in current code may be present in older wallet databases.
std::optional< int > last_scanned_height
std::optional< AddressPurpose > purpose
Address purpose which was originally recorded for payment protocol support but now serves as a cached...
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey'ed, it will be returned to the keypool...
DBErrors
Overview of wallet database classes:
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
std::map< std::string, std::string > mapValue_t
std::string GetLabel() const
std::string m_notify_tx_changed_script
Notify external script when a wallet transaction comes in or is updated (handled by -walletnotify) ...
std::optional< AddressPurpose > PurposeFromString(std::string_view s)
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
static void NotifyAddressBookChanged(WalletModel *walletmodel, const CTxDestination &address, const std::string &label, bool isMine, wallet::AddressPurpose purpose, ChangeType status)
std::shared_ptr< CWallet > LoadWallet(WalletContext &context, const std::string &name, std::optional< bool > load_on_start, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
struct containing information needed for migrating legacy wallets to descriptor wallets ...
std::shared_ptr< CWallet > m_wallet
Result CommitTransaction(CWallet &wallet, const Txid &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, Txid &bumped_txid)
Commit the bumpfee transaction.
WalletRescanReserver(CWallet &w)
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
MasterKeyMap mapMasterKeys
WalletDatabase & GetDatabase() const override
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
std::string PurposeToString(AddressPurpose p)
const CWallet *const pwallet
The wallet to reserve from.
CTxDestination address
The destination.
RecursiveMutex cs_wallet
Main wallet lock.
void LogStats() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
std::string DisplayName() const
Return wallet name for display, like LogName() but translates "default wallet" string.
bool RemoveWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Remove wallet name from persistent configuration so it will not be loaded on startup.
std::variant< TxStateConfirmed, TxStateInMempool, TxStateInactive > SyncTxState
Subset of states transaction sync logic is implemented to handle.
static const bool DEFAULT_DISABLE_WALLET
RAII object to check and reserve a wallet rescan.
std::multimap< int64_t, CWalletTx * > TxItems
A version of CTransaction with the PSBT format.
bool reserve(bool with_passphrase=false)
Access to the wallet database.
RecursiveMutex m_relock_mutex
double ScanningProgress() const
std::function< void(const CTxDestination &dest, const std::string &label, bool is_change, const std::optional< AddressPurpose > purpose)> ListAddrBookFunc
Walk-through the address book entries.
consteval auto _(util::TranslatedLiteral str)
std::function< Clock::time_point()> NowFn
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
static constexpr uint64_t MUTABLE_WALLET_FLAGS
static const bool DEFAULT_WALLET_RBF
-walletrbf default
void MaybeResendWalletTxs(WalletContext &context)
Called periodically by the schedule thread.
static const CAmount DEFAULT_MAX_AVOIDPARTIALSPEND_FEE
maximum fee increase allowed to do partial spend avoidance, even for nodes with this feature disabled...
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
int64_t CAmount
Amount in satoshis (Can be negative)
static DBErrors LoadWalletFlags(CWallet *pwallet, DatabaseBatch &batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
A transaction with a bunch of additional info that only the owner cares about.
interfaces::Chain * m_chain
Interface for accessing chain state.
std::function< TxUpdate(CWalletTx &wtx)> TryUpdatingStateFn
CWallet(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
AddressPurpose
Address purpose field that has been been stored with wallet sending and receiving addresses since BIP...
Indicates that the wallet needs an external signer.
static void NotifyCanGetAddressesChanged(WalletModel *walletmodel)
bool fSubtractFeeFromAmount
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
std::shared_ptr< CWallet > wallet
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
std::chrono::steady_clock Clock
An input of a transaction.
static constexpr uint64_t KNOWN_WALLET_FLAGS
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
static const std::map< WalletFlags, std::string > WALLET_FLAG_TO_STRING
void Unlock(Lock &lock, Callback &&callback)
std::optional< std::string > label
Address label which is always nullopt for change addresses.
void WalletLogPrintf(util::ConstevalFormatString< sizeof...(Params)> wallet_fmt, const Params &... params) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
An encapsulated public key.
std::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
static const CAmount DEFAULT_DISCARD_FEE
-discardfee default
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Indicate that this wallet supports DescriptorScriptPubKeyMan.
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
An output of a transaction.
static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress, bool resume_possible)
std::map< unsigned int, CMasterKey > MasterKeyMap
std::string m_name
Wallet name: relative directory name or "" for default wallet.
An outpoint - a combination of a transaction hash and an index n into its vout.
const std::unordered_map< COutPoint, WalletTXO, SaltedOutpointHasher > & GetTXOs() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
is a home for public enum and struct type definitions that are used by internally by wallet code...
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
util::Result< MigrationResult > MigrateLegacyToDescriptor(const std::string &wallet_name, const SecureString &passphrase, WalletContext &context)
Do all steps to migrate a legacy wallet to a descriptor wallet.
bool AddWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Add wallet name to persistent configuration so it will be loaded on startup.
std::shared_ptr< CWallet > solvables_wallet
Descriptor with some wallet metadata.
static const bool DEFAULT_WALLETBROADCAST
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
std::unordered_map< CScript, std::vector< ScriptPubKeyMan * >, SaltedSipHasher > m_cached_spks
Cache of descriptor ScriptPubKeys used for IsMine. Maps ScriptPubKey to set of spkms.
std::shared_ptr< CWallet > GetWallet(WalletContext &context, const std::string &name)
static int sign(const secp256k1_context *ctx, struct signer_secrets *signer_secrets, struct signer *signer, const secp256k1_musig_keyagg_cache *cache, const unsigned char *msg32, unsigned char *sig64)
static void NotifyUnload(WalletModel *walletModel)
bool IsChange() const
Accessor methods.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
An interface to be implemented by keystores that support signing.
#define LOCKS_EXCLUDED(...)
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
const CChainParams & Params()
Return the currently selected parameters.
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Serialized script, used inside transaction inputs and outputs.
std::shared_ptr< CWallet > watchonly_wallet
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
int64_t GetBirthTime() const
bool IsAbortingRescan() const
A reference to a CKey: the Hash160 of its serialized public key.
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
WalletContext struct containing references to state shared between CWallet instances, like the reference to the chain interface, and the list of opened wallets.
A wrapper to reserve an address from a wallet.
bool HaveChain() const
Interface to assert chain access.
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac...
void SetLabel(std::string name)
bool IsScanningWithPassphrase() const
SteadyClock::duration ScanningDuration() const
A mutable version of CTransaction.
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
void SetNextResend()
Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average...
std::unique_ptr< WalletDatabase > m_database
Internal database handle.
An encapsulated private key.
The basic transaction that is broadcasted on the network and contained in blocks. ...
static const bool DEFAULT_WALLETCROSSCHAIN
constexpr CAmount HIGH_APS_FEE
discourage APS fee higher than this amount
static const CAmount DEFAULT_CONSOLIDATE_FEERATE
-consolidatefeerate default
std::shared_ptr< CWallet > CreateWallet(WalletContext &context, const std::string &name, std::optional< bool > load_on_start, DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
ChangeType
General change type (added, updated, removed).
is a home for public enum and struct type definitions that are used internally by node code...
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
std::shared_ptr< CWallet > GetDefaultWallet(WalletContext &context, size_t &count)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
std::shared_ptr< CWallet > RestoreWallet(WalletContext &context, const fs::path &backup_file, const std::string &wallet_name, std::optional< bool > load_on_start, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings, bool load_after_restore, bool allow_unnamed)
static std::set< std::string > g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex)
An instance of this class represents one database.
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Clock::time_point now() const
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
static constexpr CAmount COIN
The amount of satoshis in one BTC.