PageRenderTime 195ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/src/wallet/scriptpubkeyman.cpp

https://github.com/bitcoin/bitcoin
C++ | 2363 lines | 1903 code | 283 blank | 177 comment | 404 complexity | 84cddb1f7e11276cd2c4dccef12359ca MD5 | raw file

Large files files are truncated, but you can click here to view the full 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) {

Large files files are truncated, but you can click here to view the full file