PageRenderTime 318ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/src/wallet/scriptpubkeyman.cpp

https://github.com/bitcoin/bitcoin
C++ | 2363 lines | 1903 code | 283 blank | 177 comment | 404 complexity | 84cddb1f7e11276cd2c4dccef12359ca MD5 | raw file
  1. // Copyright (c) 2019-2021 The Bitcoin Core developers
  2. // Distributed under the MIT software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #include <key_io.h>
  5. #include <logging.h>
  6. #include <outputtype.h>
  7. #include <script/descriptor.h>
  8. #include <script/sign.h>
  9. #include <util/bip32.h>
  10. #include <util/strencodings.h>
  11. #include <util/string.h>
  12. #include <util/system.h>
  13. #include <util/time.h>
  14. #include <util/translation.h>
  15. #include <wallet/scriptpubkeyman.h>
  16. #include <optional>
  17. namespace wallet {
  18. //! Value for the first BIP 32 hardened derivation. Can be used as a bit mask and as a value. See BIP 32 for more details.
  19. const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
  20. bool LegacyScriptPubKeyMan::GetNewDestination(const OutputType type, CTxDestination& dest, bilingual_str& error)
  21. {
  22. if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
  23. error = _("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types");
  24. return false;
  25. }
  26. assert(type != OutputType::BECH32M);
  27. LOCK(cs_KeyStore);
  28. error.clear();
  29. // Generate a new key that is added to wallet
  30. CPubKey new_key;
  31. if (!GetKeyFromPool(new_key, type)) {
  32. error = _("Error: Keypool ran out, please call keypoolrefill first");
  33. return false;
  34. }
  35. LearnRelatedScripts(new_key, type);
  36. dest = GetDestinationForKey(new_key, type);
  37. return true;
  38. }
  39. typedef std::vector<unsigned char> valtype;
  40. namespace {
  41. /**
  42. * This is an enum that tracks the execution context of a script, similar to
  43. * SigVersion in script/interpreter. It is separate however because we want to
  44. * distinguish between top-level scriptPubKey execution and P2SH redeemScript
  45. * execution (a distinction that has no impact on consensus rules).
  46. */
  47. enum class IsMineSigVersion
  48. {
  49. TOP = 0, //!< scriptPubKey execution
  50. P2SH = 1, //!< P2SH redeemScript
  51. WITNESS_V0 = 2, //!< P2WSH witness script execution
  52. };
  53. /**
  54. * This is an internal representation of isminetype + invalidity.
  55. * Its order is significant, as we return the max of all explored
  56. * possibilities.
  57. */
  58. enum class IsMineResult
  59. {
  60. NO = 0, //!< Not ours
  61. WATCH_ONLY = 1, //!< Included in watch-only balance
  62. SPENDABLE = 2, //!< Included in all balances
  63. INVALID = 3, //!< Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
  64. };
  65. bool PermitsUncompressed(IsMineSigVersion sigversion)
  66. {
  67. return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
  68. }
  69. bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyScriptPubKeyMan& keystore)
  70. {
  71. for (const valtype& pubkey : pubkeys) {
  72. CKeyID keyID = CPubKey(pubkey).GetID();
  73. if (!keystore.HaveKey(keyID)) return false;
  74. }
  75. return true;
  76. }
  77. //! Recursively solve script and return spendable/watchonly/invalid status.
  78. //!
  79. //! @param keystore legacy key and script store
  80. //! @param scriptPubKey script to solve
  81. //! @param sigversion script type (top-level / redeemscript / witnessscript)
  82. //! @param recurse_scripthash whether to recurse into nested p2sh and p2wsh
  83. //! scripts or simply treat any script that has been
  84. //! stored in the keystore as spendable
  85. IsMineResult IsMineInner(const LegacyScriptPubKeyMan& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
  86. {
  87. IsMineResult ret = IsMineResult::NO;
  88. std::vector<valtype> vSolutions;
  89. TxoutType whichType = Solver(scriptPubKey, vSolutions);
  90. CKeyID keyID;
  91. switch (whichType) {
  92. case TxoutType::NONSTANDARD:
  93. case TxoutType::NULL_DATA:
  94. case TxoutType::WITNESS_UNKNOWN:
  95. case TxoutType::WITNESS_V1_TAPROOT:
  96. break;
  97. case TxoutType::PUBKEY:
  98. keyID = CPubKey(vSolutions[0]).GetID();
  99. if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
  100. return IsMineResult::INVALID;
  101. }
  102. if (keystore.HaveKey(keyID)) {
  103. ret = std::max(ret, IsMineResult::SPENDABLE);
  104. }
  105. break;
  106. case TxoutType::WITNESS_V0_KEYHASH:
  107. {
  108. if (sigversion == IsMineSigVersion::WITNESS_V0) {
  109. // P2WPKH inside P2WSH is invalid.
  110. return IsMineResult::INVALID;
  111. }
  112. if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
  113. // We do not support bare witness outputs unless the P2SH version of it would be
  114. // acceptable as well. This protects against matching before segwit activates.
  115. // This also applies to the P2WSH case.
  116. break;
  117. }
  118. ret = std::max(ret, IsMineInner(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
  119. break;
  120. }
  121. case TxoutType::PUBKEYHASH:
  122. keyID = CKeyID(uint160(vSolutions[0]));
  123. if (!PermitsUncompressed(sigversion)) {
  124. CPubKey pubkey;
  125. if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
  126. return IsMineResult::INVALID;
  127. }
  128. }
  129. if (keystore.HaveKey(keyID)) {
  130. ret = std::max(ret, IsMineResult::SPENDABLE);
  131. }
  132. break;
  133. case TxoutType::SCRIPTHASH:
  134. {
  135. if (sigversion != IsMineSigVersion::TOP) {
  136. // P2SH inside P2WSH or P2SH is invalid.
  137. return IsMineResult::INVALID;
  138. }
  139. CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
  140. CScript subscript;
  141. if (keystore.GetCScript(scriptID, subscript)) {
  142. ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
  143. }
  144. break;
  145. }
  146. case TxoutType::WITNESS_V0_SCRIPTHASH:
  147. {
  148. if (sigversion == IsMineSigVersion::WITNESS_V0) {
  149. // P2WSH inside P2WSH is invalid.
  150. return IsMineResult::INVALID;
  151. }
  152. if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
  153. break;
  154. }
  155. uint160 hash;
  156. CRIPEMD160().Write(vSolutions[0].data(), vSolutions[0].size()).Finalize(hash.begin());
  157. CScriptID scriptID = CScriptID(hash);
  158. CScript subscript;
  159. if (keystore.GetCScript(scriptID, subscript)) {
  160. ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
  161. }
  162. break;
  163. }
  164. case TxoutType::MULTISIG:
  165. {
  166. // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
  167. if (sigversion == IsMineSigVersion::TOP) {
  168. break;
  169. }
  170. // Only consider transactions "mine" if we own ALL the
  171. // keys involved. Multi-signature transactions that are
  172. // partially owned (somebody else has a key that can spend
  173. // them) enable spend-out-from-under-you attacks, especially
  174. // in shared-wallet situations.
  175. std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
  176. if (!PermitsUncompressed(sigversion)) {
  177. for (size_t i = 0; i < keys.size(); i++) {
  178. if (keys[i].size() != 33) {
  179. return IsMineResult::INVALID;
  180. }
  181. }
  182. }
  183. if (HaveKeys(keys, keystore)) {
  184. ret = std::max(ret, IsMineResult::SPENDABLE);
  185. }
  186. break;
  187. }
  188. } // no default case, so the compiler can warn about missing cases
  189. if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
  190. ret = std::max(ret, IsMineResult::WATCH_ONLY);
  191. }
  192. return ret;
  193. }
  194. } // namespace
  195. isminetype LegacyScriptPubKeyMan::IsMine(const CScript& script) const
  196. {
  197. switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
  198. case IsMineResult::INVALID:
  199. case IsMineResult::NO:
  200. return ISMINE_NO;
  201. case IsMineResult::WATCH_ONLY:
  202. return ISMINE_WATCH_ONLY;
  203. case IsMineResult::SPENDABLE:
  204. return ISMINE_SPENDABLE;
  205. }
  206. assert(false);
  207. }
  208. bool LegacyScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
  209. {
  210. {
  211. LOCK(cs_KeyStore);
  212. assert(mapKeys.empty());
  213. bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
  214. bool keyFail = false;
  215. CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
  216. WalletBatch batch(m_storage.GetDatabase());
  217. for (; mi != mapCryptedKeys.end(); ++mi)
  218. {
  219. const CPubKey &vchPubKey = (*mi).second.first;
  220. const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
  221. CKey key;
  222. if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
  223. {
  224. keyFail = true;
  225. break;
  226. }
  227. keyPass = true;
  228. if (fDecryptionThoroughlyChecked)
  229. break;
  230. else {
  231. // Rewrite these encrypted keys with checksums
  232. batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
  233. }
  234. }
  235. if (keyPass && keyFail)
  236. {
  237. LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
  238. throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
  239. }
  240. if (keyFail || (!keyPass && !accept_no_keys))
  241. return false;
  242. fDecryptionThoroughlyChecked = true;
  243. }
  244. return true;
  245. }
  246. bool LegacyScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
  247. {
  248. LOCK(cs_KeyStore);
  249. encrypted_batch = batch;
  250. if (!mapCryptedKeys.empty()) {
  251. encrypted_batch = nullptr;
  252. return false;
  253. }
  254. KeyMap keys_to_encrypt;
  255. keys_to_encrypt.swap(mapKeys); // Clear mapKeys so AddCryptedKeyInner will succeed.
  256. for (const KeyMap::value_type& mKey : keys_to_encrypt)
  257. {
  258. const CKey &key = mKey.second;
  259. CPubKey vchPubKey = key.GetPubKey();
  260. CKeyingMaterial vchSecret(key.begin(), key.end());
  261. std::vector<unsigned char> vchCryptedSecret;
  262. if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) {
  263. encrypted_batch = nullptr;
  264. return false;
  265. }
  266. if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
  267. encrypted_batch = nullptr;
  268. return false;
  269. }
  270. }
  271. encrypted_batch = nullptr;
  272. return true;
  273. }
  274. bool LegacyScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool, bilingual_str& error)
  275. {
  276. if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
  277. error = _("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types");
  278. return false;
  279. }
  280. assert(type != OutputType::BECH32M);
  281. LOCK(cs_KeyStore);
  282. if (!CanGetAddresses(internal)) {
  283. error = _("Error: Keypool ran out, please call keypoolrefill first");
  284. return false;
  285. }
  286. if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
  287. error = _("Error: Keypool ran out, please call keypoolrefill first");
  288. return false;
  289. }
  290. address = GetDestinationForKey(keypool.vchPubKey, type);
  291. return true;
  292. }
  293. bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
  294. {
  295. LOCK(cs_KeyStore);
  296. if (m_storage.IsLocked()) return false;
  297. auto it = m_inactive_hd_chains.find(seed_id);
  298. if (it == m_inactive_hd_chains.end()) {
  299. return false;
  300. }
  301. CHDChain& chain = it->second;
  302. // Top up key pool
  303. int64_t target_size = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
  304. // "size" of the keypools. Not really the size, actually the difference between index and the chain counter
  305. // Since chain counter is 1 based and index is 0 based, one of them needs to be offset by 1.
  306. int64_t kp_size = (internal ? chain.nInternalChainCounter : chain.nExternalChainCounter) - (index + 1);
  307. // make sure the keypool fits the user-selected target (-keypool)
  308. int64_t missing = std::max(target_size - kp_size, (int64_t) 0);
  309. if (missing > 0) {
  310. WalletBatch batch(m_storage.GetDatabase());
  311. for (int64_t i = missing; i > 0; --i) {
  312. GenerateNewKey(batch, chain, internal);
  313. }
  314. if (internal) {
  315. WalletLogPrintf("inactive seed with id %s added %d internal keys\n", HexStr(seed_id), missing);
  316. } else {
  317. WalletLogPrintf("inactive seed with id %s added %d keys\n", HexStr(seed_id), missing);
  318. }
  319. }
  320. return true;
  321. }
  322. std::vector<WalletDestination> LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
  323. {
  324. LOCK(cs_KeyStore);
  325. std::vector<WalletDestination> result;
  326. // extract addresses and check if they match with an unused keypool key
  327. for (const auto& keyid : GetAffectedKeys(script, *this)) {
  328. std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
  329. if (mi != m_pool_key_to_index.end()) {
  330. WalletLogPrintf("%s: Detected a used keypool key, mark all keypool keys up to this key as used\n", __func__);
  331. for (const auto& keypool : MarkReserveKeysAsUsed(mi->second)) {
  332. // derive all possible destinations as any of them could have been used
  333. for (const auto& type : LEGACY_OUTPUT_TYPES) {
  334. const auto& dest = GetDestinationForKey(keypool.vchPubKey, type);
  335. result.push_back({dest, keypool.fInternal});
  336. }
  337. }
  338. if (!TopUp()) {
  339. WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
  340. }
  341. }
  342. // Find the key's metadata and check if it's seed id (if it has one) is inactive, i.e. it is not the current m_hd_chain seed id.
  343. // If so, TopUp the inactive hd chain
  344. auto it = mapKeyMetadata.find(keyid);
  345. if (it != mapKeyMetadata.end()){
  346. CKeyMetadata meta = it->second;
  347. if (!meta.hd_seed_id.IsNull() && meta.hd_seed_id != m_hd_chain.seed_id) {
  348. bool internal = (meta.key_origin.path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
  349. int64_t index = meta.key_origin.path[2] & ~BIP32_HARDENED_KEY_LIMIT;
  350. if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
  351. WalletLogPrintf("%s: Adding inactive seed keys failed\n", __func__);
  352. }
  353. }
  354. }
  355. }
  356. return result;
  357. }
  358. void LegacyScriptPubKeyMan::UpgradeKeyMetadata()
  359. {
  360. LOCK(cs_KeyStore);
  361. if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
  362. return;
  363. }
  364. std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
  365. for (auto& meta_pair : mapKeyMetadata) {
  366. CKeyMetadata& meta = meta_pair.second;
  367. if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin && meta.hdKeypath != "s") { // If the hdKeypath is "s", that's the seed and it doesn't have a key origin
  368. CKey key;
  369. GetKey(meta.hd_seed_id, key);
  370. CExtKey masterKey;
  371. masterKey.SetSeed(key);
  372. // Add to map
  373. CKeyID master_id = masterKey.key.GetPubKey().GetID();
  374. std::copy(master_id.begin(), master_id.begin() + 4, meta.key_origin.fingerprint);
  375. if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
  376. throw std::runtime_error("Invalid stored hdKeypath");
  377. }
  378. meta.has_key_origin = true;
  379. if (meta.nVersion < CKeyMetadata::VERSION_WITH_KEY_ORIGIN) {
  380. meta.nVersion = CKeyMetadata::VERSION_WITH_KEY_ORIGIN;
  381. }
  382. // Write meta to wallet
  383. CPubKey pubkey;
  384. if (GetPubKey(meta_pair.first, pubkey)) {
  385. batch->WriteKeyMetadata(meta, pubkey, true);
  386. }
  387. }
  388. }
  389. }
  390. bool LegacyScriptPubKeyMan::SetupGeneration(bool force)
  391. {
  392. if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
  393. return false;
  394. }
  395. SetHDSeed(GenerateNewSeed());
  396. if (!NewKeyPool()) {
  397. return false;
  398. }
  399. return true;
  400. }
  401. bool LegacyScriptPubKeyMan::IsHDEnabled() const
  402. {
  403. return !m_hd_chain.seed_id.IsNull();
  404. }
  405. bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const
  406. {
  407. LOCK(cs_KeyStore);
  408. // Check if the keypool has keys
  409. bool keypool_has_keys;
  410. if (internal && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
  411. keypool_has_keys = setInternalKeyPool.size() > 0;
  412. } else {
  413. keypool_has_keys = KeypoolCountExternalKeys() > 0;
  414. }
  415. // If the keypool doesn't have keys, check if we can generate them
  416. if (!keypool_has_keys) {
  417. return CanGenerateKeys();
  418. }
  419. return keypool_has_keys;
  420. }
  421. bool LegacyScriptPubKeyMan::Upgrade(int prev_version, int new_version, bilingual_str& error)
  422. {
  423. LOCK(cs_KeyStore);
  424. bool hd_upgrade = false;
  425. bool split_upgrade = false;
  426. if (IsFeatureSupported(new_version, FEATURE_HD) && !IsHDEnabled()) {
  427. WalletLogPrintf("Upgrading wallet to HD\n");
  428. m_storage.SetMinVersion(FEATURE_HD);
  429. // generate a new master key
  430. CPubKey masterPubKey = GenerateNewSeed();
  431. SetHDSeed(masterPubKey);
  432. hd_upgrade = true;
  433. }
  434. // Upgrade to HD chain split if necessary
  435. if (!IsFeatureSupported(prev_version, FEATURE_HD_SPLIT) && IsFeatureSupported(new_version, FEATURE_HD_SPLIT)) {
  436. WalletLogPrintf("Upgrading wallet to use HD chain split\n");
  437. m_storage.SetMinVersion(FEATURE_PRE_SPLIT_KEYPOOL);
  438. split_upgrade = FEATURE_HD_SPLIT > prev_version;
  439. // Upgrade the HDChain
  440. if (m_hd_chain.nVersion < CHDChain::VERSION_HD_CHAIN_SPLIT) {
  441. m_hd_chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
  442. if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(m_hd_chain)) {
  443. throw std::runtime_error(std::string(__func__) + ": writing chain failed");
  444. }
  445. }
  446. }
  447. // Mark all keys currently in the keypool as pre-split
  448. if (split_upgrade) {
  449. MarkPreSplitKeys();
  450. }
  451. // Regenerate the keypool if upgraded to HD
  452. if (hd_upgrade) {
  453. if (!NewKeyPool()) {
  454. error = _("Unable to generate keys");
  455. return false;
  456. }
  457. }
  458. return true;
  459. }
  460. bool LegacyScriptPubKeyMan::HavePrivateKeys() const
  461. {
  462. LOCK(cs_KeyStore);
  463. return !mapKeys.empty() || !mapCryptedKeys.empty();
  464. }
  465. void LegacyScriptPubKeyMan::RewriteDB()
  466. {
  467. LOCK(cs_KeyStore);
  468. setInternalKeyPool.clear();
  469. setExternalKeyPool.clear();
  470. m_pool_key_to_index.clear();
  471. // Note: can't top-up keypool here, because wallet is locked.
  472. // User will be prompted to unlock wallet the next operation
  473. // that requires a new key.
  474. }
  475. static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
  476. if (setKeyPool.empty()) {
  477. return GetTime();
  478. }
  479. CKeyPool keypool;
  480. int64_t nIndex = *(setKeyPool.begin());
  481. if (!batch.ReadPool(nIndex, keypool)) {
  482. throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
  483. }
  484. assert(keypool.vchPubKey.IsValid());
  485. return keypool.nTime;
  486. }
  487. std::optional<int64_t> LegacyScriptPubKeyMan::GetOldestKeyPoolTime() const
  488. {
  489. LOCK(cs_KeyStore);
  490. WalletBatch batch(m_storage.GetDatabase());
  491. // load oldest key from keypool, get time and return
  492. int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
  493. if (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
  494. oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
  495. if (!set_pre_split_keypool.empty()) {
  496. oldestKey = std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch), oldestKey);
  497. }
  498. }
  499. return oldestKey;
  500. }
  501. size_t LegacyScriptPubKeyMan::KeypoolCountExternalKeys() const
  502. {
  503. LOCK(cs_KeyStore);
  504. return setExternalKeyPool.size() + set_pre_split_keypool.size();
  505. }
  506. unsigned int LegacyScriptPubKeyMan::GetKeyPoolSize() const
  507. {
  508. LOCK(cs_KeyStore);
  509. return setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size();
  510. }
  511. int64_t LegacyScriptPubKeyMan::GetTimeFirstKey() const
  512. {
  513. LOCK(cs_KeyStore);
  514. return nTimeFirstKey;
  515. }
  516. std::unique_ptr<SigningProvider> LegacyScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
  517. {
  518. return std::make_unique<LegacySigningProvider>(*this);
  519. }
  520. bool LegacyScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
  521. {
  522. IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
  523. if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
  524. // If ismine, it means we recognize keys or script ids in the script, or
  525. // are watching the script itself, and we can at least provide metadata
  526. // or solving information, even if not able to sign fully.
  527. return true;
  528. } else {
  529. // If, given the stuff in sigdata, we could make a valid sigature, then we can provide for this script
  530. ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
  531. if (!sigdata.signatures.empty()) {
  532. // If we could make signatures, make sure we have a private key to actually make a signature
  533. bool has_privkeys = false;
  534. for (const auto& key_sig_pair : sigdata.signatures) {
  535. has_privkeys |= HaveKey(key_sig_pair.first);
  536. }
  537. return has_privkeys;
  538. }
  539. return false;
  540. }
  541. }
  542. bool LegacyScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
  543. {
  544. return ::SignTransaction(tx, this, coins, sighash, input_errors);
  545. }
  546. SigningResult LegacyScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
  547. {
  548. CKey key;
  549. if (!GetKey(ToKeyID(pkhash), key)) {
  550. return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
  551. }
  552. if (MessageSign(key, message, str_sig)) {
  553. return SigningResult::OK;
  554. }
  555. return SigningResult::SIGNING_FAILED;
  556. }
  557. TransactionError LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
  558. {
  559. if (n_signed) {
  560. *n_signed = 0;
  561. }
  562. for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
  563. const CTxIn& txin = psbtx.tx->vin[i];
  564. PSBTInput& input = psbtx.inputs.at(i);
  565. if (PSBTInputSigned(input)) {
  566. continue;
  567. }
  568. // Get the Sighash type
  569. if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
  570. return TransactionError::SIGHASH_MISMATCH;
  571. }
  572. // Check non_witness_utxo has specified prevout
  573. if (input.non_witness_utxo) {
  574. if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
  575. return TransactionError::MISSING_INPUTS;
  576. }
  577. } else if (input.witness_utxo.IsNull()) {
  578. // There's no UTXO so we can just skip this now
  579. continue;
  580. }
  581. SignatureData sigdata;
  582. input.FillSignatureData(sigdata);
  583. SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
  584. bool signed_one = PSBTInputSigned(input);
  585. if (n_signed && (signed_one || !sign)) {
  586. // If sign is false, we assume that we _could_ sign if we get here. This
  587. // will never have false negatives; it is hard to tell under what i
  588. // circumstances it could have false positives.
  589. (*n_signed)++;
  590. }
  591. }
  592. // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
  593. for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
  594. UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
  595. }
  596. return TransactionError::OK;
  597. }
  598. std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
  599. {
  600. LOCK(cs_KeyStore);
  601. CKeyID key_id = GetKeyForDestination(*this, dest);
  602. if (!key_id.IsNull()) {
  603. auto it = mapKeyMetadata.find(key_id);
  604. if (it != mapKeyMetadata.end()) {
  605. return std::make_unique<CKeyMetadata>(it->second);
  606. }
  607. }
  608. CScript scriptPubKey = GetScriptForDestination(dest);
  609. auto it = m_script_metadata.find(CScriptID(scriptPubKey));
  610. if (it != m_script_metadata.end()) {
  611. return std::make_unique<CKeyMetadata>(it->second);
  612. }
  613. return nullptr;
  614. }
  615. uint256 LegacyScriptPubKeyMan::GetID() const
  616. {
  617. return uint256::ONE;
  618. }
  619. /**
  620. * Update wallet first key creation time. This should be called whenever keys
  621. * are added to the wallet, with the oldest key creation time.
  622. */
  623. void LegacyScriptPubKeyMan::UpdateTimeFirstKey(int64_t nCreateTime)
  624. {
  625. AssertLockHeld(cs_KeyStore);
  626. if (nCreateTime <= 1) {
  627. // Cannot determine birthday information, so set the wallet birthday to
  628. // the beginning of time.
  629. nTimeFirstKey = 1;
  630. } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
  631. nTimeFirstKey = nCreateTime;
  632. }
  633. }
  634. bool LegacyScriptPubKeyMan::LoadKey(const CKey& key, const CPubKey &pubkey)
  635. {
  636. return AddKeyPubKeyInner(key, pubkey);
  637. }
  638. bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
  639. {
  640. LOCK(cs_KeyStore);
  641. WalletBatch batch(m_storage.GetDatabase());
  642. return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
  643. }
  644. bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
  645. {
  646. AssertLockHeld(cs_KeyStore);
  647. // Make sure we aren't adding private keys to private key disabled wallets
  648. assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
  649. // FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
  650. // which is overridden below. To avoid flushes, the database handle is
  651. // tunneled through to it.
  652. bool needsDB = !encrypted_batch;
  653. if (needsDB) {
  654. encrypted_batch = &batch;
  655. }
  656. if (!AddKeyPubKeyInner(secret, pubkey)) {
  657. if (needsDB) encrypted_batch = nullptr;
  658. return false;
  659. }
  660. if (needsDB) encrypted_batch = nullptr;
  661. // check if we need to remove from watch-only
  662. CScript script;
  663. script = GetScriptForDestination(PKHash(pubkey));
  664. if (HaveWatchOnly(script)) {
  665. RemoveWatchOnly(script);
  666. }
  667. script = GetScriptForRawPubKey(pubkey);
  668. if (HaveWatchOnly(script)) {
  669. RemoveWatchOnly(script);
  670. }
  671. if (!m_storage.HasEncryptionKeys()) {
  672. return batch.WriteKey(pubkey,
  673. secret.GetPrivKey(),
  674. mapKeyMetadata[pubkey.GetID()]);
  675. }
  676. m_storage.UnsetBlankWalletFlag(batch);
  677. return true;
  678. }
  679. bool LegacyScriptPubKeyMan::LoadCScript(const CScript& redeemScript)
  680. {
  681. /* A sanity check was added in pull #3843 to avoid adding redeemScripts
  682. * that never can be redeemed. However, old wallets may still contain
  683. * these. Do not add them to the wallet and warn. */
  684. if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
  685. {
  686. std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
  687. WalletLogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
  688. return true;
  689. }
  690. return FillableSigningProvider::AddCScript(redeemScript);
  691. }
  692. void LegacyScriptPubKeyMan::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
  693. {
  694. LOCK(cs_KeyStore);
  695. UpdateTimeFirstKey(meta.nCreateTime);
  696. mapKeyMetadata[keyID] = meta;
  697. }
  698. void LegacyScriptPubKeyMan::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
  699. {
  700. LOCK(cs_KeyStore);
  701. UpdateTimeFirstKey(meta.nCreateTime);
  702. m_script_metadata[script_id] = meta;
  703. }
  704. bool LegacyScriptPubKeyMan::AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey)
  705. {
  706. LOCK(cs_KeyStore);
  707. if (!m_storage.HasEncryptionKeys()) {
  708. return FillableSigningProvider::AddKeyPubKey(key, pubkey);
  709. }
  710. if (m_storage.IsLocked()) {
  711. return false;
  712. }
  713. std::vector<unsigned char> vchCryptedSecret;
  714. CKeyingMaterial vchSecret(key.begin(), key.end());
  715. if (!EncryptSecret(m_storage.GetEncryptionKey(), vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
  716. return false;
  717. }
  718. if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
  719. return false;
  720. }
  721. return true;
  722. }
  723. bool LegacyScriptPubKeyMan::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
  724. {
  725. // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
  726. if (!checksum_valid) {
  727. fDecryptionThoroughlyChecked = false;
  728. }
  729. return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
  730. }
  731. bool LegacyScriptPubKeyMan::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
  732. {
  733. LOCK(cs_KeyStore);
  734. assert(mapKeys.empty());
  735. mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
  736. ImplicitlyLearnRelatedKeyScripts(vchPubKey);
  737. return true;
  738. }
  739. bool LegacyScriptPubKeyMan::AddCryptedKey(const CPubKey &vchPubKey,
  740. const std::vector<unsigned char> &vchCryptedSecret)
  741. {
  742. if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
  743. return false;
  744. {
  745. LOCK(cs_KeyStore);
  746. if (encrypted_batch)
  747. return encrypted_batch->WriteCryptedKey(vchPubKey,
  748. vchCryptedSecret,
  749. mapKeyMetadata[vchPubKey.GetID()]);
  750. else
  751. return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
  752. vchCryptedSecret,
  753. mapKeyMetadata[vchPubKey.GetID()]);
  754. }
  755. }
  756. bool LegacyScriptPubKeyMan::HaveWatchOnly(const CScript &dest) const
  757. {
  758. LOCK(cs_KeyStore);
  759. return setWatchOnly.count(dest) > 0;
  760. }
  761. bool LegacyScriptPubKeyMan::HaveWatchOnly() const
  762. {
  763. LOCK(cs_KeyStore);
  764. return (!setWatchOnly.empty());
  765. }
  766. static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
  767. {
  768. std::vector<std::vector<unsigned char>> solutions;
  769. return Solver(dest, solutions) == TxoutType::PUBKEY &&
  770. (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
  771. }
  772. bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest)
  773. {
  774. {
  775. LOCK(cs_KeyStore);
  776. setWatchOnly.erase(dest);
  777. CPubKey pubKey;
  778. if (ExtractPubKey(dest, pubKey)) {
  779. mapWatchKeys.erase(pubKey.GetID());
  780. }
  781. // Related CScripts are not removed; having superfluous scripts around is
  782. // harmless (see comment in ImplicitlyLearnRelatedKeyScripts).
  783. }
  784. if (!HaveWatchOnly())
  785. NotifyWatchonlyChanged(false);
  786. if (!WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest))
  787. return false;
  788. return true;
  789. }
  790. bool LegacyScriptPubKeyMan::LoadWatchOnly(const CScript &dest)
  791. {
  792. return AddWatchOnlyInMem(dest);
  793. }
  794. bool LegacyScriptPubKeyMan::AddWatchOnlyInMem(const CScript &dest)
  795. {
  796. LOCK(cs_KeyStore);
  797. setWatchOnly.insert(dest);
  798. CPubKey pubKey;
  799. if (ExtractPubKey(dest, pubKey)) {
  800. mapWatchKeys[pubKey.GetID()] = pubKey;
  801. ImplicitlyLearnRelatedKeyScripts(pubKey);
  802. }
  803. return true;
  804. }
  805. bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest)
  806. {
  807. if (!AddWatchOnlyInMem(dest))
  808. return false;
  809. const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
  810. UpdateTimeFirstKey(meta.nCreateTime);
  811. NotifyWatchonlyChanged(true);
  812. if (batch.WriteWatchOnly(dest, meta)) {
  813. m_storage.UnsetBlankWalletFlag(batch);
  814. return true;
  815. }
  816. return false;
  817. }
  818. bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
  819. {
  820. m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
  821. return AddWatchOnlyWithDB(batch, dest);
  822. }
  823. bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest)
  824. {
  825. WalletBatch batch(m_storage.GetDatabase());
  826. return AddWatchOnlyWithDB(batch, dest);
  827. }
  828. bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
  829. {
  830. m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
  831. return AddWatchOnly(dest);
  832. }
  833. void LegacyScriptPubKeyMan::LoadHDChain(const CHDChain& chain)
  834. {
  835. LOCK(cs_KeyStore);
  836. m_hd_chain = chain;
  837. }
  838. void LegacyScriptPubKeyMan::AddHDChain(const CHDChain& chain)
  839. {
  840. LOCK(cs_KeyStore);
  841. // Store the new chain
  842. if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(chain)) {
  843. throw std::runtime_error(std::string(__func__) + ": writing chain failed");
  844. }
  845. // When there's an old chain, add it as an inactive chain as we are now rotating hd chains
  846. if (!m_hd_chain.seed_id.IsNull()) {
  847. AddInactiveHDChain(m_hd_chain);
  848. }
  849. m_hd_chain = chain;
  850. }
  851. void LegacyScriptPubKeyMan::AddInactiveHDChain(const CHDChain& chain)
  852. {
  853. LOCK(cs_KeyStore);
  854. assert(!chain.seed_id.IsNull());
  855. m_inactive_hd_chains[chain.seed_id] = chain;
  856. }
  857. bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const
  858. {
  859. LOCK(cs_KeyStore);
  860. if (!m_storage.HasEncryptionKeys()) {
  861. return FillableSigningProvider::HaveKey(address);
  862. }
  863. return mapCryptedKeys.count(address) > 0;
  864. }
  865. bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey& keyOut) const
  866. {
  867. LOCK(cs_KeyStore);
  868. if (!m_storage.HasEncryptionKeys()) {
  869. return FillableSigningProvider::GetKey(address, keyOut);
  870. }
  871. CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
  872. if (mi != mapCryptedKeys.end())
  873. {
  874. const CPubKey &vchPubKey = (*mi).second.first;
  875. const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
  876. return DecryptKey(m_storage.GetEncryptionKey(), vchCryptedSecret, vchPubKey, keyOut);
  877. }
  878. return false;
  879. }
  880. bool LegacyScriptPubKeyMan::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
  881. {
  882. CKeyMetadata meta;
  883. {
  884. LOCK(cs_KeyStore);
  885. auto it = mapKeyMetadata.find(keyID);
  886. if (it != mapKeyMetadata.end()) {
  887. meta = it->second;
  888. }
  889. }
  890. if (meta.has_key_origin) {
  891. std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
  892. info.path = meta.key_origin.path;
  893. } else { // Single pubkeys get the master fingerprint of themselves
  894. std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
  895. }
  896. return true;
  897. }
  898. bool LegacyScriptPubKeyMan::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
  899. {
  900. LOCK(cs_KeyStore);
  901. WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
  902. if (it != mapWatchKeys.end()) {
  903. pubkey_out = it->second;
  904. return true;
  905. }
  906. return false;
  907. }
  908. bool LegacyScriptPubKeyMan::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
  909. {
  910. LOCK(cs_KeyStore);
  911. if (!m_storage.HasEncryptionKeys()) {
  912. if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
  913. return GetWatchPubKey(address, vchPubKeyOut);
  914. }
  915. return true;
  916. }
  917. CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
  918. if (mi != mapCryptedKeys.end())
  919. {
  920. vchPubKeyOut = (*mi).second.first;
  921. return true;
  922. }
  923. // Check for watch-only pubkeys
  924. return GetWatchPubKey(address, vchPubKeyOut);
  925. }
  926. CPubKey LegacyScriptPubKeyMan::GenerateNewKey(WalletBatch &batch, CHDChain& hd_chain, bool internal)
  927. {
  928. assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
  929. assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
  930. AssertLockHeld(cs_KeyStore);
  931. bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
  932. CKey secret;
  933. // Create new metadata
  934. int64_t nCreationTime = GetTime();
  935. CKeyMetadata metadata(nCreationTime);
  936. // use HD key derivation if HD was enabled during wallet creation and a seed is present
  937. if (IsHDEnabled()) {
  938. DeriveNewChildKey(batch, metadata, secret, hd_chain, (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
  939. } else {
  940. secret.MakeNewKey(fCompressed);
  941. }
  942. // Compressed public keys were introduced in version 0.6.0
  943. if (fCompressed) {
  944. m_storage.SetMinVersion(FEATURE_COMPRPUBKEY);
  945. }
  946. CPubKey pubkey = secret.GetPubKey();
  947. assert(secret.VerifyPubKey(pubkey));
  948. mapKeyMetadata[pubkey.GetID()] = metadata;
  949. UpdateTimeFirstKey(nCreationTime);
  950. if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
  951. throw std::runtime_error(std::string(__func__) + ": AddKey failed");
  952. }
  953. return pubkey;
  954. }
  955. void LegacyScriptPubKeyMan::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal)
  956. {
  957. // for now we use a fixed keypath scheme of m/0'/0'/k
  958. CKey seed; //seed (256bit)
  959. CExtKey masterKey; //hd master key
  960. CExtKey accountKey; //key at m/0'
  961. CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
  962. CExtKey childKey; //key at m/0'/0'/<n>'
  963. // try to get the seed
  964. if (!GetKey(hd_chain.seed_id, seed))
  965. throw std::runtime_error(std::string(__func__) + ": seed not found");
  966. masterKey.SetSeed(seed);
  967. // derive m/0'
  968. // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
  969. masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
  970. // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
  971. assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
  972. accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
  973. // derive child key at next index, skip keys already known to the wallet
  974. do {
  975. // always derive hardened keys
  976. // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
  977. // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
  978. if (internal) {
  979. chainChildKey.Derive(childKey, hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
  980. metadata.hdKeypath = "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
  981. metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
  982. metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
  983. metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
  984. hd_chain.nInternalChainCounter++;
  985. }
  986. else {
  987. chainChildKey.Derive(childKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
  988. metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
  989. metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
  990. metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
  991. metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
  992. hd_chain.nExternalChainCounter++;
  993. }
  994. } while (HaveKey(childKey.key.GetPubKey().GetID()));
  995. secret = childKey.key;
  996. metadata.hd_seed_id = hd_chain.seed_id;
  997. CKeyID master_id = masterKey.key.GetPubKey().GetID();
  998. std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
  999. metadata.has_key_origin = true;
  1000. // update the chain model in the database
  1001. if (hd_chain.seed_id == m_hd_chain.seed_id && !batch.WriteHDChain(hd_chain))
  1002. throw std::runtime_error(std::string(__func__) + ": writing HD chain model failed");
  1003. }
  1004. void LegacyScriptPubKeyMan::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
  1005. {
  1006. LOCK(cs_KeyStore);
  1007. if (keypool.m_pre_split) {
  1008. set_pre_split_keypool.insert(nIndex);
  1009. } else if (keypool.fInternal) {
  1010. setInternalKeyPool.insert(nIndex);
  1011. } else {
  1012. setExternalKeyPool.insert(nIndex);
  1013. }
  1014. m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
  1015. m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
  1016. // If no metadata exists yet, create a default with the pool key's
  1017. // creation time. Note that this may be overwritten by actually
  1018. // stored metadata for that key later, which is fine.
  1019. CKeyID keyid = keypool.vchPubKey.GetID();
  1020. if (mapKeyMetadata.count(keyid) == 0)
  1021. mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
  1022. }
  1023. bool LegacyScriptPubKeyMan::CanGenerateKeys() const
  1024. {
  1025. // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
  1026. LOCK(cs_KeyStore);
  1027. return IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD);
  1028. }
  1029. CPubKey LegacyScriptPubKeyMan::GenerateNewSeed()
  1030. {
  1031. assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
  1032. CKey key;
  1033. key.MakeNewKey(true);
  1034. return DeriveNewSeed(key);
  1035. }
  1036. CPubKey LegacyScriptPubKeyMan::DeriveNewSeed(const CKey& key)
  1037. {
  1038. int64_t nCreationTime = GetTime();
  1039. CKeyMetadata metadata(nCreationTime);
  1040. // calculate the seed
  1041. CPubKey seed = key.GetPubKey();
  1042. assert(key.VerifyPubKey(seed));
  1043. // set the hd keypath to "s" -> Seed, refers the seed to itself
  1044. metadata.hdKeypath = "s";
  1045. metadata.has_key_origin = false;
  1046. metadata.hd_seed_id = seed.GetID();
  1047. {
  1048. LOCK(cs_KeyStore);
  1049. // mem store the metadata
  1050. mapKeyMetadata[seed.GetID()] = metadata;
  1051. // write the key&metadata to the database
  1052. if (!AddKeyPubKey(key, seed))
  1053. throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
  1054. }
  1055. return seed;
  1056. }
  1057. void LegacyScriptPubKeyMan::SetHDSeed(const CPubKey& seed)
  1058. {
  1059. LOCK(cs_KeyStore);
  1060. // store the keyid (hash160) together with
  1061. // the child index counter in the database
  1062. // as a hdchain object
  1063. CHDChain newHdChain;
  1064. newHdChain.nVersion = m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
  1065. newHdChain.seed_id = seed.GetID();
  1066. AddHDChain(newHdChain);
  1067. NotifyCanGetAddressesChanged();
  1068. WalletBatch batch(m_storage.GetDatabase());
  1069. m_storage.UnsetBlankWalletFlag(batch);
  1070. }
  1071. /**
  1072. * Mark old keypool keys as used,
  1073. * and generate all new keys
  1074. */
  1075. bool LegacyScriptPubKeyMan::NewKeyPool()
  1076. {
  1077. if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
  1078. return false;
  1079. }
  1080. {
  1081. LOCK(cs_KeyStore);
  1082. WalletBatch batch(m_storage.GetDatabase());
  1083. for (const int64_t nIndex : setInternalKeyPool) {
  1084. batch.ErasePool(nIndex);
  1085. }
  1086. setInternalKeyPool.clear();
  1087. for (const int64_t nIndex : setExternalKeyPool) {
  1088. batch.ErasePool(nIndex);
  1089. }
  1090. setExternalKeyPool.clear();
  1091. for (const int64_t nIndex : set_pre_split_keypool) {
  1092. batch.ErasePool(nIndex);
  1093. }
  1094. set_pre_split_keypool.clear();
  1095. m_pool_key_to_index.clear();
  1096. if (!TopUp()) {
  1097. return false;
  1098. }
  1099. WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
  1100. }
  1101. return true;
  1102. }
  1103. bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
  1104. {
  1105. if (!CanGenerateKeys()) {
  1106. return false;
  1107. }
  1108. {
  1109. LOCK(cs_KeyStore);
  1110. if (m_storage.IsLocked()) return false;
  1111. // Top up key pool
  1112. unsigned int nTargetSize;
  1113. if (kpSize > 0)
  1114. nTargetSize = kpSize;
  1115. else
  1116. nTargetSize = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
  1117. // count amount of available keys (internal, external)
  1118. // make sure the keypool of external and internal keys fits the user selected target (-keypool)
  1119. int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
  1120. int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
  1121. if (!IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))
  1122. {
  1123. // don't create extra internal keys
  1124. missingInternal = 0;
  1125. }
  1126. bool internal = false;
  1127. WalletBatch batch(m_storage.GetDatabase());
  1128. for (int64_t i = missingInternal + missingExternal; i--;)
  1129. {
  1130. if (i < missingInternal) {
  1131. internal = true;
  1132. }
  1133. CPubKey pubkey(GenerateNewKey(batch, m_hd_chain, internal));
  1134. AddKeypoolPubkeyWithDB(pubkey, internal, batch);
  1135. }
  1136. if (missingInternal + missingExternal > 0) {
  1137. WalletLogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size(), setInternalKeyPool.size());
  1138. }
  1139. }
  1140. NotifyCanGetAddressesChanged();
  1141. return true;
  1142. }
  1143. void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
  1144. {
  1145. LOCK(cs_KeyStore);
  1146. assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
  1147. int64_t index = ++m_max_keypool_index;
  1148. if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
  1149. throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
  1150. }
  1151. if (internal) {
  1152. setInternalKeyPool.insert(index);
  1153. } else {
  1154. setExternalKeyPool.insert(index);
  1155. }
  1156. m_pool_key_to_index[pubkey.GetID()] = index;
  1157. }
  1158. void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
  1159. {
  1160. assert(type != OutputType::BECH32M);
  1161. // Remove from key pool
  1162. WalletBatch batch(m_storage.GetDatabase());
  1163. batch.ErasePool(nIndex);
  1164. CPubKey pubkey;
  1165. bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
  1166. assert(have_pk);
  1167. LearnRelatedScripts(pubkey, type);
  1168. m_index_to_reserved_key.erase(nIndex);
  1169. WalletLogPrintf("keypool keep %d\n", nIndex);
  1170. }
  1171. void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal, const CTxDestination&)
  1172. {
  1173. // Return to key pool
  1174. {
  1175. LOCK(cs_KeyStore);
  1176. if (fInternal) {
  1177. setInternalKeyPool.insert(nIndex);
  1178. } else if (!set_pre_split_keypool.empty()) {
  1179. set_pre_split_keypool.insert(nIndex);
  1180. } else {
  1181. setExternalKeyPool.insert(nIndex);
  1182. }
  1183. CKeyID& pubkey_id = m_index_to_reserved_key.at(nIndex);
  1184. m_pool_key_to_index[pubkey_id] = nIndex;
  1185. m_index_to_reserved_key.erase(nIndex);
  1186. NotifyCanGetAddressesChanged();
  1187. }
  1188. WalletLogPrintf("keypool return %d\n", nIndex);
  1189. }
  1190. bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type, bool internal)
  1191. {
  1192. assert(type != OutputType::BECH32M);
  1193. if (!CanGetAddresses(internal)) {
  1194. return false;
  1195. }
  1196. CKeyPool keypool;
  1197. {
  1198. LOCK(cs_KeyStore);
  1199. int64_t nIndex;
  1200. if (!ReserveKeyFromKeyPool(nIndex, keypool, internal) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
  1201. if (m_storage.IsLocked()) return false;
  1202. WalletBatch batch(m_storage.GetDatabase());
  1203. result = GenerateNewKey(batch, m_hd_chain, internal);
  1204. return true;
  1205. }
  1206. KeepDestination(nIndex, type);
  1207. result = keypool.vchPubKey;
  1208. }
  1209. return true;
  1210. }
  1211. bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
  1212. {
  1213. nIndex = -1;
  1214. keypool.vchPubKey = CPubKey();
  1215. {
  1216. LOCK(cs_KeyStore);
  1217. bool fReturningInternal = fRequestedInternal;
  1218. fReturningInternal &= (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) || m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
  1219. bool use_split_keypool = set_pre_split_keypool.empty();
  1220. std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
  1221. // Get the oldest key
  1222. if (setKeyPool.empty()) {
  1223. return false;
  1224. }
  1225. WalletBatch batch(m_storage.GetDatabase());
  1226. auto it = setKeyPool.begin();
  1227. nIndex = *it;
  1228. setKeyPool.erase(it);
  1229. if (!batch.ReadPool(nIndex, keypool)) {
  1230. throw std::runtime_error(std::string(__func__) + ": read failed");
  1231. }
  1232. CPubKey pk;
  1233. if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
  1234. throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
  1235. }
  1236. // If the key was pre-split keypool, we don't care about what type it is
  1237. if (use_split_keypool && keypool.fInternal != fReturningInternal) {
  1238. throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
  1239. }
  1240. if (!keypool.vchPubKey.IsValid()) {
  1241. throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
  1242. }
  1243. assert(m_index_to_reserved_key.count(nIndex) == 0);
  1244. m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
  1245. m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
  1246. WalletLogPrintf("keypool reserve %d\n", nIndex);
  1247. }
  1248. NotifyCanGetAddressesChanged();
  1249. return true;
  1250. }
  1251. void LegacyScriptPubKeyMan::LearnRelatedScripts(const CPubKey& key, OutputType type)
  1252. {
  1253. assert(type != OutputType::BECH32M);
  1254. if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
  1255. CTxDestination witdest = WitnessV0KeyHash(key.GetID());
  1256. CScript witprog = GetScriptForDestination(witdest);
  1257. // Make sure the resulting program is solvable.
  1258. assert(IsSolvable(*this, witprog));
  1259. AddCScript(witprog);
  1260. }
  1261. }
  1262. void LegacyScriptPubKeyMan::LearnAllRelatedScripts(const CPubKey& key)
  1263. {
  1264. // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
  1265. LearnRelatedScripts(key, OutputType::P2SH_SEGWIT);
  1266. }
  1267. std::vector<CKeyPool> LegacyScriptPubKeyMan::MarkReserveKeysAsUsed(int64_t keypool_id)
  1268. {
  1269. AssertLockHeld(cs_KeyStore);
  1270. bool internal = setInternalKeyPool.count(keypool_id);
  1271. if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
  1272. std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
  1273. auto it = setKeyPool->begin();
  1274. std::vector<CKeyPool> result;
  1275. WalletBatch batch(m_storage.GetDatabase());
  1276. while (it != std::end(*setKeyPool)) {
  1277. const int64_t& index = *(it);
  1278. if (index > keypool_id) break; // set*KeyPool is ordered
  1279. CKeyPool keypool;
  1280. if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
  1281. m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
  1282. }
  1283. LearnAllRelatedScripts(keypool.vchPubKey);
  1284. batch.ErasePool(index);
  1285. WalletLogPrintf("keypool index %d removed\n", index);
  1286. it = setKeyPool->erase(it);
  1287. result.push_back(std::move(keypool));
  1288. }
  1289. return result;
  1290. }
  1291. std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
  1292. {
  1293. std::vector<CScript> dummy;
  1294. FlatSigningProvider out;
  1295. InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
  1296. std::vector<CKeyID> ret;
  1297. for (const auto& entry : out.pubkeys) {
  1298. ret.push_back(entry.first);
  1299. }
  1300. return ret;
  1301. }
  1302. void LegacyScriptPubKeyMan::MarkPreSplitKeys()
  1303. {
  1304. WalletBatch batch(m_storage.GetDatabase());
  1305. for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
  1306. int64_t index = *it;
  1307. CKeyPool keypool;
  1308. if (!batch.ReadPool(index, keypool)) {
  1309. throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
  1310. }
  1311. keypool.m_pre_split = true;
  1312. if (!batch.WritePool(index, keypool)) {
  1313. throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
  1314. }
  1315. set_pre_split_keypool.insert(index);
  1316. it = setExternalKeyPool.erase(it);
  1317. }
  1318. }
  1319. bool LegacyScriptPubKeyMan::AddCScript(const CScript& redeemScript)
  1320. {
  1321. WalletBatch batch(m_storage.GetDatabase());
  1322. return AddCScriptWithDB(batch, redeemScript);
  1323. }
  1324. bool LegacyScriptPubKeyMan::AddCScriptWithDB(WalletBatch& batch, const CScript& redeemScript)
  1325. {
  1326. if (!FillableSigningProvider::AddCScript(redeemScript))
  1327. return false;
  1328. if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
  1329. m_storage.UnsetBlankWalletFlag(batch);
  1330. return true;
  1331. }
  1332. return false;
  1333. }
  1334. bool LegacyScriptPubKeyMan::AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info)
  1335. {
  1336. LOCK(cs_KeyStore);
  1337. std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
  1338. mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
  1339. mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
  1340. mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
  1341. return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
  1342. }
  1343. bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
  1344. {
  1345. WalletBatch batch(m_storage.GetDatabase());
  1346. for (const auto& entry : scripts) {
  1347. CScriptID id(entry);
  1348. if (HaveCScript(id)) {
  1349. WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
  1350. continue;
  1351. }
  1352. if (!AddCScriptWithDB(batch, entry)) {
  1353. return false;
  1354. }
  1355. if (timestamp > 0) {
  1356. m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
  1357. }
  1358. }
  1359. if (timestamp > 0) {
  1360. UpdateTimeFirstKey(timestamp);
  1361. }
  1362. return true;
  1363. }
  1364. bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
  1365. {
  1366. WalletBatch batch(m_storage.GetDatabase());
  1367. for (const auto& entry : privkey_map) {
  1368. const CKey& key = entry.second;
  1369. CPubKey pubkey = key.GetPubKey();
  1370. const CKeyID& id = entry.first;
  1371. assert(key.VerifyPubKey(pubkey));
  1372. // Skip if we already have the key
  1373. if (HaveKey(id)) {
  1374. WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
  1375. continue;
  1376. }
  1377. mapKeyMetadata[id].nCreateTime = timestamp;
  1378. // If the private key is not present in the wallet, insert it.
  1379. if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
  1380. return false;
  1381. }
  1382. UpdateTimeFirstKey(timestamp);
  1383. }
  1384. return true;
  1385. }
  1386. bool LegacyScriptPubKeyMan::ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp)
  1387. {
  1388. WalletBatch batch(m_storage.GetDatabase());
  1389. for (const auto& entry : key_origins) {
  1390. AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
  1391. }
  1392. for (const CKeyID& id : ordered_pubkeys) {
  1393. auto entry = pubkey_map.find(id);
  1394. if (entry == pubkey_map.end()) {
  1395. continue;
  1396. }
  1397. const CPubKey& pubkey = entry->second;
  1398. CPubKey temp;
  1399. if (GetPubKey(id, temp)) {
  1400. // Already have pubkey, skipping
  1401. WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
  1402. continue;
  1403. }
  1404. if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey), timestamp)) {
  1405. return false;
  1406. }
  1407. mapKeyMetadata[id].nCreateTime = timestamp;
  1408. // Add to keypool only works with pubkeys
  1409. if (add_keypool) {
  1410. AddKeypoolPubkeyWithDB(pubkey, internal, batch);
  1411. NotifyCanGetAddressesChanged();
  1412. }
  1413. }
  1414. return true;
  1415. }
  1416. bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
  1417. {
  1418. WalletBatch batch(m_storage.GetDatabase());
  1419. for (const CScript& script : script_pub_keys) {
  1420. if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
  1421. if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
  1422. return false;
  1423. }
  1424. }
  1425. }
  1426. return true;
  1427. }
  1428. std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
  1429. {
  1430. LOCK(cs_KeyStore);
  1431. if (!m_storage.HasEncryptionKeys()) {
  1432. return FillableSigningProvider::GetKeys();
  1433. }
  1434. std::set<CKeyID> set_address;
  1435. for (const auto& mi : mapCryptedKeys) {
  1436. set_address.insert(mi.first);
  1437. }
  1438. return set_address;
  1439. }
  1440. bool DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type, CTxDestination& dest, bilingual_str& error)
  1441. {
  1442. // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
  1443. if (!CanGetAddresses()) {
  1444. error = _("No addresses available");
  1445. return false;
  1446. }
  1447. {
  1448. LOCK(cs_desc_man);
  1449. assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
  1450. std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
  1451. assert(desc_addr_type);
  1452. if (type != *desc_addr_type) {
  1453. throw std::runtime_error(std::string(__func__) + ": Types are inconsistent");
  1454. }
  1455. TopUp();
  1456. // Get the scriptPubKey from the descriptor
  1457. FlatSigningProvider out_keys;
  1458. std::vector<CScript> scripts_temp;
  1459. if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
  1460. // We can't generate anymore keys
  1461. error = _("Error: Keypool ran out, please call keypoolrefill first");
  1462. return false;
  1463. }
  1464. if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
  1465. // We can't generate anymore keys
  1466. error = _("Error: Keypool ran out, please call keypoolrefill first");
  1467. return false;
  1468. }
  1469. std::optional<OutputType> out_script_type = m_wallet_descriptor.descriptor->GetOutputType();
  1470. if (out_script_type && out_script_type == type) {
  1471. ExtractDestination(scripts_temp[0], dest);
  1472. } else {
  1473. throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
  1474. }
  1475. m_wallet_descriptor.next_index++;
  1476. WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
  1477. return true;
  1478. }
  1479. }
  1480. isminetype DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
  1481. {
  1482. LOCK(cs_desc_man);
  1483. if (m_map_script_pub_keys.count(script) > 0) {
  1484. return ISMINE_SPENDABLE;
  1485. }
  1486. return ISMINE_NO;
  1487. }
  1488. bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
  1489. {
  1490. LOCK(cs_desc_man);
  1491. if (!m_map_keys.empty()) {
  1492. return false;
  1493. }
  1494. bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
  1495. bool keyFail = false;
  1496. for (const auto& mi : m_map_crypted_keys) {
  1497. const CPubKey &pubkey = mi.second.first;
  1498. const std::vector<unsigned char> &crypted_secret = mi.second.second;
  1499. CKey key;
  1500. if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
  1501. keyFail = true;
  1502. break;
  1503. }
  1504. keyPass = true;
  1505. if (m_decryption_thoroughly_checked)
  1506. break;
  1507. }
  1508. if (keyPass && keyFail) {
  1509. LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
  1510. throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
  1511. }
  1512. if (keyFail || (!keyPass && !accept_no_keys)) {
  1513. return false;
  1514. }
  1515. m_decryption_thoroughly_checked = true;
  1516. return true;
  1517. }
  1518. bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
  1519. {
  1520. LOCK(cs_desc_man);
  1521. if (!m_map_crypted_keys.empty()) {
  1522. return false;
  1523. }
  1524. for (const KeyMap::value_type& key_in : m_map_keys)
  1525. {
  1526. const CKey &key = key_in.second;
  1527. CPubKey pubkey = key.GetPubKey();
  1528. CKeyingMaterial secret(key.begin(), key.end());
  1529. std::vector<unsigned char> crypted_secret;
  1530. if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
  1531. return false;
  1532. }
  1533. m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
  1534. batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
  1535. }
  1536. m_map_keys.clear();
  1537. return true;
  1538. }
  1539. bool DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool, bilingual_str& error)
  1540. {
  1541. LOCK(cs_desc_man);
  1542. bool result = GetNewDestination(type, address, error);
  1543. index = m_wallet_descriptor.next_index - 1;
  1544. return result;
  1545. }
  1546. void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
  1547. {
  1548. LOCK(cs_desc_man);
  1549. // Only return when the index was the most recent
  1550. if (m_wallet_descriptor.next_index - 1 == index) {
  1551. m_wallet_descriptor.next_index--;
  1552. }
  1553. WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
  1554. NotifyCanGetAddressesChanged();
  1555. }
  1556. std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
  1557. {
  1558. AssertLockHeld(cs_desc_man);
  1559. if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
  1560. KeyMap keys;
  1561. for (auto key_pair : m_map_crypted_keys) {
  1562. const CPubKey& pubkey = key_pair.second.first;
  1563. const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
  1564. CKey key;
  1565. DecryptKey(m_storage.GetEncryptionKey(), crypted_secret, pubkey, key);
  1566. keys[pubkey.GetID()] = key;
  1567. }
  1568. return keys;
  1569. }
  1570. return m_map_keys;
  1571. }
  1572. bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
  1573. {
  1574. LOCK(cs_desc_man);
  1575. unsigned int target_size;
  1576. if (size > 0) {
  1577. target_size = size;
  1578. } else {
  1579. target_size = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
  1580. }
  1581. // Calculate the new range_end
  1582. int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
  1583. // If the descriptor is not ranged, we actually just want to fill the first cache item
  1584. if (!m_wallet_descriptor.descriptor->IsRange()) {
  1585. new_range_end = 1;
  1586. m_wallet_descriptor.range_end = 1;
  1587. m_wallet_descriptor.range_start = 0;
  1588. }
  1589. FlatSigningProvider provider;
  1590. provider.keys = GetKeys();
  1591. WalletBatch batch(m_storage.GetDatabase());
  1592. uint256 id = GetID();
  1593. for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
  1594. FlatSigningProvider out_keys;
  1595. std::vector<CScript> scripts_temp;
  1596. DescriptorCache temp_cache;
  1597. // Maybe we have a cached xpub and we can expand from the cache first
  1598. if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
  1599. if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
  1600. }
  1601. // Add all of the scriptPubKeys to the scriptPubKey set
  1602. for (const CScript& script : scripts_temp) {
  1603. m_map_script_pub_keys[script] = i;
  1604. }
  1605. for (const auto& pk_pair : out_keys.pubkeys) {
  1606. const CPubKey& pubkey = pk_pair.second;
  1607. if (m_map_pubkeys.count(pubkey) != 0) {
  1608. // We don't need to give an error here.
  1609. // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
  1610. continue;
  1611. }
  1612. m_map_pubkeys[pubkey] = i;
  1613. }
  1614. // Merge and write the cache
  1615. DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
  1616. if (!batch.WriteDescriptorCacheItems(id, new_items)) {
  1617. throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
  1618. }
  1619. m_max_cached_index++;
  1620. }
  1621. m_wallet_descriptor.range_end = new_range_end;
  1622. batch.WriteDescriptor(GetID(), m_wallet_descriptor);
  1623. // By this point, the cache size should be the size of the entire range
  1624. assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
  1625. NotifyCanGetAddressesChanged();
  1626. return true;
  1627. }
  1628. std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
  1629. {
  1630. LOCK(cs_desc_man);
  1631. std::vector<WalletDestination> result;
  1632. if (IsMine(script)) {
  1633. int32_t index = m_map_script_pub_keys[script];
  1634. if (index >= m_wallet_descriptor.next_index) {
  1635. WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
  1636. auto out_keys = std::make_unique<FlatSigningProvider>();
  1637. std::vector<CScript> scripts_temp;
  1638. while (index >= m_wallet_descriptor.next_index) {
  1639. if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
  1640. throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
  1641. }
  1642. CTxDestination dest;
  1643. ExtractDestination(scripts_temp[0], dest);
  1644. result.push_back({dest, std::nullopt});
  1645. m_wallet_descriptor.next_index++;
  1646. }
  1647. }
  1648. if (!TopUp()) {
  1649. WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
  1650. }
  1651. }
  1652. return result;
  1653. }
  1654. void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
  1655. {
  1656. LOCK(cs_desc_man);
  1657. WalletBatch batch(m_storage.GetDatabase());
  1658. if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
  1659. throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
  1660. }
  1661. }
  1662. bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
  1663. {
  1664. AssertLockHeld(cs_desc_man);
  1665. assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
  1666. // Check if provided key already exists
  1667. if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
  1668. m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
  1669. return true;
  1670. }
  1671. if (m_storage.HasEncryptionKeys()) {
  1672. if (m_storage.IsLocked()) {
  1673. return false;
  1674. }
  1675. std::vector<unsigned char> crypted_secret;
  1676. CKeyingMaterial secret(key.begin(), key.end());
  1677. if (!EncryptSecret(m_storage.GetEncryptionKey(), secret, pubkey.GetHash(), crypted_secret)) {
  1678. return false;
  1679. }
  1680. m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
  1681. return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
  1682. } else {
  1683. m_map_keys[pubkey.GetID()] = key;
  1684. return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
  1685. }
  1686. }
  1687. bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(const CExtKey& master_key, OutputType addr_type, bool internal)
  1688. {
  1689. LOCK(cs_desc_man);
  1690. assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
  1691. // Ignore when there is already a descriptor
  1692. if (m_wallet_descriptor.descriptor) {
  1693. return false;
  1694. }
  1695. int64_t creation_time = GetTime();
  1696. std::string xpub = EncodeExtPubKey(master_key.Neuter());
  1697. // Build descriptor string
  1698. std::string desc_prefix;
  1699. std::string desc_suffix = "/*)";
  1700. switch (addr_type) {
  1701. case OutputType::LEGACY: {
  1702. desc_prefix = "pkh(" + xpub + "/44'";
  1703. break;
  1704. }
  1705. case OutputType::P2SH_SEGWIT: {
  1706. desc_prefix = "sh(wpkh(" + xpub + "/49'";
  1707. desc_suffix += ")";
  1708. break;
  1709. }
  1710. case OutputType::BECH32: {
  1711. desc_prefix = "wpkh(" + xpub + "/84'";
  1712. break;
  1713. }
  1714. case OutputType::BECH32M: {
  1715. desc_prefix = "tr(" + xpub + "/86'";
  1716. break;
  1717. }
  1718. } // no default case, so the compiler can warn about missing cases
  1719. assert(!desc_prefix.empty());
  1720. // Mainnet derives at 0', testnet and regtest derive at 1'
  1721. if (Params().IsTestChain()) {
  1722. desc_prefix += "/1'";
  1723. } else {
  1724. desc_prefix += "/0'";
  1725. }
  1726. std::string internal_path = internal ? "/1" : "/0";
  1727. std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
  1728. // Make the descriptor
  1729. FlatSigningProvider keys;
  1730. std::string error;
  1731. std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
  1732. WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
  1733. m_wallet_descriptor = w_desc;
  1734. // Store the master private key, and descriptor
  1735. WalletBatch batch(m_storage.GetDatabase());
  1736. if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
  1737. throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
  1738. }
  1739. if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
  1740. throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
  1741. }
  1742. // TopUp
  1743. TopUp();
  1744. m_storage.UnsetBlankWalletFlag(batch);
  1745. return true;
  1746. }
  1747. bool DescriptorScriptPubKeyMan::IsHDEnabled() const
  1748. {
  1749. LOCK(cs_desc_man);
  1750. return m_wallet_descriptor.descriptor->IsRange();
  1751. }
  1752. bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
  1753. {
  1754. // We can only give out addresses from descriptors that are single type (not combo), ranged,
  1755. // and either have cached keys or can generate more keys (ignoring encryption)
  1756. LOCK(cs_desc_man);
  1757. return m_wallet_descriptor.descriptor->IsSingleType() &&
  1758. m_wallet_descriptor.descriptor->IsRange() &&
  1759. (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
  1760. }
  1761. bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
  1762. {
  1763. LOCK(cs_desc_man);
  1764. return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
  1765. }
  1766. std::optional<int64_t> DescriptorScriptPubKeyMan::GetOldestKeyPoolTime() const
  1767. {
  1768. // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
  1769. return std::nullopt;
  1770. }
  1771. unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
  1772. {
  1773. LOCK(cs_desc_man);
  1774. return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
  1775. }
  1776. int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
  1777. {
  1778. LOCK(cs_desc_man);
  1779. return m_wallet_descriptor.creation_time;
  1780. }
  1781. std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
  1782. {
  1783. LOCK(cs_desc_man);
  1784. // Find the index of the script
  1785. auto it = m_map_script_pub_keys.find(script);
  1786. if (it == m_map_script_pub_keys.end()) {
  1787. return nullptr;
  1788. }
  1789. int32_t index = it->second;
  1790. return GetSigningProvider(index, include_private);
  1791. }
  1792. std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
  1793. {
  1794. LOCK(cs_desc_man);
  1795. // Find index of the pubkey
  1796. auto it = m_map_pubkeys.find(pubkey);
  1797. if (it == m_map_pubkeys.end()) {
  1798. return nullptr;
  1799. }
  1800. int32_t index = it->second;
  1801. // Always try to get the signing provider with private keys. This function should only be called during signing anyways
  1802. return GetSigningProvider(index, true);
  1803. }
  1804. std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
  1805. {
  1806. AssertLockHeld(cs_desc_man);
  1807. // Get the scripts, keys, and key origins for this script
  1808. std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
  1809. std::vector<CScript> scripts_temp;
  1810. if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
  1811. if (HavePrivateKeys() && include_private) {
  1812. FlatSigningProvider master_provider;
  1813. master_provider.keys = GetKeys();
  1814. m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
  1815. }
  1816. return out_keys;
  1817. }
  1818. std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
  1819. {
  1820. return GetSigningProvider(script, false);
  1821. }
  1822. bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
  1823. {
  1824. return IsMine(script);
  1825. }
  1826. bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
  1827. {
  1828. std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
  1829. for (const auto& coin_pair : coins) {
  1830. std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
  1831. if (!coin_keys) {
  1832. continue;
  1833. }
  1834. *keys = Merge(*keys, *coin_keys);
  1835. }
  1836. return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
  1837. }
  1838. SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
  1839. {
  1840. std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
  1841. if (!keys) {
  1842. return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
  1843. }
  1844. CKey key;
  1845. if (!keys->GetKey(ToKeyID(pkhash), key)) {
  1846. return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
  1847. }
  1848. if (!MessageSign(key, message, str_sig)) {
  1849. return SigningResult::SIGNING_FAILED;
  1850. }
  1851. return SigningResult::OK;
  1852. }
  1853. TransactionError DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
  1854. {
  1855. if (n_signed) {
  1856. *n_signed = 0;
  1857. }
  1858. for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
  1859. const CTxIn& txin = psbtx.tx->vin[i];
  1860. PSBTInput& input = psbtx.inputs.at(i);
  1861. if (PSBTInputSigned(input)) {
  1862. continue;
  1863. }
  1864. // Get the Sighash type
  1865. if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
  1866. return TransactionError::SIGHASH_MISMATCH;
  1867. }
  1868. // Get the scriptPubKey to know which SigningProvider to use
  1869. CScript script;
  1870. if (!input.witness_utxo.IsNull()) {
  1871. script = input.witness_utxo.scriptPubKey;
  1872. } else if (input.non_witness_utxo) {
  1873. if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
  1874. return TransactionError::MISSING_INPUTS;
  1875. }
  1876. script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
  1877. } else {
  1878. // There's no UTXO so we can just skip this now
  1879. continue;
  1880. }
  1881. SignatureData sigdata;
  1882. input.FillSignatureData(sigdata);
  1883. std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
  1884. std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, sign);
  1885. if (script_keys) {
  1886. *keys = Merge(*keys, *script_keys);
  1887. } else {
  1888. // Maybe there are pubkeys listed that we can sign for
  1889. script_keys = std::make_unique<FlatSigningProvider>();
  1890. for (const auto& pk_pair : input.hd_keypaths) {
  1891. const CPubKey& pubkey = pk_pair.first;
  1892. std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
  1893. if (pk_keys) {
  1894. *keys = Merge(*keys, *pk_keys);
  1895. }
  1896. }
  1897. }
  1898. SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
  1899. bool signed_one = PSBTInputSigned(input);
  1900. if (n_signed && (signed_one || !sign)) {
  1901. // If sign is false, we assume that we _could_ sign if we get here. This
  1902. // will never have false negatives; it is hard to tell under what i
  1903. // circumstances it could have false positives.
  1904. (*n_signed)++;
  1905. }
  1906. }
  1907. // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
  1908. for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
  1909. std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
  1910. if (!keys) {
  1911. continue;
  1912. }
  1913. UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs), psbtx, i);
  1914. }
  1915. return TransactionError::OK;
  1916. }
  1917. std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
  1918. {
  1919. std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
  1920. if (provider) {
  1921. KeyOriginInfo orig;
  1922. CKeyID key_id = GetKeyForDestination(*provider, dest);
  1923. if (provider->GetKeyOrigin(key_id, orig)) {
  1924. LOCK(cs_desc_man);
  1925. std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
  1926. meta->key_origin = orig;
  1927. meta->has_key_origin = true;
  1928. meta->nCreateTime = m_wallet_descriptor.creation_time;
  1929. return meta;
  1930. }
  1931. }
  1932. return nullptr;
  1933. }
  1934. uint256 DescriptorScriptPubKeyMan::GetID() const
  1935. {
  1936. LOCK(cs_desc_man);
  1937. std::string desc_str = m_wallet_descriptor.descriptor->ToString();
  1938. uint256 id;
  1939. CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
  1940. return id;
  1941. }
  1942. void DescriptorScriptPubKeyMan::SetCache(const DescriptorCache& cache)
  1943. {
  1944. LOCK(cs_desc_man);
  1945. m_wallet_descriptor.cache = cache;
  1946. for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
  1947. FlatSigningProvider out_keys;
  1948. std::vector<CScript> scripts_temp;
  1949. if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
  1950. throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
  1951. }
  1952. // Add all of the scriptPubKeys to the scriptPubKey set
  1953. for (const CScript& script : scripts_temp) {
  1954. if (m_map_script_pub_keys.count(script) != 0) {
  1955. throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
  1956. }
  1957. m_map_script_pub_keys[script] = i;
  1958. }
  1959. for (const auto& pk_pair : out_keys.pubkeys) {
  1960. const CPubKey& pubkey = pk_pair.second;
  1961. if (m_map_pubkeys.count(pubkey) != 0) {
  1962. // We don't need to give an error here.
  1963. // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
  1964. continue;
  1965. }
  1966. m_map_pubkeys[pubkey] = i;
  1967. }
  1968. m_max_cached_index++;
  1969. }
  1970. }
  1971. bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
  1972. {
  1973. LOCK(cs_desc_man);
  1974. m_map_keys[key_id] = key;
  1975. return true;
  1976. }
  1977. bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
  1978. {
  1979. LOCK(cs_desc_man);
  1980. if (!m_map_keys.empty()) {
  1981. return false;
  1982. }
  1983. m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
  1984. return true;
  1985. }
  1986. bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
  1987. {
  1988. LOCK(cs_desc_man);
  1989. return m_wallet_descriptor.descriptor != nullptr && desc.descriptor != nullptr && m_wallet_descriptor.descriptor->ToString() == desc.descriptor->ToString();
  1990. }
  1991. void DescriptorScriptPubKeyMan::WriteDescriptor()
  1992. {
  1993. LOCK(cs_desc_man);
  1994. WalletBatch batch(m_storage.GetDatabase());
  1995. if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
  1996. throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
  1997. }
  1998. }
  1999. const WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
  2000. {
  2001. return m_wallet_descriptor;
  2002. }
  2003. const std::vector<CScript> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
  2004. {
  2005. LOCK(cs_desc_man);
  2006. std::vector<CScript> script_pub_keys;
  2007. script_pub_keys.reserve(m_map_script_pub_keys.size());
  2008. for (auto const& script_pub_key: m_map_script_pub_keys) {
  2009. script_pub_keys.push_back(script_pub_key.first);
  2010. }
  2011. return script_pub_keys;
  2012. }
  2013. bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
  2014. {
  2015. LOCK(cs_desc_man);
  2016. FlatSigningProvider provider;
  2017. provider.keys = GetKeys();
  2018. if (priv) {
  2019. // For the private version, always return the master key to avoid
  2020. // exposing child private keys. The risk implications of exposing child
  2021. // private keys together with the parent xpub may be non-obvious for users.
  2022. return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
  2023. }
  2024. return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
  2025. }
  2026. void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
  2027. {
  2028. LOCK(cs_desc_man);
  2029. if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
  2030. return;
  2031. }
  2032. // Skip if we have the last hardened xpub cache
  2033. if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
  2034. return;
  2035. }
  2036. // Expand the descriptor
  2037. FlatSigningProvider provider;
  2038. provider.keys = GetKeys();
  2039. FlatSigningProvider out_keys;
  2040. std::vector<CScript> scripts_temp;
  2041. DescriptorCache temp_cache;
  2042. if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
  2043. throw std::runtime_error("Unable to expand descriptor");
  2044. }
  2045. // Cache the last hardened xpubs
  2046. DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
  2047. if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
  2048. throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
  2049. }
  2050. }
  2051. void DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor)
  2052. {
  2053. LOCK(cs_desc_man);
  2054. std::string error;
  2055. if (!CanUpdateToWalletDescriptor(descriptor, error)) {
  2056. throw std::runtime_error(std::string(__func__) + ": " + error);
  2057. }
  2058. m_map_pubkeys.clear();
  2059. m_map_script_pub_keys.clear();
  2060. m_max_cached_index = -1;
  2061. m_wallet_descriptor = descriptor;
  2062. }
  2063. bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
  2064. {
  2065. LOCK(cs_desc_man);
  2066. if (!HasWalletDescriptor(descriptor)) {
  2067. error = "can only update matching descriptor";
  2068. return false;
  2069. }
  2070. if (descriptor.range_start > m_wallet_descriptor.range_start ||
  2071. descriptor.range_end < m_wallet_descriptor.range_end) {
  2072. // Use inclusive range for error
  2073. error = strprintf("new range must include current range = [%d,%d]",
  2074. m_wallet_descriptor.range_start,
  2075. m_wallet_descriptor.range_end - 1);
  2076. return false;
  2077. }
  2078. return true;
  2079. }
  2080. } // namespace wallet