{"metadata": {"vulnerability": "CVE-2012-1909", "count": 14, "kinds": {"milestone": 4, "sighting": 1, "kev": 0, "other": 9}, "linked_omitted": 0}, "data": [{"timestamp": "2012-03-26T00:00:00Z", "date_only": false, "value": "2012-03-26T00:00:00.000Z", "kind": "milestone", "label": "Reserved", "source": "cvelistv5", "record": "CVE-2012-1909", "field": "cveMetadata.dateReserved"}, {"timestamp": "2012-08-06T16:00:00Z", "date_only": false, "value": "2012-08-06T16:00:00.000Z", "kind": "milestone", "label": "Published", "source": "cvelistv5", "record": "CVE-2012-1909", "field": "cveMetadata.datePublished", "metric_role": "disclosure", "metric_basis": "recorded_event"}, {"timestamp": "2012-08-06T16:00:00Z", "date_only": false, "value": "2012-08-06T16:00:00.000Z", "kind": "other", "label": "Updated", "source": "cvelistv5 / mitre", "record": "CVE-2012-1909", "field": "containers.cna.providerMetadata.dateUpdated"}, {"timestamp": "2012-08-06T16:55:00Z", "date_only": false, "value": "2012-08-06T16:55:00Z", "kind": "other", "label": "Nvd published at", "source": "github \u00b7 GHSA-77F9-3FQP-C88C", "record": "GHSA-77F9-3FQP-C88C", "field": "database_specific.nvd_published_at", "linked_record": true}, {"timestamp": "2012-08-06T16:55:00Z", "date_only": false, "value": "2012-08-06T16:55Z", "kind": "other", "label": "Published Date", "source": "gsd \u00b7 GSD-2012-1909", "record": "GSD-2012-1909", "field": "namespaces.nvd.nist.gov.publishedDate", "linked_record": true}, {"timestamp": "2012-08-06T16:55:01.400Z", "date_only": false, "value": "2012-08-06T16:55:01.400", "kind": "milestone", "label": "Published", "source": "fkie_nvd \u00b7 FKIE_CVE-2012-1909", "record": "FKIE_CVE-2012-1909", "field": "published", "metric_role": "disclosure", "metric_basis": "recorded_event", "linked_record": true}, {"timestamp": "2020-03-18T17:37:00Z", "date_only": false, "value": "2020-03-18T17:37Z", "kind": "other", "label": "Last Modified Date", "source": "gsd \u00b7 GSD-2012-1909", "record": "GSD-2012-1909", "field": "namespaces.nvd.nist.gov.lastModifiedDate", "linked_record": true}, {"timestamp": "2022-05-13T01:27:55Z", "date_only": false, "value": "2022-05-13T01:27:55Z", "kind": "milestone", "label": "Published", "source": "github \u00b7 GHSA-77F9-3FQP-C88C", "record": "GHSA-77F9-3FQP-C88C", "field": "published", "metric_role": "disclosure", "metric_basis": "recorded_event", "linked_record": true}, {"timestamp": "2022-05-13T01:27:55Z", "date_only": false, "value": "2022-05-13T01:27:55Z", "kind": "other", "label": "Updated", "source": "github \u00b7 GHSA-77F9-3FQP-C88C", "record": "GHSA-77F9-3FQP-C88C", "field": "modified", "linked_record": true}, {"timestamp": "2023-12-13T01:20:18.270Z", "date_only": false, "value": "2023-12-13T01:20:18.270284Z", "kind": "other", "label": "Updated", "source": "gsd \u00b7 GSD-2012-1909", "record": "GSD-2012-1909", "field": "gsd.osvSchema.modified", "linked_record": true}, {"timestamp": "2024-08-06T19:17:27.004Z", "date_only": false, "value": "2024-08-06T19:17:27.004Z", "kind": "other", "label": "Updated", "source": "cvelistv5 / CVE", "record": "CVE-2012-1909", "field": "containers.adp.0.providerMetadata.dateUpdated"}, {"timestamp": "2024-09-17T00:31:19.043Z", "date_only": false, "value": "2024-09-17T00:31:19.043Z", "kind": "other", "label": "Updated", "source": "cvelistv5", "record": "CVE-2012-1909", "field": "cveMetadata.dateUpdated"}, {"timestamp": "2026-05-06T07:21:34Z", "date_only": false, "value": "2026-05-06T07:21:34.000000Z", "kind": "sighting", "label": "Seen", "source": "https://gist.github.com/LarryRuane/7a1ea41744a1068e069a91304ca29c4a", "record": "CVE-2012-1909", "field": "creation_timestamp", "uuid": "1d32c554-6467-4ac2-a206-ed5005cd437f", "content": "diff --git a/src/coins.cpp b/src/coins.cpp\nindex c403e006c8..fa829a267f 100644\n--- a/src/coins.cpp\n+++ b/src/coins.cpp\n@@ -1,409 +1,439 @@\n // Copyright (c) 2012-present The Bitcoin Core developers\n // Distributed under the MIT software license, see the accompanying\n // file COPYING or http://www.opensource.org/licenses/mit-license.php.\n \n #include \n \n #include \n #include \n #include \n #include \n #include \n \n TRACEPOINT_SEMAPHORE(utxocache, add);\n TRACEPOINT_SEMAPHORE(utxocache, spent);\n TRACEPOINT_SEMAPHORE(utxocache, uncache);\n \n CoinsViewEmpty&amp; CoinsViewEmpty::Get()\n {\n     static CoinsViewEmpty instance;\n     return instance;\n }\n \n std::optional CCoinsViewCache::PeekCoin(const COutPoint&amp; outpoint) const\n {\n     if (auto it{cacheCoins.find(outpoint)}; it != cacheCoins.end()) {\n-        return it-&gt;second.coin.IsSpent() ? std::nullopt : std::optional{it-&gt;second.coin};\n+        return it-&gt;second.coin ? std::optional{*it-&gt;second.coin} : std::nullopt;\n     }\n     return base-&gt;PeekCoin(outpoint);\n }\n \n CCoinsViewCache::CCoinsViewCache(CCoinsView* in_base, bool deterministic) :\n     CCoinsViewBacked(in_base), m_deterministic(deterministic),\n     cacheCoins(0, SaltedOutpointHasher(/*deterministic=*/deterministic), CCoinsMap::key_equal{}, &amp;m_cache_coins_memory_resource)\n {\n     m_sentinel.second.SelfRef(m_sentinel);\n }\n \n size_t CCoinsViewCache::DynamicMemoryUsage() const {\n     return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;\n }\n \n+//! Move a coin into a cache entry, overwriting any existing coin.\n+void CCoinsViewCache::MoveCoin(CCoinsCacheEntry&amp; dest_entry, Coin&amp;&amp; source_coin) const\n+{\n+    if (dest_entry.coin) {\n+        // Deconstruct the existing unspent coin, but for efficiency use its existing memory for the new coin.\n+        Assume(TrySub(cachedCoinsUsage, dest_entry.coin-&gt;DynamicMemoryUsage()));\n+        dest_entry.coin-&gt;~Coin();\n+    } else {\n+        // Existing spent (non-)coin will now become the given unspent coin.\n+        dest_entry.coin = static_cast(m_cache_coins_memory_resource.Allocate(sizeof(Coin), alignof(Coin)));\n+    }\n+    new (dest_entry.coin) Coin(std::move(source_coin));\n+    cachedCoinsUsage += dest_entry.coin-&gt;DynamicMemoryUsage();\n+}\n+\n+//! Free (deallocate) a coin, this cache entry becomes spent (coin is nullptr).\n+void CCoinsViewCache::FreeCoin(CCoinsCacheEntry&amp; entry) const noexcept\n+{\n+    assert(entry.coin);\n+    Assume(TrySub(cachedCoinsUsage, entry.coin-&gt;DynamicMemoryUsage()));\n+    entry.coin-&gt;~Coin();\n+    m_cache_coins_memory_resource.Deallocate(entry.coin, sizeof(Coin), alignof(Coin));\n+    entry.coin = nullptr;\n+}\n+\n+void CCoinsViewCache::FreeAllCoins() const noexcept\n+{\n+    for (auto&amp; entry : cacheCoins) if (entry.second.coin) FreeCoin(entry.second);\n+}\n+\n std::optional CCoinsViewCache::FetchCoinFromBase(const COutPoint&amp; outpoint) const\n {\n     return base-&gt;GetCoin(outpoint);\n }\n \n CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &amp;outpoint) const {\n     const auto [ret, inserted] = cacheCoins.try_emplace(outpoint);\n     if (inserted) {\n         if (auto coin{FetchCoinFromBase(outpoint)}) {\n-            ret-&gt;second.coin = std::move(*coin);\n-            cachedCoinsUsage += ret-&gt;second.coin.DynamicMemoryUsage();\n-            Assert(!ret-&gt;second.coin.IsSpent());\n+            Assert(!coin.value().IsSpent());\n+            MoveCoin(ret-&gt;second, std::move(coin.value()));\n         } else {\n             cacheCoins.erase(ret);\n             return cacheCoins.end();\n         }\n     }\n     return ret;\n }\n \n std::optional CCoinsViewCache::GetCoin(const COutPoint&amp; outpoint) const\n {\n-    if (auto it{FetchCoin(outpoint)}; it != cacheCoins.end() &amp;&amp; !it-&gt;second.coin.IsSpent()) return it-&gt;second.coin;\n+    if (auto it{FetchCoin(outpoint)}; it != cacheCoins.end() &amp;&amp; it-&gt;second.coin &amp;&amp; !it-&gt;second.coin-&gt;IsSpent()) return *it-&gt;second.coin;\n     return std::nullopt;\n }\n \n void CCoinsViewCache::AddCoin(const COutPoint &amp;outpoint, Coin&amp;&amp; coin, bool possible_overwrite) {\n     assert(!coin.IsSpent());\n     if (coin.out.scriptPubKey.IsUnspendable()) return;\n     CCoinsMap::iterator it;\n     bool inserted;\n     std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple&lt;&gt;());\n     bool fresh = false;\n     if (!possible_overwrite) {\n-        if (!it-&gt;second.coin.IsSpent()) {\n+        if (!it-&gt;second.IsSpent()) {\n             throw std::logic_error(\"Attempted to overwrite an unspent coin (when possible_overwrite is false)\");\n         }\n         // If the coin exists in this cache as a spent coin and is DIRTY, then\n         // its spentness hasn't been flushed to the parent cache. We're\n         // re-adding the coin to this cache now but we can't mark it as FRESH.\n         // If we mark it FRESH and then spend it before the cache is flushed\n         // we would remove it from this cache and would never flush spentness\n         // to the parent cache.\n         //\n         // Re-adding a spent coin can happen in the case of a re-org (the coin\n         // is 'spent' when the block adding it is disconnected and then\n         // re-added when it is also added in a newly connected block).\n         //\n         // If the coin doesn't exist in the current cache, or is spent but not\n         // DIRTY, then it can be marked FRESH.\n         fresh = !it-&gt;second.IsDirty();\n     }\n     if (!inserted) {\n         Assume(TrySub(m_dirty_count, it-&gt;second.IsDirty()));\n-        Assume(TrySub(cachedCoinsUsage, it-&gt;second.coin.DynamicMemoryUsage()));\n     }\n-    it-&gt;second.coin = std::move(coin);\n+    MoveCoin(it-&gt;second, std::move(coin));\n     CCoinsCacheEntry::SetDirty(*it, m_sentinel);\n     ++m_dirty_count;\n     if (fresh) CCoinsCacheEntry::SetFresh(*it, m_sentinel);\n-    cachedCoinsUsage += it-&gt;second.coin.DynamicMemoryUsage();\n     TRACEPOINT(utxocache, add,\n            outpoint.hash.data(),\n            (uint32_t)outpoint.n,\n-           (uint32_t)it-&gt;second.coin.nHeight,\n-           (int64_t)it-&gt;second.coin.out.nValue,\n-           (bool)it-&gt;second.coin.IsCoinBase());\n+           (uint32_t)it-&gt;second.coin-&gt;nHeight,\n+           (int64_t)it-&gt;second.coin-&gt;out.nValue,\n+           (bool)it-&gt;second.coin-&gt;IsCoinBase());\n }\n \n void CCoinsViewCache::EmplaceCoinInternalDANGER(COutPoint&amp;&amp; outpoint, Coin&amp;&amp; coin) {\n-    const auto mem_usage{coin.DynamicMemoryUsage()};\n-    auto [it, inserted] = cacheCoins.try_emplace(std::move(outpoint), std::move(coin));\n+    auto [it, inserted] = cacheCoins.try_emplace(std::move(outpoint));\n     if (inserted) {\n+        MoveCoin(it-&gt;second, std::move(coin));\n         CCoinsCacheEntry::SetDirty(*it, m_sentinel);\n         ++m_dirty_count;\n-        cachedCoinsUsage += mem_usage;\n     }\n }\n \n void AddCoins(CCoinsViewCache&amp; cache, const CTransaction &amp;tx, int nHeight, bool check_for_overwrite) {\n     bool fCoinbase = tx.IsCoinBase();\n     const Txid&amp; txid = tx.GetHash();\n     for (size_t i = 0; i &lt; tx.vout.size(); ++i) {\n         bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;\n         // Coinbase transactions can always be overwritten, in order to correctly\n         // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.\n         cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);\n     }\n }\n \n bool CCoinsViewCache::SpendCoin(const COutPoint &amp;outpoint, Coin* moveout) {\n     CCoinsMap::iterator it = FetchCoin(outpoint);\n     if (it == cacheCoins.end()) return false;\n     Assume(TrySub(m_dirty_count, it-&gt;second.IsDirty()));\n-    Assume(TrySub(cachedCoinsUsage, it-&gt;second.coin.DynamicMemoryUsage()));\n     TRACEPOINT(utxocache, spent,\n            outpoint.hash.data(),\n            (uint32_t)outpoint.n,\n-           (uint32_t)it-&gt;second.coin.nHeight,\n-           (int64_t)it-&gt;second.coin.out.nValue,\n-           (bool)it-&gt;second.coin.IsCoinBase());\n+           (uint32_t)(it-&gt;second.coin ? it-&gt;second.coin-&gt;.nHeight : 0),\n+           (int64_t)(it-&gt;second.coin ? it-&gt;second.coin-&gt;.out.nValue : -1),\n+           (bool)(it-&gt;second.coin ? it-&gt;second.coin-&gt;IsCoinBase() : false));\n     if (moveout) {\n-        *moveout = std::move(it-&gt;second.coin);\n+        *moveout = std::move(it-&gt;second.coin ? *it-&gt;second.coin : Coin{});\n     }\n+    if (it-&gt;second.coin) FreeCoin(it-&gt;second);\n     if (it-&gt;second.IsFresh()) {\n         cacheCoins.erase(it);\n     } else {\n         CCoinsCacheEntry::SetDirty(*it, m_sentinel);\n         ++m_dirty_count;\n-        it-&gt;second.coin.Clear();\n     }\n     return true;\n }\n \n static const Coin coinEmpty;\n \n const Coin&amp; CCoinsViewCache::AccessCoin(const COutPoint &amp;outpoint) const {\n     CCoinsMap::const_iterator it = FetchCoin(outpoint);\n-    if (it == cacheCoins.end()) {\n+    if (it == cacheCoins.end() || !it-&gt;second.coin) {\n         return coinEmpty;\n     } else {\n-        return it-&gt;second.coin;\n+        return *it-&gt;second.coin;\n     }\n }\n \n bool CCoinsViewCache::HaveCoin(const COutPoint&amp; outpoint) const\n {\n     CCoinsMap::const_iterator it = FetchCoin(outpoint);\n-    return (it != cacheCoins.end() &amp;&amp; !it-&gt;second.coin.IsSpent());\n+    return it != cacheCoins.end() &amp;&amp; !it-&gt;second.IsSpent();\n }\n \n bool CCoinsViewCache::HaveCoinInCache(const COutPoint &amp;outpoint) const {\n     CCoinsMap::const_iterator it = cacheCoins.find(outpoint);\n-    return (it != cacheCoins.end() &amp;&amp; !it-&gt;second.coin.IsSpent());\n+    return it != cacheCoins.end() &amp;&amp; !it-&gt;second.IsSpent();\n }\n \n uint256 CCoinsViewCache::GetBestBlock() const {\n     if (m_block_hash.IsNull())\n         m_block_hash = base-&gt;GetBestBlock();\n     return m_block_hash;\n }\n \n void CCoinsViewCache::SetBestBlock(const uint256&amp; in_block_hash)\n {\n     m_block_hash = in_block_hash;\n }\n \n void CCoinsViewCache::BatchWrite(CoinsViewCacheCursor&amp; cursor, const uint256&amp; in_block_hash)\n {\n     for (auto it{cursor.Begin()}; it != cursor.End(); it = cursor.NextAndMaybeErase(*it)) {\n+        CCoinsCacheEntry&amp; source_entry{it-&gt;second};\n         if (!it-&gt;second.IsDirty()) { // TODO a cursor can only contain dirty entries\n             continue;\n         }\n         auto [itUs, inserted]{cacheCoins.try_emplace(it-&gt;first)};\n+        CCoinsCacheEntry&amp; dest_entry{itUs-&gt;second};\n+        const auto MoveOrCopyCoin{[this, &amp;cursor, &amp;source_entry, &amp;dest_entry]() -&gt; void {\n+            if (cursor.WillClear()) {\n+                // Since this entry will be erased,\n+                // we can move the coin into us instead of copying it\n+                MoveCoin(dest_entry, std::move(*source_entry.coin));\n+                source_entry.coin = nullptr;\n+            } else {\n+                // Make a full copy, leaving the existing coin unchanged.\n+                // Note that if source_entry.coin is nullptr (spent), dest_entry\n+                // is already initialized correctly as a spent coin.\n+                Coin source_coin(*source_entry.coin);\n+                MoveCoin(dest_entry, std::move(source_coin));\n+            }\n+        }};\n         if (inserted) {\n-            if (it-&gt;second.IsFresh() &amp;&amp; it-&gt;second.coin.IsSpent()) {\n+            if (source_entry.IsFresh() &amp;&amp; source_entry.IsSpent()) {\n+                if (dest_entry.coin) FreeCoin(dest_entry);\n                 cacheCoins.erase(itUs); // TODO fresh coins should have been removed at spend\n             } else {\n                 // The parent cache does not have an entry, while the child cache does.\n                 // Move the data up and mark it as dirty.\n-                CCoinsCacheEntry&amp; entry{itUs-&gt;second};\n-                assert(entry.coin.DynamicMemoryUsage() == 0);\n-                if (cursor.WillErase(*it)) {\n-                    // Since this entry will be erased,\n-                    // we can move the coin into us instead of copying it\n-                    entry.coin = std::move(it-&gt;second.coin);\n-                } else {\n-                    entry.coin = it-&gt;second.coin;\n-                }\n+                if (source_entry.coin) MoveOrCopyCoin();\n                 CCoinsCacheEntry::SetDirty(*itUs, m_sentinel);\n                 ++m_dirty_count;\n-                cachedCoinsUsage += entry.coin.DynamicMemoryUsage();\n                 // We can mark it FRESH in the parent if it was FRESH in the child\n                 // Otherwise it might have just been flushed from the parent's cache\n                 // and already exist in the grandparent\n-                if (it-&gt;second.IsFresh()) CCoinsCacheEntry::SetFresh(*itUs, m_sentinel);\n+                if (source_entry.IsFresh()) CCoinsCacheEntry::SetFresh(*itUs, m_sentinel);\n             }\n         } else {\n             // Found the entry in the parent cache\n-            if (it-&gt;second.IsFresh() &amp;&amp; !itUs-&gt;second.coin.IsSpent()) {\n+            if (source_entry.IsFresh() &amp;&amp; !dest_entry.IsSpent()) {\n                 // The coin was marked FRESH in the child cache, but the coin\n                 // exists in the parent cache. If this ever happens, it means\n                 // the FRESH flag was misapplied and there is a logic error in\n                 // the calling code.\n                 throw std::logic_error(\"FRESH flag misapplied to coin that exists in parent cache\");\n             }\n \n-            if (itUs-&gt;second.IsFresh() &amp;&amp; it-&gt;second.coin.IsSpent()) {\n+            if (dest_entry.IsFresh() &amp;&amp; source_entry.IsSpent()) {\n                 // The grandparent cache does not have an entry, and the coin\n                 // has been spent. We can just delete it from the parent cache.\n-                Assume(TrySub(m_dirty_count, itUs-&gt;second.IsDirty()));\n-                Assume(TrySub(cachedCoinsUsage, itUs-&gt;second.coin.DynamicMemoryUsage()));\n+                Assume(TrySub(m_dirty_count, dest_entry.IsDirty()));\n+                if (dest_entry.coin) FreeCoin(dest_entry);\n                 cacheCoins.erase(itUs);\n             } else {\n                 // A normal modification.\n-                Assume(TrySub(cachedCoinsUsage, itUs-&gt;second.coin.DynamicMemoryUsage()));\n-                if (cursor.WillErase(*it)) {\n-                    // Since this entry will be erased,\n-                    // we can move the coin into us instead of copying it\n-                    itUs-&gt;second.coin = std::move(it-&gt;second.coin);\n-                } else {\n-                    itUs-&gt;second.coin = it-&gt;second.coin;\n-                }\n-                cachedCoinsUsage += itUs-&gt;second.coin.DynamicMemoryUsage();\n-                if (!itUs-&gt;second.IsDirty()) {\n+                if (source_entry.coin) {\n+                    MoveOrCopyCoin();\n+                } else if (dest_entry.coin) FreeCoin(dest_entry);\n+\n+                if (!dest_entry.IsDirty()) {\n                     CCoinsCacheEntry::SetDirty(*itUs, m_sentinel);\n                     ++m_dirty_count;\n                 }\n                 // NOTE: It isn't safe to mark the coin as FRESH in the parent\n                 // cache. If it already existed and was spent in the parent\n                 // cache then marking it FRESH would prevent that spentness\n                 // from being flushed to the grandparent.\n             }\n         }\n     }\n     SetBestBlock(in_block_hash);\n }\n \n void CCoinsViewCache::Flush(bool reallocate_cache)\n {\n-    auto cursor{CoinsViewCacheCursor(m_dirty_count, m_sentinel, cacheCoins, /*will_erase=*/true)};\n+    auto cursor{CoinsViewCacheCursor(m_dirty_count, m_sentinel, cacheCoins, m_cache_coins_memory_resource, /*will_erase=*/true)};\n     base-&gt;BatchWrite(cursor, m_block_hash);\n     Assume(m_dirty_count == 0);\n+    FreeAllCoins();\n     cacheCoins.clear();\n     if (reallocate_cache) {\n         ReallocateCache();\n     }\n     cachedCoinsUsage = 0;\n }\n \n void CCoinsViewCache::Sync()\n {\n-    auto cursor{CoinsViewCacheCursor(m_dirty_count, m_sentinel, cacheCoins, /*will_erase=*/false)};\n+    auto cursor{CoinsViewCacheCursor(m_dirty_count, m_sentinel, cacheCoins, m_cache_coins_memory_resource, /*will_erase=*/false)};\n     base-&gt;BatchWrite(cursor, m_block_hash);\n     Assume(m_dirty_count == 0);\n     if (m_sentinel.second.Next() != &amp;m_sentinel) {\n         /* BatchWrite must clear flags of all entries */\n         throw std::logic_error(\"Not all unspent flagged entries were cleared\");\n     }\n }\n \n void CCoinsViewCache::Reset() noexcept\n {\n+    FreeAllCoins();\n     cacheCoins.clear();\n     cachedCoinsUsage = 0;\n     m_dirty_count = 0;\n     SetBestBlock(uint256::ZERO);\n }\n \n void CCoinsViewCache::Uncache(const COutPoint&amp; hash)\n {\n     CCoinsMap::iterator it = cacheCoins.find(hash);\n     if (it != cacheCoins.end() &amp;&amp; !it-&gt;second.IsDirty()) {\n-        Assume(TrySub(cachedCoinsUsage, it-&gt;second.coin.DynamicMemoryUsage()));\n         TRACEPOINT(utxocache, uncache,\n                hash.hash.data(),\n                (uint32_t)hash.n,\n-               (uint32_t)it-&gt;second.coin.nHeight,\n-               (int64_t)it-&gt;second.coin.out.nValue,\n-               (bool)it-&gt;second.coin.IsCoinBase());\n+               (uint32_t)(it-&gt;second.coin ? it-&gt;second.coin.nHeight : 0),\n+               (int64_t)(it-&gt;second.coin ? it-&gt;second.coin-&gt;out.nValue : -1),\n+               (bool)(it-&gt;second.coin ? it-&gt;second.coin-&gt;IsCoinBase() : false));\n+        if (it-&gt;second.coin) FreeCoin(it-&gt;second);\n         cacheCoins.erase(it);\n     }\n }\n \n unsigned int CCoinsViewCache::GetCacheSize() const {\n     return cacheCoins.size();\n }\n \n bool CCoinsViewCache::HaveInputs(const CTransaction&amp; tx) const\n {\n     if (!tx.IsCoinBase()) {\n         for (unsigned int i = 0; i &lt; tx.vin.size(); i++) {\n             if (!HaveCoin(tx.vin[i].prevout)) {\n                 return false;\n             }\n         }\n     }\n     return true;\n }\n \n void CCoinsViewCache::ReallocateCache()\n {\n     // Cache should be empty when we're calling this.\n     assert(cacheCoins.size() == 0);\n     cacheCoins.~CCoinsMap();\n     m_cache_coins_memory_resource.~CCoinsMapMemoryResource();\n     ::new (&amp;m_cache_coins_memory_resource) CCoinsMapMemoryResource{};\n     ::new (&amp;cacheCoins) CCoinsMap{0, SaltedOutpointHasher{/*deterministic=*/m_deterministic}, CCoinsMap::key_equal{}, &amp;m_cache_coins_memory_resource};\n }\n \n void CCoinsViewCache::SanityCheck() const\n {\n     size_t recomputed_usage = 0;\n     size_t count_dirty = 0;\n     for (const auto&amp; [_, entry] : cacheCoins) {\n-        if (entry.coin.IsSpent()) {\n+        if (entry.IsSpent()) {\n             assert(entry.IsDirty() &amp;&amp; !entry.IsFresh()); // A spent coin must be dirty and cannot be fresh\n         } else {\n             assert(entry.IsDirty() || !entry.IsFresh()); // An unspent coin must not be fresh if not dirty\n         }\n \n         // Recompute cachedCoinsUsage.\n-        recomputed_usage += entry.coin.DynamicMemoryUsage();\n+        if (entry.coin) recomputed_usage += entry.coin-&gt;DynamicMemoryUsage();\n \n         // Count the number of entries we expect in the linked list.\n         if (entry.IsDirty()) ++count_dirty;\n     }\n     // Iterate over the linked list of flagged entries.\n     size_t count_linked = 0;\n     for (auto it = m_sentinel.second.Next(); it != &amp;m_sentinel; it = it-&gt;second.Next()) {\n         // Verify linked list integrity.\n         assert(it-&gt;second.Next()-&gt;second.Prev() == it);\n         assert(it-&gt;second.Prev()-&gt;second.Next() == it);\n         // Verify they are actually flagged.\n         assert(it-&gt;second.IsDirty());\n         // Count the number of entries actually in the list.\n         ++count_linked;\n     }\n     assert(count_dirty == count_linked &amp;&amp; count_dirty == m_dirty_count);\n     assert(recomputed_usage == cachedCoinsUsage);\n }\n \n static const uint64_t MIN_TRANSACTION_OUTPUT_WEIGHT{WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut())};\n static const uint64_t MAX_OUTPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT};\n \n const Coin&amp; AccessByTxid(const CCoinsViewCache&amp; view, const Txid&amp; txid)\n {\n     COutPoint iter(txid, 0);\n     while (iter.n &lt; MAX_OUTPUTS_PER_BLOCK) {\n         const Coin&amp; alternate = view.AccessCoin(iter);\n         if (!alternate.IsSpent()) return alternate;\n         ++iter.n;\n     }\n     return coinEmpty;\n }\n \n template \n static ReturnType ExecuteBackedWrapper(Func func, const std::vector&gt;&amp; err_callbacks)\n {\n     try {\n         return func();\n     } catch(const std::runtime_error&amp; e) {\n         for (const auto&amp; f : err_callbacks) {\n             f();\n         }\n         LogError(\"Error reading from database: %s\\n\", e.what());\n         // Starting the shutdown sequence and returning false to the caller would be\n         // interpreted as 'entry not found' (as opposed to unable to read data), and\n         // could lead to invalid interpretation. Just exit immediately, as we can't\n         // continue anyway, and all writes should be atomic.\n         std::abort();\n     }\n }\n \n std::optional CCoinsViewErrorCatcher::GetCoin(const COutPoint&amp; outpoint) const\n {\n     return ExecuteBackedWrapper&gt;([&amp;]() { return CCoinsViewBacked::GetCoin(outpoint); }, m_err_callbacks);\n }\n \n bool CCoinsViewErrorCatcher::HaveCoin(const COutPoint&amp; outpoint) const\n {\n     return ExecuteBackedWrapper([&amp;]() { return CCoinsViewBacked::HaveCoin(outpoint); }, m_err_callbacks);\n }\n \n std::optional CCoinsViewErrorCatcher::PeekCoin(const COutPoint&amp; outpoint) const\n {\n     return ExecuteBackedWrapper&gt;([&amp;]() { return CCoinsViewBacked::PeekCoin(outpoint); }, m_err_callbacks);\n }\ndiff --git a/src/coins.h b/src/coins.h\nindex ae7f34f465..135ff5381d 100644\n--- a/src/coins.h\n+++ b/src/coins.h\n@@ -1,616 +1,665 @@\n // Copyright (c) 2009-2010 Satoshi Nakamoto\n // Copyright (c) 2009-present The Bitcoin Core developers\n // Distributed under the MIT software license, see the accompanying\n // file COPYING or http://www.opensource.org/licenses/mit-license.php.\n \n #ifndef BITCOIN_COINS_H\n #define BITCOIN_COINS_H\n \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n \n #include \n #include \n \n #include \n #include \n \n /**\n  * A UTXO entry.\n  *\n  * Serialized format:\n  * - VARINT((height &lt;&lt; 1) | (coinbase ? 1 : 0))\n  * - the non-spent CTxOut (via TxOutCompression)\n  */\n class Coin\n {\n public:\n     //! unspent transaction output\n     CTxOut out;\n \n     //! whether containing transaction was a coinbase\n     bool fCoinBase : 1;\n \n     //! at which height this containing transaction was included in the active block chain\n     uint32_t nHeight : 31;\n \n     //! construct a Coin from a CTxOut and height/coinbase information.\n     Coin(CTxOut&amp;&amp; outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}\n     Coin(const CTxOut&amp; outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}\n \n     void Clear() {\n         out.SetNull();\n         fCoinBase = false;\n         nHeight = 0;\n     }\n \n     //! empty constructor\n     Coin() : fCoinBase(false), nHeight(0) { }\n \n     bool IsCoinBase() const {\n         return fCoinBase;\n     }\n \n     template\n     void Serialize(Stream &amp;s) const {\n         assert(!IsSpent());\n         uint32_t code{(uint32_t{nHeight} &lt;&lt; 1) | uint32_t{fCoinBase}};\n         ::Serialize(s, VARINT(code));\n         ::Serialize(s, Using(out));\n     }\n \n     template\n     void Unserialize(Stream &amp;s) {\n         uint32_t code = 0;\n         ::Unserialize(s, VARINT(code));\n         nHeight = code &gt;&gt; 1;\n         fCoinBase = code &amp; 1;\n         ::Unserialize(s, Using(out));\n     }\n \n     /** Either this coin never existed (see e.g. coinEmpty in coins.cpp), or it\n       * did exist and has been spent.\n       */\n     bool IsSpent() const {\n         return out.IsNull();\n     }\n \n     size_t DynamicMemoryUsage() const {\n         return memusage::DynamicUsage(out.scriptPubKey);\n     }\n };\n \n struct CCoinsCacheEntry;\n using CoinsCachePair = std::pair;\n \n /**\n  * A Coin in one level of the coins database caching hierarchy.\n  *\n  * A coin can either be:\n  * - unspent or spent (in which case the Coin object will be nulled out - see Coin.Clear())\n  * - DIRTY or not DIRTY\n  * - FRESH or not FRESH\n  *\n  * Out of these 2^3 = 8 states, only some combinations are valid:\n  * - unspent, FRESH, DIRTY (e.g. a new coin created in the cache)\n  * - unspent, not FRESH, DIRTY (e.g. a coin changed in the cache during a reorg)\n  * - unspent, not FRESH, not DIRTY (e.g. an unspent coin fetched from the parent cache)\n  * - spent, not FRESH, DIRTY (e.g. a coin is spent and spentness needs to be flushed to the parent)\n  */\n struct CCoinsCacheEntry\n {\n private:\n     /**\n      * These are used to create a doubly linked list of flagged entries.\n      * They are set in SetDirty, SetFresh, and unset in SetClean.\n      * A flagged entry is any entry that is either DIRTY, FRESH, or both.\n      *\n      * DIRTY entries are tracked so that only modified entries can be passed to\n      * the parent cache for batch writing. This is a performance optimization\n      * compared to giving all entries in the cache to the parent and having the\n      * parent scan for only modified entries.\n      */\n     CoinsCachePair* m_prev{nullptr};\n     CoinsCachePair* m_next{nullptr};\n     uint8_t m_flags{0};\n \n     //! Adding a flag requires a reference to the sentinel of the flagged pair linked list.\n     static void AddFlags(uint8_t flags, CoinsCachePair&amp; pair, CoinsCachePair&amp; sentinel) noexcept\n     {\n         Assume(flags &amp; (DIRTY | FRESH));\n         if (!pair.second.m_flags) {\n             Assume(!pair.second.m_prev &amp;&amp; !pair.second.m_next);\n             pair.second.m_prev = sentinel.second.m_prev;\n             pair.second.m_next = &amp;sentinel;\n             sentinel.second.m_prev = &amp;pair;\n             pair.second.m_prev-&gt;second.m_next = &amp;pair;\n         }\n         Assume(pair.second.m_prev &amp;&amp; pair.second.m_next);\n         pair.second.m_flags |= flags;\n     }\n \n public:\n-    Coin coin; // The actual cached data.\n+    /**\n+     * Pointer to the actual coin, pool-allocated, nullptr if spent (or freshly initialized).\n+     * */\n+    Coin* coin{nullptr};\n \n     enum Flags {\n         /**\n          * DIRTY means the CCoinsCacheEntry is potentially different from the\n          * version in the parent cache. Failure to mark a coin as DIRTY when\n          * it is potentially different from the parent cache will cause a\n          * consensus failure, since the coin's state won't get written to the\n          * parent when the cache is flushed.\n          */\n         DIRTY = (1 &lt;&lt; 0),\n         /**\n          * FRESH means the parent cache does not have this coin or that it is a\n          * spent coin in the parent cache. If a FRESH coin in the cache is\n          * later spent, it can be deleted entirely and doesn't ever need to be\n          * flushed to the parent. This is a performance optimization. Marking a\n          * coin as FRESH when it exists unspent in the parent cache will cause a\n          * consensus failure, since it might not be deleted from the parent\n          * when this cache is flushed.\n          */\n         FRESH = (1 &lt;&lt; 1),\n     };\n \n     CCoinsCacheEntry() noexcept = default;\n-    explicit CCoinsCacheEntry(Coin&amp;&amp; coin_) noexcept : coin(std::move(coin_)) {}\n     ~CCoinsCacheEntry()\n     {\n+        Assume(coin == nullptr);\n+        if (coin) coin-&gt;~Coin();\n         SetClean();\n     }\n+    // copying an entry would copy the coin pointer!\n+    CCoinsCacheEntry(const CCoinsCacheEntry&amp;) = delete;\n+\n+    // Move Constructor\n+    CCoinsCacheEntry(CCoinsCacheEntry&amp;&amp; other) noexcept \n+        : m_flags(other.m_flags), coin(other.coin)\n+    {\n+        other.coin = nullptr; // Ensure the source is nulled\n+    }\n+\n+    // Move Assignment\n+    CCoinsCacheEntry&amp; operator=(CCoinsCacheEntry&amp;&amp; other) noexcept\n+    {\n+        if (this != &amp;other) {\n+            Assume(!coin);\n+            coin = other.coin;\n+            m_flags = other.m_flags;\n+            other.coin = nullptr;\n+        }\n+        return *this;\n+    }\n \n     static void SetDirty(CoinsCachePair&amp; pair, CoinsCachePair&amp; sentinel) noexcept { AddFlags(DIRTY, pair, sentinel); }\n     static void SetFresh(CoinsCachePair&amp; pair, CoinsCachePair&amp; sentinel) noexcept { AddFlags(FRESH, pair, sentinel); }\n \n     void SetClean() noexcept\n     {\n         if (!m_flags) return;\n         m_next-&gt;second.m_prev = m_prev;\n         m_prev-&gt;second.m_next = m_next;\n         m_flags = 0;\n         m_prev = m_next = nullptr;\n     }\n     bool IsDirty() const noexcept { return m_flags &amp; DIRTY; }\n     bool IsFresh() const noexcept { return m_flags &amp; FRESH; }\n \n+    // It's acceptable for higher-level code to directly test if coin is nullptr.\n+    bool IsSpent() const noexcept\n+    {\n+        return !coin || coin-&gt;IsSpent();\n+    }\n+\n     //! Only call Next when this entry is DIRTY, FRESH, or both\n     CoinsCachePair* Next() const noexcept\n     {\n         Assume(m_flags);\n         return m_next;\n     }\n \n     //! Only call Prev when this entry is DIRTY, FRESH, or both\n     CoinsCachePair* Prev() const noexcept\n     {\n         Assume(m_flags);\n         return m_prev;\n     }\n \n     //! Only use this for initializing the linked list sentinel\n     void SelfRef(CoinsCachePair&amp; pair) noexcept\n     {\n         Assume(&amp;pair.second == this);\n         m_prev = &amp;pair;\n         m_next = &amp;pair;\n         // Set sentinel to DIRTY so we can call Next on it\n         m_flags = DIRTY;\n     }\n };\n \n /**\n  * PoolAllocator's MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size\n  * of 4 pointers. We do not know the exact node size used in the std::unordered_node implementation\n  * because it is implementation defined. Most implementations have an overhead of 1 or 2 pointers,\n  * so nodes can be connected in a linked list, and in some cases the hash value is stored as well.\n  * Using an additional sizeof(void*)*4 for MAX_BLOCK_SIZE_BYTES should thus be sufficient so that\n  * all implementations can allocate the nodes from the PoolAllocator.\n  */\n using CCoinsMap = std::unordered_map,\n                                      PoolAllocator&gt;;\n \n using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType;\n \n /** Cursor for iterating over CoinsView state */\n class CCoinsViewCursor\n {\n public:\n     CCoinsViewCursor(const uint256&amp; in_block_hash) : block_hash(in_block_hash) {}\n     virtual ~CCoinsViewCursor() = default;\n \n     virtual bool GetKey(COutPoint &amp;key) const = 0;\n     virtual bool GetValue(Coin &amp;coin) const = 0;\n \n     virtual bool Valid() const = 0;\n     virtual void Next() = 0;\n \n     //! Get best block at the time this cursor was created\n     const uint256&amp; GetBestBlock() const { return block_hash; }\n private:\n     uint256 block_hash;\n };\n \n /**\n  * Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.\n  *\n  * This is a helper struct to encapsulate the diverging logic between a non-erasing\n  * CCoinsViewCache::Sync and an erasing CCoinsViewCache::Flush. This allows the receiver\n  * of CCoinsView::BatchWrite to iterate through the flagged entries without knowing\n  * the caller's intent.\n  *\n- * However, the receiver can still call CoinsViewCacheCursor::WillErase to see if the\n+ * However, the receiver can still call CoinsViewCacheCursor::WillClear to see if the\n  * caller will erase the entry after BatchWrite returns. If so, the receiver can\n  * perform optimizations such as moving the coin out of the CCoinsCachEntry instead\n  * of copying it.\n  */\n struct CoinsViewCacheCursor\n {\n-    //! If will_erase is not set, iterating through the cursor will erase spent coins from the map,\n+    //! If will_clear is not set, iterating through the cursor will erase spent coins from the map,\n     //! and other coins will be unflagged (removing them from the linked list).\n-    //! If will_erase is set, the underlying map and linked list will not be modified,\n+    //! If will_clear is set, the underlying map and linked list will not be modified,\n     //! as the caller is expected to wipe the entire map anyway.\n-    //! This is an optimization compared to erasing all entries as the cursor iterates them when will_erase is set.\n+    //! This is an optimization compared to erasing all entries as the cursor iterates them when will_clear is set.\n     //! Calling CCoinsMap::clear() afterwards is faster because a CoinsCachePair cannot be coerced back into a\n     //! CCoinsMap::iterator to be erased, and must therefore be looked up again by key in the CCoinsMap before being erased.\n     CoinsViewCacheCursor(size_t&amp; dirty_count LIFETIMEBOUND,\n                          CoinsCachePair&amp; sentinel LIFETIMEBOUND,\n                          CCoinsMap&amp; map LIFETIMEBOUND,\n-                         bool will_erase) noexcept\n-        : m_dirty_count(dirty_count), m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}\n+                         CCoinsMapMemoryResource&amp; memory LIFETIMEBOUND,\n+                         bool will_clear) noexcept\n+        : m_dirty_count(dirty_count), m_sentinel(sentinel), m_map(map), m_memory(memory), m_will_clear(will_clear) {}\n \n     inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }\n     inline CoinsCachePair* End() const noexcept { return &amp;m_sentinel; }\n \n     //! Return the next entry after current, possibly erasing current\n     inline CoinsCachePair* NextAndMaybeErase(CoinsCachePair&amp; current) noexcept\n     {\n         const auto next_entry{current.second.Next()};\n         Assume(TrySub(m_dirty_count, current.second.IsDirty()));\n         // If we are not going to erase the cache, we must still erase spent entries.\n         // Otherwise, clear the state of the entry.\n-        if (!m_will_erase) {\n-            if (current.second.coin.IsSpent()) {\n-                assert(current.second.coin.DynamicMemoryUsage() == 0); // scriptPubKey was already cleared in SpendCoin\n+        if (!m_will_clear) {\n+            if (current.second.IsSpent()) {\n+                // there is no coin to deallocate\n                 m_map.erase(current.first);\n             } else {\n                 current.second.SetClean();\n             }\n+        } else if (current.second.coin) {\n+            // Clearing the map doesn't delete the coins; that must be done explicitly.\n+            m_memory.Deallocate(current.second.coin, sizeof(Coin), alignof(Coin));\n+            current.second.coin = nullptr;\n         }\n         return next_entry;\n     }\n \n-    inline bool WillErase(CoinsCachePair&amp; current) const noexcept { return m_will_erase || current.second.coin.IsSpent(); }\n+    bool WillClear() const noexcept { return m_will_clear; }\n     size_t GetDirtyCount() const noexcept { return m_dirty_count; }\n     size_t GetTotalCount() const noexcept { return m_map.size(); }\n private:\n     size_t&amp; m_dirty_count;\n     CoinsCachePair&amp; m_sentinel;\n     CCoinsMap&amp; m_map;\n-    bool m_will_erase;\n+    CCoinsMapMemoryResource&amp; m_memory;\n+    bool m_will_clear;\n };\n \n /** Pure abstract view on the open txout dataset. */\n class CCoinsView\n {\n public:\n     //! As we use CCoinsViews polymorphically, have a virtual destructor\n     virtual ~CCoinsView() = default;\n \n     //! Retrieve the Coin (unspent transaction output) for a given outpoint.\n     //! May populate the cache. Use PeekCoin() to perform a non-caching lookup.\n     virtual std::optional GetCoin(const COutPoint&amp; outpoint) const = 0;\n \n     //! Retrieve the Coin (unspent transaction output) for a given outpoint, without caching results.\n     //! Does not populate the cache. Use GetCoin() to cache the result.\n     virtual std::optional PeekCoin(const COutPoint&amp; outpoint) const = 0;\n \n     //! Just check whether a given outpoint is unspent.\n     //! May populate the cache. Use PeekCoin() to perform a non-caching lookup.\n     virtual bool HaveCoin(const COutPoint&amp; outpoint) const = 0;\n \n     //! Retrieve the block hash whose state this CCoinsView currently represents\n     virtual uint256 GetBestBlock() const = 0;\n \n     //! Retrieve the range of blocks that may have been only partially written.\n     //! If the database is in a consistent state, the result is the empty vector.\n     //! Otherwise, a two-element vector is returned consisting of the new and\n     //! the old block hash, in that order.\n     virtual std::vector GetHeadBlocks() const = 0;\n \n     //! Do a bulk modification (multiple Coin changes + BestBlock change).\n     //! The passed cursor is used to iterate through the coins.\n     virtual void BatchWrite(CoinsViewCacheCursor&amp; cursor, const uint256&amp; block_hash) = 0;\n \n     //! Get a cursor to iterate over the whole state. Implementations may return nullptr.\n     virtual std::unique_ptr Cursor() const = 0;\n \n     //! Estimate database size\n     virtual size_t EstimateSize() const = 0;\n };\n \n /** Noop coins view. */\n class CoinsViewEmpty : public CCoinsView\n {\n protected:\n     CoinsViewEmpty() = default;\n \n public:\n     static CoinsViewEmpty&amp; Get();\n \n     CoinsViewEmpty(const CoinsViewEmpty&amp;) = delete;\n     CoinsViewEmpty&amp; operator=(const CoinsViewEmpty&amp;) = delete;\n \n     std::optional GetCoin(const COutPoint&amp;) const override { return {}; }\n     std::optional PeekCoin(const COutPoint&amp; outpoint) const override { return GetCoin(outpoint); }\n     bool HaveCoin(const COutPoint&amp; outpoint) const override { return !!GetCoin(outpoint); }\n     uint256 GetBestBlock() const override { return {}; }\n     std::vector GetHeadBlocks() const override { return {}; }\n     void BatchWrite(CoinsViewCacheCursor&amp; cursor, const uint256&amp;) override\n     {\n         for (auto it{cursor.Begin()}; it != cursor.End(); it = cursor.NextAndMaybeErase(*it)) { }\n     }\n     std::unique_ptr Cursor() const override { return {}; }\n     size_t EstimateSize() const override { return 0; }\n };\n \n /** CCoinsView backed by another CCoinsView */\n class CCoinsViewBacked : public CCoinsView\n {\n protected:\n     CCoinsView* base;\n \n public:\n     explicit CCoinsViewBacked(CCoinsView* in_view) : base{Assert(in_view)} {}\n \n     void SetBackend(CCoinsView&amp; in_view) { base = &amp;in_view; }\n \n     std::optional GetCoin(const COutPoint&amp; outpoint) const override { return base-&gt;GetCoin(outpoint); }\n     std::optional PeekCoin(const COutPoint&amp; outpoint) const override { return base-&gt;PeekCoin(outpoint); }\n     bool HaveCoin(const COutPoint&amp; outpoint) const override { return base-&gt;HaveCoin(outpoint); }\n     uint256 GetBestBlock() const override { return base-&gt;GetBestBlock(); }\n     std::vector GetHeadBlocks() const override { return base-&gt;GetHeadBlocks(); }\n     void BatchWrite(CoinsViewCacheCursor&amp; cursor, const uint256&amp; block_hash) override { base-&gt;BatchWrite(cursor, block_hash); }\n     std::unique_ptr Cursor() const override { return base-&gt;Cursor(); }\n     size_t EstimateSize() const override { return base-&gt;EstimateSize(); }\n };\n \n \n /** CCoinsView that adds a memory cache for transactions to another CCoinsView */\n class CCoinsViewCache : public CCoinsViewBacked\n {\n private:\n     const bool m_deterministic;\n \n protected:\n     /**\n      * Make mutable so that we can \"fill the cache\" even from Get-methods\n      * declared as \"const\".\n      */\n     mutable uint256 m_block_hash;\n     mutable CCoinsMapMemoryResource m_cache_coins_memory_resource{};\n     /* The starting sentinel of the flagged entry circular doubly linked list. */\n     mutable CoinsCachePair m_sentinel;\n     mutable CCoinsMap cacheCoins;\n \n     /* Cached dynamic memory usage for the inner Coin objects. */\n     mutable size_t cachedCoinsUsage{0};\n     /* Running count of dirty Coin cache entries. */\n     mutable size_t m_dirty_count{0};\n \n     /**\n      * Discard all modifications made to this cache without flushing to the base view.\n      * This can be used to efficiently reuse a cache instance across multiple operations.\n      */\n     void Reset() noexcept;\n \n     /* Fetch the coin from base. Used for cache misses in FetchCoin. */\n     virtual std::optional FetchCoinFromBase(const COutPoint&amp; outpoint) const;\n \n public:\n     CCoinsViewCache(CCoinsView* in_base, bool deterministic = false);\n \n     /**\n      * By deleting the copy constructor, we prevent accidentally using it when one intends to create a cache on top of a base cache.\n      */\n     CCoinsViewCache(const CCoinsViewCache &amp;) = delete;\n \n+    // Coins need to be deconstructed explicitly.\n+    ~CCoinsViewCache() { FreeAllCoins(); }\n+\n     // Standard CCoinsView methods\n     std::optional GetCoin(const COutPoint&amp; outpoint) const override;\n     std::optional PeekCoin(const COutPoint&amp; outpoint) const override;\n     bool HaveCoin(const COutPoint&amp; outpoint) const override;\n     uint256 GetBestBlock() const override;\n     void SetBestBlock(const uint256&amp; block_hash);\n     void BatchWrite(CoinsViewCacheCursor&amp; cursor, const uint256&amp; block_hash) override;\n     std::unique_ptr Cursor() const override {\n         throw std::logic_error(\"CCoinsViewCache cursor iteration not supported.\");\n     }\n \n     /**\n      * Check if we have the given utxo already loaded in this cache.\n      * The semantics are the same as HaveCoin(), but no calls to\n      * the backing CCoinsView are made.\n      */\n     bool HaveCoinInCache(const COutPoint &amp;outpoint) const;\n \n     /**\n      * Return a reference to Coin in the cache, or coinEmpty if not found. This is\n      * more efficient than GetCoin.\n      *\n      * Generally, do not hold the reference returned for more than a short scope.\n      * While the current implementation allows for modifications to the contents\n      * of the cache while holding the reference, this behavior should not be relied\n      * on! To be safe, best to not hold the returned reference through any other\n      * calls to this cache.\n      */\n     const Coin&amp; AccessCoin(const COutPoint &amp;output) const;\n \n     /**\n      * Add a coin. Set possible_overwrite to true if an unspent version may\n      * already exist in the cache.\n      */\n     void AddCoin(const COutPoint&amp; outpoint, Coin&amp;&amp; coin, bool possible_overwrite);\n \n     /**\n      * Emplace a coin into cacheCoins without performing any checks, marking\n      * the emplaced coin as dirty.\n      *\n      * NOT FOR GENERAL USE. Used only when loading coins from a UTXO snapshot.\n      * @sa ChainstateManager::PopulateAndValidateSnapshot()\n      */\n     void EmplaceCoinInternalDANGER(COutPoint&amp;&amp; outpoint, Coin&amp;&amp; coin);\n \n     /**\n      * Spend a coin. Pass moveto in order to get the deleted data.\n      * If no unspent output exists for the passed outpoint, this call\n      * has no effect.\n      */\n     bool SpendCoin(const COutPoint &amp;outpoint, Coin* moveto = nullptr);\n \n+    //! Move a coin into a cache entry, overwriting any existing coin.\n+    void MoveCoin(CCoinsCacheEntry&amp; entry, Coin&amp;&amp; coin) const;\n+\n+    //! Free (deallocate) a coin (TODO - is noexcept ok here?)\n+    void FreeCoin(CCoinsCacheEntry&amp; entry) const noexcept;\n+\n+    //! Call FreeCoin() on all the coins within this cache.\n+    void FreeAllCoins() const noexcept;\n+\n     /**\n      * Push the modifications applied to this cache to its base and wipe local state.\n      * Failure to call this method or Sync() before destruction will cause the changes\n      * to be forgotten.\n      * If reallocate_cache is false, the cache will retain the same memory footprint\n      * after flushing and should be destroyed to deallocate.\n      */\n     void Flush(bool reallocate_cache = true);\n \n     /**\n      * Push the modifications applied to this cache to its base while retaining\n      * the contents of this cache (except for spent coins, which we erase).\n      * Failure to call this method or Flush() before destruction will cause the changes\n      * to be forgotten.\n      */\n     void Sync();\n \n     /**\n      * Removes the UTXO with the given outpoint from the cache, if it is\n      * not modified.\n      */\n     void Uncache(const COutPoint &amp;outpoint);\n \n     //! Size of the cache (in number of transaction outputs)\n     unsigned int GetCacheSize() const;\n \n     //! Number of dirty cache entries (transaction outputs)\n     size_t GetDirtyCount() const noexcept { return m_dirty_count; }\n \n     //! Calculate the size of the cache (in bytes)\n     size_t DynamicMemoryUsage() const;\n \n     //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view\n     bool HaveInputs(const CTransaction&amp; tx) const;\n \n     //! Force a reallocation of the cache map. This is required when downsizing\n     //! the cache because the map's allocator may be hanging onto a lot of\n     //! memory despite having called .clear().\n     //!\n     //! See: https://stackoverflow.com/questions/42114044/how-to-release-unordered-map-memory\n     void ReallocateCache();\n \n     //! Run an internal sanity check on the cache data structure. */\n     void SanityCheck() const;\n \n     class ResetGuard\n     {\n     private:\n         friend CCoinsViewCache;\n         CCoinsViewCache&amp; m_cache;\n         explicit ResetGuard(CCoinsViewCache&amp; cache LIFETIMEBOUND) noexcept : m_cache{cache} {}\n \n     public:\n         ResetGuard(const ResetGuard&amp;) = delete;\n         ResetGuard&amp; operator=(const ResetGuard&amp;) = delete;\n         ResetGuard(ResetGuard&amp;&amp;) = delete;\n         ResetGuard&amp; operator=(ResetGuard&amp;&amp;) = delete;\n \n         ~ResetGuard() { m_cache.Reset(); }\n     };\n \n     //! Create a scoped guard that will call `Reset()` on this cache when it goes out of scope.\n     [[nodiscard]] ResetGuard CreateResetGuard() noexcept { return ResetGuard{*this}; }\n \n private:\n     /**\n      * @note this is marked const, but may actually append to `cacheCoins`, increasing\n      * memory usage.\n      */\n     CCoinsMap::iterator FetchCoin(const COutPoint &amp;outpoint) const;\n };\n \n /**\n  * CCoinsViewCache overlay that avoids populating/mutating parent cache layers on cache misses.\n  *\n  * This is achieved by fetching coins from the base view using PeekCoin() instead of GetCoin(),\n  * so intermediate CCoinsViewCache layers are not filled.\n  *\n  * Used during ConnectBlock() as an ephemeral, resettable top-level view that is flushed only\n  * on success, so invalid blocks don't pollute the underlying cache.\n  */\n class CoinsViewOverlay : public CCoinsViewCache\n {\n private:\n     std::optional FetchCoinFromBase(const COutPoint&amp; outpoint) const override\n     {\n         return base-&gt;PeekCoin(outpoint);\n     }\n \n public:\n     using CCoinsViewCache::CCoinsViewCache;\n };\n \n //! Utility function to add all of a transaction's outputs to a cache.\n //! When check is false, this assumes that overwrites are only possible for coinbase transactions.\n //! When check is true, the underlying view may be queried to determine whether an addition is\n //! an overwrite.\n // TODO: pass in a boolean to limit these possible overwrites to known\n // (pre-BIP34) cases.\n void AddCoins(CCoinsViewCache&amp; cache, const CTransaction&amp; tx, int nHeight, bool check = false);\n \n //! Utility function to find any unspent output with a given txid.\n //! This function can be quite expensive because in the event of a transaction\n //! which is not found in the cache, it can cause up to MAX_OUTPUTS_PER_BLOCK\n //! lookups to database, so it should be used with care.\n const Coin&amp; AccessByTxid(const CCoinsViewCache&amp; cache, const Txid&amp; txid);\n \n /**\n  * This is a minimally invasive approach to shutdown on LevelDB read errors from the\n  * chainstate, while keeping user interface out of the common library, which is shared\n  * between bitcoind, and bitcoin-qt and non-server tools.\n  *\n  * Writes do not need similar protection, as failure to write is handled by the caller.\n */\n class CCoinsViewErrorCatcher final : public CCoinsViewBacked\n {\n public:\n     explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}\n \n     void AddReadErrCallback(std::function f) {\n         m_err_callbacks.emplace_back(std::move(f));\n     }\n \n     std::optional GetCoin(const COutPoint&amp; outpoint) const override;\n     bool HaveCoin(const COutPoint&amp; outpoint) const override;\n     std::optional PeekCoin(const COutPoint&amp; outpoint) const override;\n \n private:\n     /** A list of callbacks to execute upon leveldb read error. */\n     std::vector&gt; m_err_callbacks;\n \n };\n \n #endif // BITCOIN_COINS_H\ndiff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp\nindex 14ccb1c443..9137814355 100644\n--- a/src/test/coins_tests.cpp\n+++ b/src/test/coins_tests.cpp\n@@ -1,1194 +1,1226 @@\n // Copyright (c) 2014-present The Bitcoin Core developers\n // Distributed under the MIT software license, see the accompanying\n // file COPYING or http://www.opensource.org/licenses/mit-license.php.\n \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n \n #include \n #include \n #include \n #include \n \n #include \n \n using namespace util::hex_literals;\n \n int ApplyTxInUndo(Coin&amp;&amp; undo, CCoinsViewCache&amp; view, const COutPoint&amp; out);\n void UpdateCoins(const CTransaction&amp; tx, CCoinsViewCache&amp; inputs, CTxUndo &amp;txundo, int nHeight);\n \n namespace\n {\n //! equality test\n bool operator==(const Coin &amp;a, const Coin &amp;b) {\n     // Empty Coin objects are always equal.\n     if (a.IsSpent() &amp;&amp; b.IsSpent()) return true;\n     return a.fCoinBase == b.fCoinBase &amp;&amp;\n            a.nHeight == b.nHeight &amp;&amp;\n            a.out == b.out;\n }\n \n class CCoinsViewTest : public CoinsViewEmpty\n {\n     FastRandomContext&amp; m_rng;\n     uint256 hashBestBlock_;\n     std::map map_;\n \n public:\n     explicit CCoinsViewTest(FastRandomContext&amp; rng) : m_rng{rng} {}\n \n     std::optional GetCoin(const COutPoint&amp; outpoint) const override\n     {\n         if (auto it{map_.find(outpoint)}; it != map_.end() &amp;&amp; !it-&gt;second.IsSpent()) return it-&gt;second;\n         return std::nullopt;\n     }\n \n     uint256 GetBestBlock() const override { return hashBestBlock_; }\n \n     void BatchWrite(CoinsViewCacheCursor&amp; cursor, const uint256&amp; block_hash) override\n     {\n         for (auto it{cursor.Begin()}; it != cursor.End(); it = cursor.NextAndMaybeErase(*it)){\n             if (it-&gt;second.IsDirty()) {\n                 // Same optimization used in CCoinsViewDB is to only write dirty entries.\n-                map_[it-&gt;first] = it-&gt;second.coin;\n-                if (it-&gt;second.coin.IsSpent() &amp;&amp; m_rng.randrange(3) == 0) {\n+                map_[it-&gt;first] = it-&gt;second.coin ? *it-&gt;second.coin : Coin{};\n+                if (it-&gt;second.IsSpent() &amp;&amp; m_rng.randrange(3) == 0) {\n                     // Randomly delete empty entries on write.\n                     map_.erase(it-&gt;first);\n                 }\n             }\n         }\n         if (!block_hash.IsNull())\n             hashBestBlock_ = block_hash;\n     }\n };\n \n class CCoinsViewCacheTest : public CCoinsViewCache\n {\n public:\n     explicit CCoinsViewCacheTest(CCoinsView* _base) : CCoinsViewCache(_base) {}\n \n     void SelfTest(bool sanity_check = true) const\n     {\n         // Manually recompute the dynamic usage of the whole data, and compare it.\n         size_t ret = memusage::DynamicUsage(cacheCoins);\n         size_t count = 0;\n         for (const auto&amp; entry : cacheCoins) {\n-            ret += entry.second.coin.DynamicMemoryUsage();\n+            if (entry.second.coin) ret += entry.second.coin-&gt;DynamicMemoryUsage();\n             ++count;\n         }\n         BOOST_CHECK_EQUAL(GetCacheSize(), count);\n         BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret);\n         if (sanity_check) {\n             SanityCheck();\n         }\n     }\n \n     CCoinsMap&amp; map() const { return cacheCoins; }\n     CoinsCachePair&amp; sentinel() const { return m_sentinel; }\n+    CCoinsMapMemoryResource&amp; resource() { return m_cache_coins_memory_resource; }\n     size_t&amp; usage() const { return cachedCoinsUsage; }\n     size_t&amp; dirty() const { return m_dirty_count; }\n };\n \n } // namespace\n \n static const unsigned int NUM_SIMULATION_ITERATIONS = 40000;\n \n struct CacheTest : BasicTestingSetup {\n // This is a large randomized insert/remove simulation test on a variable-size\n // stack of caches on top of CCoinsViewTest.\n //\n // It will randomly create/update/delete Coin entries to a tip of caches, with\n // txids picked from a limited list of random 256-bit hashes. Occasionally, a\n // new tip is added to the stack of caches, or the tip is flushed and removed.\n //\n // During the process, booleans are kept to make sure that the randomized\n // operation hits all branches.\n //\n // If fake_best_block is true, assign a random uint256 to mock the recording\n // of best block on flush. This is necessary when using CCoinsViewDB as the base,\n // otherwise we'll hit an assertion in BatchWrite.\n //\n void SimulationTest(CCoinsView* base, bool fake_best_block)\n {\n     // Various coverage trackers.\n     bool removed_all_caches = false;\n     bool reached_4_caches = false;\n     bool added_an_entry = false;\n     bool added_an_unspendable_entry = false;\n     bool removed_an_entry = false;\n     bool updated_an_entry = false;\n     bool found_an_entry = false;\n     bool missed_an_entry = false;\n     bool uncached_an_entry = false;\n     bool flushed_without_erase = false;\n \n     // A simple map to track what we expect the cache stack to represent.\n     std::map result;\n \n     // The cache stack.\n     std::vector&gt; stack; // A stack of CCoinsViewCaches on top.\n     stack.push_back(std::make_unique(base)); // Start with one cache.\n \n     // Use a limited set of random transaction ids, so we do test overwriting entries.\n     std::vector txids;\n     txids.resize(NUM_SIMULATION_ITERATIONS / 8);\n     for (unsigned int i = 0; i &lt; txids.size(); i++) {\n         txids[i] = Txid::FromUint256(m_rng.rand256());\n     }\n \n     for (unsigned int i = 0; i &lt; NUM_SIMULATION_ITERATIONS; i++) {\n         // Do a random modification.\n         {\n             auto txid = txids[m_rng.randrange(txids.size())]; // txid we're going to modify in this iteration.\n             Coin&amp; coin = result[COutPoint(txid, 0)];\n \n             // Determine whether to test HaveCoin before or after Access* (or both). As these functions\n             // can influence each other's behaviour by pulling things into the cache, all combinations\n             // are tested.\n             bool test_havecoin_before = m_rng.randbits(2) == 0;\n             bool test_havecoin_after = m_rng.randbits(2) == 0;\n \n             bool result_havecoin = test_havecoin_before ? stack.back()-&gt;HaveCoin(COutPoint(txid, 0)) : false;\n \n             // Infrequently, test usage of AccessByTxid instead of AccessCoin - the\n             // former just delegates to the latter and returns the first unspent in a txn.\n             const Coin&amp; entry = (m_rng.randrange(500) == 0) ?\n                 AccessByTxid(*stack.back(), txid) : stack.back()-&gt;AccessCoin(COutPoint(txid, 0));\n             BOOST_CHECK(coin == entry);\n \n             if (test_havecoin_before) {\n                 BOOST_CHECK(result_havecoin == !entry.IsSpent());\n             }\n \n             if (test_havecoin_after) {\n                 bool ret = stack.back()-&gt;HaveCoin(COutPoint(txid, 0));\n                 BOOST_CHECK(ret == !entry.IsSpent());\n             }\n \n             if (m_rng.randrange(5) == 0 || coin.IsSpent()) {\n                 Coin newcoin;\n                 newcoin.out.nValue = RandMoney(m_rng);\n                 newcoin.nHeight = 1;\n \n                 // Infrequently test adding unspendable coins.\n                 if (m_rng.randrange(16) == 0 &amp;&amp; coin.IsSpent()) {\n                     newcoin.out.scriptPubKey.assign(1 + m_rng.randbits(6), OP_RETURN);\n                     BOOST_CHECK(newcoin.out.scriptPubKey.IsUnspendable());\n                     added_an_unspendable_entry = true;\n                 } else {\n                     // Random sizes so we can test memory usage accounting\n                     newcoin.out.scriptPubKey.assign(m_rng.randbits(6), 0);\n                     (coin.IsSpent() ? added_an_entry : updated_an_entry) = true;\n                     coin = newcoin;\n                 }\n                 if (COutPoint op(txid, 0); !stack.back()-&gt;map().contains(op) &amp;&amp; !newcoin.out.scriptPubKey.IsUnspendable() &amp;&amp; m_rng.randbool()) {\n                     stack.back()-&gt;EmplaceCoinInternalDANGER(std::move(op), std::move(newcoin));\n                 } else {\n                     stack.back()-&gt;AddCoin(op, std::move(newcoin), /*possible_overwrite=*/!coin.IsSpent() || m_rng.randbool());\n                 }\n             } else {\n                 // Spend the coin.\n                 removed_an_entry = true;\n                 coin.Clear();\n                 BOOST_CHECK(stack.back()-&gt;SpendCoin(COutPoint(txid, 0)));\n             }\n         }\n \n         // Once every 10 iterations, remove a random entry from the cache\n         if (m_rng.randrange(10) == 0) {\n             COutPoint out(txids[m_rng.rand32() % txids.size()], 0);\n             int cacheid = m_rng.rand32() % stack.size();\n             stack[cacheid]-&gt;Uncache(out);\n             uncached_an_entry |= !stack[cacheid]-&gt;HaveCoinInCache(out);\n         }\n \n         // Once every 1000 iterations and at the end, verify the full cache.\n         if (m_rng.randrange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {\n             for (const auto&amp; entry : result) {\n                 bool have = stack.back()-&gt;HaveCoin(entry.first);\n                 const Coin&amp; coin = stack.back()-&gt;AccessCoin(entry.first);\n                 BOOST_CHECK(have == !coin.IsSpent());\n                 BOOST_CHECK(coin == entry.second);\n                 if (coin.IsSpent()) {\n                     missed_an_entry = true;\n                 } else {\n                     BOOST_CHECK(stack.back()-&gt;HaveCoinInCache(entry.first));\n                     found_an_entry = true;\n                 }\n             }\n             for (const auto&amp; test : stack) {\n                 test-&gt;SelfTest();\n             }\n         }\n \n         if (m_rng.randrange(100) == 0) {\n             // Every 100 iterations, flush an intermediate cache\n             if (stack.size() &gt; 1 &amp;&amp; m_rng.randbool() == 0) {\n                 unsigned int flushIndex = m_rng.randrange(stack.size() - 1);\n                 if (fake_best_block) stack[flushIndex]-&gt;SetBestBlock(m_rng.rand256());\n                 bool should_erase = m_rng.randrange(4) &lt; 3;\n                 should_erase ? stack[flushIndex]-&gt;Flush() : stack[flushIndex]-&gt;Sync();\n                 flushed_without_erase |= !should_erase;\n             }\n         }\n         if (m_rng.randrange(100) == 0) {\n             // Every 100 iterations, change the cache stack.\n             if (stack.size() &gt; 0 &amp;&amp; m_rng.randbool() == 0) {\n                 //Remove the top cache\n                 if (fake_best_block) stack.back()-&gt;SetBestBlock(m_rng.rand256());\n                 bool should_erase = m_rng.randrange(4) &lt; 3;\n                 should_erase ? stack.back()-&gt;Flush() : stack.back()-&gt;Sync();\n                 flushed_without_erase |= !should_erase;\n                 stack.pop_back();\n             }\n             if (stack.size() == 0 || (stack.size() &lt; 4 &amp;&amp; m_rng.randbool())) {\n                 //Add a new cache\n                 CCoinsView* tip = base;\n                 if (stack.size() &gt; 0) {\n                     tip = stack.back().get();\n                 } else {\n                     removed_all_caches = true;\n                 }\n                 stack.push_back(std::make_unique(tip));\n                 if (stack.size() == 4) {\n                     reached_4_caches = true;\n                 }\n             }\n         }\n     }\n \n     // Verify coverage.\n     BOOST_CHECK(removed_all_caches);\n     BOOST_CHECK(reached_4_caches);\n     BOOST_CHECK(added_an_entry);\n     BOOST_CHECK(added_an_unspendable_entry);\n     BOOST_CHECK(removed_an_entry);\n     BOOST_CHECK(updated_an_entry);\n     BOOST_CHECK(found_an_entry);\n     BOOST_CHECK(missed_an_entry);\n     BOOST_CHECK(uncached_an_entry);\n     BOOST_CHECK(flushed_without_erase);\n }\n }; // struct CacheTest\n \n BOOST_FIXTURE_TEST_SUITE(coins_tests_base, BasicTestingSetup)\n \n // Run the above simulation for multiple base types.\n BOOST_FIXTURE_TEST_CASE(coins_cache_base_simulation_test, CacheTest)\n {\n     CCoinsViewTest base{m_rng};\n     SimulationTest(&amp;base, false);\n }\n \n BOOST_AUTO_TEST_SUITE_END()\n \n BOOST_FIXTURE_TEST_SUITE(coins_tests_dbbase, BasicTestingSetup)\n \n BOOST_FIXTURE_TEST_CASE(coins_cache_dbbase_simulation_test, CacheTest)\n {\n     CCoinsViewDB db_base{{.path = \"test\", .cache_bytes = 8_MiB, .memory_only = true}, {}};\n     SimulationTest(&amp;db_base, true);\n }\n \n BOOST_AUTO_TEST_SUITE_END()\n \n BOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup)\n \n struct UpdateTest : BasicTestingSetup {\n // Store of all necessary tx and undo data for next test\n typedef std::map&gt; UtxoData;\n UtxoData utxoData;\n \n UtxoData::iterator FindRandomFrom(const std::set &amp;utxoSet) {\n     assert(utxoSet.size());\n     auto utxoSetIt = utxoSet.lower_bound(COutPoint(Txid::FromUint256(m_rng.rand256()), 0));\n     if (utxoSetIt == utxoSet.end()) {\n         utxoSetIt = utxoSet.begin();\n     }\n     auto utxoDataIt = utxoData.find(*utxoSetIt);\n     assert(utxoDataIt != utxoData.end());\n     return utxoDataIt;\n }\n }; // struct UpdateTest\n \n \n // This test is similar to the previous test\n // except the emphasis is on testing the functionality of UpdateCoins\n // random txs are created and UpdateCoins is used to update the cache stack\n // In particular it is tested that spending a duplicate coinbase tx\n // has the expected effect (the other duplicate is overwritten at all cache levels)\n BOOST_FIXTURE_TEST_CASE(updatecoins_simulation_test, UpdateTest)\n {\n     SeedRandomForTest(SeedRand::ZEROS);\n \n     bool spent_a_duplicate_coinbase = false;\n     // A simple map to track what we expect the cache stack to represent.\n     std::map result;\n \n     // The cache stack.\n     CCoinsViewTest base{m_rng}; // A CCoinsViewTest at the bottom.\n     std::vector&gt; stack; // A stack of CCoinsViewCaches on top.\n     stack.push_back(std::make_unique(&amp;base)); // Start with one cache.\n \n     // Track the txids we've used in various sets\n     std::set coinbase_coins;\n     std::set disconnected_coins;\n     std::set duplicate_coins;\n     std::set utxoset;\n \n     for (unsigned int i = 0; i &lt; NUM_SIMULATION_ITERATIONS; i++) {\n         uint32_t randiter = m_rng.rand32();\n \n         // 19/20 txs add a new transaction\n         if (randiter % 20 &lt; 19) {\n             CMutableTransaction tx;\n             tx.vin.resize(1);\n             tx.vout.resize(1);\n             tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate\n             tx.vout[0].scriptPubKey.assign(m_rng.rand32() &amp; 0x3F, 0); // Random sizes so we can test memory usage accounting\n             const int height{int(m_rng.rand32() &gt;&gt; 1)};\n             Coin old_coin;\n \n             // 2/20 times create a new coinbase\n             if (randiter % 20 &lt; 2 || coinbase_coins.size() &lt; 10) {\n                 // 1/10 of those times create a duplicate coinbase\n                 if (m_rng.randrange(10) == 0 &amp;&amp; coinbase_coins.size()) {\n                     auto utxod = FindRandomFrom(coinbase_coins);\n                     // Reuse the exact same coinbase\n                     tx = CMutableTransaction{std::get&lt;0&gt;(utxod-&gt;second)};\n                     // shouldn't be available for reconnection if it's been duplicated\n                     disconnected_coins.erase(utxod-&gt;first);\n \n                     duplicate_coins.insert(utxod-&gt;first);\n                 }\n                 else {\n                     coinbase_coins.insert(COutPoint(tx.GetHash(), 0));\n                 }\n                 assert(CTransaction(tx).IsCoinBase());\n             }\n \n             // 17/20 times reconnect previous or add a regular tx\n             else {\n \n                 COutPoint prevout;\n                 // 1/20 times reconnect a previously disconnected tx\n                 if (randiter % 20 == 2 &amp;&amp; disconnected_coins.size()) {\n                     auto utxod = FindRandomFrom(disconnected_coins);\n                     tx = CMutableTransaction{std::get&lt;0&gt;(utxod-&gt;second)};\n                     prevout = tx.vin[0].prevout;\n                     if (!CTransaction(tx).IsCoinBase() &amp;&amp; !utxoset.contains(prevout)) {\n                         disconnected_coins.erase(utxod-&gt;first);\n                         continue;\n                     }\n \n                     // If this tx is a", "url": "https://gist.github.com/LarryRuane/7a1ea41744a1068e069a91304ca29c4a"}, {"timestamp": "2026-06-16T23:40:32.433Z", "date_only": false, "value": "2026-06-16T23:40:32.433", "kind": "other", "label": "Updated", "source": "fkie_nvd \u00b7 FKIE_CVE-2012-1909", "record": "FKIE_CVE-2012-1909", "field": "lastModified", "linked_record": true}], "metrics": {"as_of": "2026-12-03T08:02:23.988Z", "anchors": {"origin": {"timestamp": "2012-08-06T16:00:00Z", "date_only": false, "value": "2012-08-06T16:00:00.000Z", "kind": "milestone", "label": "Published", "source": "cvelistv5", "record": "CVE-2012-1909", "field": "cveMetadata.datePublished", "metric_role": "disclosure", "metric_basis": "recorded_event"}, "discovery": null, "report": null, "acknowledgement": null, "disclosure": {"timestamp": "2012-08-06T16:00:00Z", "date_only": false, "value": "2012-08-06T16:00:00.000Z", "kind": "milestone", "label": "Published", "source": "cvelistv5", "record": "CVE-2012-1909", "field": "cveMetadata.datePublished", "metric_role": "disclosure", "metric_basis": "recorded_event"}, "exploit_publication": null, "exploitation": null, "patch": null}, "vendor_response_time": {"available": false, "missing": ["start", "end"]}, "time_to_exploit": {"available": false, "missing": ["end"]}, "disclosure_to_exploit": {"available": false, "missing": ["end"]}, "disclosure_to_exploit_publication": {"available": false, "missing": ["end"]}, "time_to_patch": {"available": false, "missing": ["start", "end"]}, "total_time_to_patch": {"available": false, "missing": ["start", "end"]}, "disclosure_to_patch": {"available": false, "missing": ["end"]}, "time_unpatched": {"available": true, "seconds": 452016143.988409, "hours": 125560.03999678027, "days": 5231.668333199178, "min_seconds": 452016143.988409, "max_seconds": 452016143.988409, "approximate": false, "ongoing": true, "order_known": true, "batch_listing": false, "end_before_start": false, "start": {"timestamp": "2012-08-06T16:00:00Z", "date_only": false, "value": "2012-08-06T16:00:00.000Z", "kind": "milestone", "label": "Published", "source": "cvelistv5", "record": "CVE-2012-1909", "field": "cveMetadata.datePublished", "metric_role": "disclosure", "metric_basis": "recorded_event"}, "end": {"timestamp": "2026-12-03T08:02:23.988Z", "date_only": false, "label": "As of", "source": "Calculation clock"}}, "exploitation_to_patch": {"available": false, "missing": ["start"]}, "exploit_publication_to_patch": {"available": false, "missing": ["start"]}}}
