29typedef std::vector<unsigned char>
valtype;
41enum class IsMineSigVersion
53enum class IsMineResult
68 for (
const valtype& pubkey : pubkeys) {
86 IsMineResult
ret = IsMineResult::NO;
102 return IsMineResult::INVALID;
105 ret = std::max(
ret, IsMineResult::SPENDABLE);
110 if (
sigversion == IsMineSigVersion::WITNESS_V0) {
112 return IsMineResult::INVALID;
128 return IsMineResult::INVALID;
132 ret = std::max(
ret, IsMineResult::SPENDABLE);
139 return IsMineResult::INVALID;
150 if (
sigversion == IsMineSigVersion::WITNESS_V0) {
152 return IsMineResult::INVALID;
179 for (
size_t i = 0; i < keys.size(); i++) {
180 if (keys[i].size() != 33) {
181 return IsMineResult::INVALID;
186 ret = std::max(
ret, IsMineResult::SPENDABLE);
192 if (
ret == IsMineResult::NO &&
keystore.HaveWatchOnly(scriptPubKey)) {
193 ret = std::max(
ret, IsMineResult::WATCH_ONLY);
203 case IsMineResult::INVALID:
204 case IsMineResult::NO:
206 case IsMineResult::WATCH_ONLY:
207 case IsMineResult::SPENDABLE:
243 LogWarning(
"The wallet is probably corrupted: Some keys decrypt but not all.");
244 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
255 return std::make_unique<LegacySigningProvider>(*
this);
261 if (
ismine == IsMineResult::SPENDABLE ||
ismine == IsMineResult::WATCH_ONLY) {
352 std::vector<std::vector<unsigned char>>
solutions;
421 if (
meta.has_key_origin) {
433 WatchKeyMap::const_iterator it =
mapWatchKeys.find(address);
475 for (
const auto& [
_, key] :
mapKeys) {
512 std::unordered_set<CScript, SaltedSipHasher>
spks;
525 std::unordered_set<CScript, SaltedSipHasher>
spks;
559 if (
meta.hdKeypath ==
"s" ||
meta.hdKeypath ==
"m") {
573 LogWarning(
"Error generating descriptors for migration, cannot initialize db transaction");
588 creation_time = it->second.nCreateTime;
622 std::vector<CHDChain>
chains;
631 for (
int i = 0; i < 2; ++i) {
646 std::string
desc_str =
"combo(" +
xpub +
"/0h/" + ToString(i) +
"h/*h)";
680 for (
auto it =
spks.begin(); it !=
spks.end();) {
687 creation_time =
mit->second.nCreateTime;
696 std::string
desc_str = desc->ToString();
708 std::vector<CScript> scripts;
723 out.watch_descs.emplace_back(desc->ToString(), creation_time);
727 desc->Expand(0, provider,
desc_spks, provider);
768 if (!
script.IsPayToScriptHash() && !
script.IsPayToWitnessScriptHash()) {
783 creation_time = it->second.nCreateTime;
788 if (!desc->IsSolvable()) {
797 std::string
desc_str = desc->ToString();
806 out.solvable_descs.emplace_back(desc->ToString(), creation_time);
811 LogWarning(
"Error generating descriptors for migration, cannot commit db transaction");
836 throw std::runtime_error(std::string(
__func__) +
": Types are inconsistent. Stored type does not match type of newly generated address");
846 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
850 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
855 return util::Error{
_(
"Error: Cannot extract destination from the generated scriptpubkey")};
891 LogWarning(
"The wallet is probably corrupted: Some keys decrypt but not all.");
892 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
955 keys[pubkey.
GetID()] = key;
976 const std::vector<unsigned char>&
crypted_secret = it->second.second;
979 return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
995 if (!batch.
TxnBegin())
return false;
1051 throw std::runtime_error(std::string(
__func__) +
": writing cache items failed");
1069 std::vector<WalletDestination> result;
1073 WalletLogPrintf(
"%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n",
__func__, index);
1074 auto out_keys = std::make_unique<FlatSigningProvider>();
1078 throw std::runtime_error(std::string(
__func__) +
": Unable to expand descriptor from cache");
1082 result.push_back({dest, std::nullopt});
1099 throw std::runtime_error(std::string(
__func__) +
": writing descriptor private key failed");
1122 return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1149 throw std::runtime_error(std::string(
__func__) +
": writing descriptor master private key failed");
1152 throw std::runtime_error(std::string(
__func__) +
": writing descriptor failed");
1229 if (!out->HaveKey(pubkey.
GetID())) {
1239 std::unique_ptr<FlatSigningProvider>
out_keys = std::make_unique<FlatSigningProvider>();
1279 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1314 for (
unsigned int i = 0; i <
psbtx.tx->vin.size(); ++i) {
1328 return PSBTError::MISSING_INPUTS;
1336 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1342 std::vector<CPubKey> pubkeys;
1347 pubkeys.push_back(pk);
1351 std::vector<std::vector<unsigned char>>
sols;
1353 sols[0].insert(
sols[0].begin(), 0x02);
1354 pubkeys.emplace_back(
sols[0]);
1356 pubkeys.emplace_back(
sols[0]);
1362 for (
unsigned char prefix : {0x02, 0x03}) {
1363 unsigned char b[33] = {
prefix};
1364 std::copy(pubkey.
begin(), pubkey.
end(), b + 1);
1371 for (
const auto& pubkey : pubkeys) {
1374 keys->Merge(std::move(*
pk_keys));
1380 if (
res != PSBTError::OK &&
res != PSBTError::INCOMPLETE) {
1394 for (
unsigned int i = 0; i <
psbtx.tx->vout.size(); ++i) {
1413 std::unique_ptr<CKeyMetadata>
meta = std::make_unique<CKeyMetadata>();
1415 meta->has_key_origin =
true;
1438 throw std::runtime_error(
"Error: Unable to expand wallet descriptor from cache");
1492 throw std::runtime_error(std::string(
__func__) +
": writing descriptor failed");
1559 throw std::runtime_error(
"Unable to expand descriptor");
1565 throw std::runtime_error(std::string(
__func__) +
": writing cache items failed");
1590 error =
"can only update matching descriptor";
1602 error =
strprintf(
"new range must include current range = [%d,%d]",
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
CKeyID ToKeyID(const PKHash &key_hash)
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
std::string FormatHDKeypath(const std::vector< uint32_t > &path, bool apostrophe)
#define CHECK_NONFATAL(condition)
Identity function.
#define STR_INTERNAL_BUG(msg)
#define Assume(val)
Assume is the identity function.
An encapsulated private key.
const std::byte * begin() const
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
CPubKey GetPubKey() const
Compute the public key from a private key.
const std::byte * end() const
A reference to a CKey: the Hash160 of its serialized public key.
An encapsulated public key.
bool IsCompressed() const
Check whether this is a compressed public key.
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
uint256 GetHash() const
Get the 256-bit hash of this public key.
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
Serialized script, used inside transaction inputs and outputs.
A reference to a CScript: the Hash160 of its serialization.
An input of a transaction.
Cache for single descriptor's derived extended pubkeys.
DescriptorCache MergeAndDiff(const DescriptorCache &other)
Combine another DescriptorCache into this one.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
virtual bool GetKey(const CKeyID &address, CKey &keyOut) const override
virtual bool AddCScript(const CScript &redeemScript)
void ImplicitlyLearnRelatedKeyScripts(const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
RecursiveMutex cs_KeyStore
virtual bool HaveKey(const CKeyID &address) const override
const unsigned char * end() const
const unsigned char * begin() const
constexpr bool IsNull() const
static const int VERSION_HD_CHAIN_SPLIT
CKeyID seed_id
seed hash160
bool IsMine(const CScript &script) const override
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool GetDescriptorString(std::string &out, bool priv) const
void SetCache(const DescriptorCache &cache)
std::map< int32_t, FlatSigningProvider > m_map_signing_providers
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
void UpgradeDescriptorCache()
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors) const override
Creates new signatures and adds them to the transaction.
std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
std::optional< common::PSBTError > FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, std::optional< int > sighash_type=std::nullopt, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr, bool finalize=true) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
std::optional< CKey > GetKey(const CKeyID &keyid) const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
Retrieve the particular key if it is available. Returns nullopt if the key is not in the wallet,...
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< unsigned char > &crypted_key)
util::Result< CTxDestination > GetReservedDestination(OutputType type, bool internal, int64_t &index) override
bool SetupDescriptorGeneration(WalletBatch &batch, const CExtKey &master_key, OutputType addr_type, bool internal)
Setup descriptors based on the given CExtkey.
bool TopUp(unsigned int size=0) override
Fills internal address pool.
bool m_decryption_thoroughly_checked
keeps track of whether Unlock has run a thorough check before
std::map< CKeyID, CKey > KeyMap
unsigned int GetKeyPoolSize() const override
int64_t GetTimeFirstKey() const override
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
bool HaveCryptedKeys() const override
int32_t GetEndRange() const
bool CheckDecryptionKey(const CKeyingMaterial &master_key) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
bool CanGetAddresses(bool internal=false) const override
bool CanUpdateToWalletDescriptor(const WalletDescriptor &descriptor, std::string &error)
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
bool HavePrivateKeys() const override
bool AddKey(const CKeyID &key_id, const CKey &key)
util::Result< void > UpdateWalletDescriptor(WalletDescriptor &descriptor)
bool TopUpWithDB(WalletBatch &batch, unsigned int size=0)
Same as 'TopUp' but designed for use within a batch transaction context.
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
std::vector< WalletDestination > MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used Affects all keys up to and including the one determined by provid...
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool HasWalletDescriptor(const WalletDescriptor &desc) const
int32_t m_max_cached_index
RecursiveMutex cs_desc_man
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
util::Result< CTxDestination > GetNewDestination(OutputType type) override
bool IsHDEnabled() const override
std::map< uint256, MuSig2SecNonce > m_musig2_secnonces
Map of a session id to MuSig2 secnonce.
bool HasPrivKey(const CKeyID &keyid) const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
uint256 GetID() const override
bool DeleteRecordsWithDB(WalletBatch &batch)
Delete all the records of this LegacyScriptPubKeyMan from disk.
std::optional< MigrationData > MigrateToDescriptor()
Get the DescriptorScriptPubKeyMans (with private keys) that have the same scriptPubKeys as this Legac...
virtual bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
std::unordered_set< CScript, SaltedSipHasher > GetCandidateScriptPubKeys() const
virtual void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, bool checksum_valid)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
void AddInactiveHDChain(const CHDChain &chain)
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
std::unordered_set< CScript, SaltedSipHasher > GetNotMineScriptPubKeys() const
Retrieves scripts that were imported by bugs into the legacy spkm and are simply invalid,...
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
bool AddWatchOnlyInMem(const CScript &dest)
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
bool CheckDecryptionKey(const CKeyingMaterial &master_key) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
bool GetKey(const CKeyID &address, CKey &keyOut) const override
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
bool IsMine(const CScript &script) const override
virtual void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
std::unordered_map< CKeyID, CHDChain, SaltedSipHasher > m_inactive_hd_chains
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool HaveKey(const CKeyID &address) const override
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
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.
WalletStorage & m_storage
boost::signals2::signal< void(const ScriptPubKeyMan *spkm, int64_t new_birth_time) NotifyFirstKeyTimeChanged)
Birth time changed.
Access to the wallet database.
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
bool TxnBegin()
Begin a new transaction.
bool TxnCommit()
Commit current transaction.
bool EraseRecords(const std::unordered_set< std::string > &types)
Delete records of the given types.
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Descriptor with some wallet metadata.
std::shared_ptr< Descriptor > descriptor
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual void TopUpCallback(const std::set< CScript > &, ScriptPubKeyMan *)=0
Callback function for after TopUp completes containing any scripts that were added by a SPKMan.
virtual std::string LogName() const =0
virtual WalletDatabase & GetDatabase() const =0
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
virtual bool IsLocked() const =0
virtual bool HasEncryptionKeys() const =0
virtual bool WithEncryptionKey(std::function< bool(const CKeyingMaterial &)> cb) const =0
Pass the encryption key to cb().
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
uint160 RIPEMD160(std::span< const unsigned char > data)
Compute the 160-bit RIPEMD-160 hash of an array.
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
@ WITNESS_V0
Witness v0 (P2WPKH and P2WSH); see BIP 141.
std::string EncodeDestination(const CTxDestination &dest)
std::string EncodeExtPubKey(const CExtPubKey &key)
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)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
const std::unordered_set< std::string > LEGACY_TYPES
std::vector< unsigned char > valtype
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
bool DecryptKey(const CKeyingMaterial &master_key, const std::span< const unsigned char > crypted_secret, const CPubKey &pub_key, CKey &key)
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
bool EncryptSecret(const CKeyingMaterial &vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256 &nIV, std::vector< unsigned char > &vchCiphertext)
@ WALLET_FLAG_LAST_HARDENED_XPUB_CACHED
WalletDescriptor GenerateWalletDescriptor(const CExtPubKey &master_key, const OutputType &addr_type, bool internal)
is a home for public enum and struct type definitions that are used internally by node code,...
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
PSBTError SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, std::optional< int > sighash, SignatureData *out_sigdata, bool finalize)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
const SigningProvider & DUMMY_SIGNING_PROVIDER
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
@ PRIVATE_KEY_NOT_AVAILABLE
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
@ ANCHOR
anyone can spend script
@ NULL_DATA
unspendable OP_RETURN script that carries data
unsigned char * UCharCast(char *c)
CExtPubKey Neuter() const
void SetSeed(std::span< const std::byte > seed)
A mutable version of CTransaction.
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > origins
std::map< CKeyID, CKey > keys
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
std::vector< uint32_t > path
A version of CTransaction with the PSBT format.
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
struct containing information needed for migrating legacy wallets to descriptor wallets
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define AssertLockHeld(cs)
consteval auto _(util::TranslatedLiteral str)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.