Skip to content

coins: delegate CCoinsViewDB::HaveCoin to GetCoin - #34320

Closed
l0rinc wants to merge 4 commits into
bitcoin:masterfrom
l0rinc:l0rinc/remove-HaveCoin
Closed

l0rinc wants to merge 4 commits into
bitcoin:masterfrom
l0rinc:l0rinc/remove-HaveCoin

Conversation

@l0rinc

@l0rinc l0rinc commented Jan 16, 2026 •

Copy link
Copy Markdown
Contributor

Split out of #34132 (comment).

Problem: CCoinsViewDB::HaveCoin() currently answers a different question from the cache-backed coins view path.
It calls CDBWrapper::Exists(), which only checks whether LevelDB has a value for the coin key, while GetCoin() tries to read the value as an unspent Coin.
This makes the direct DB view's HaveCoin() semantics diverge from CCoinsViewCache::HaveCoin(), which fetches through GetCoin() on cache misses.
The separate CDBWrapper::ExistsImpl() read path also duplicates ReadImpl() even though the remaining CDBWrapper::Exists() callers are infrequent metadata checks.

Fix: Make CCoinsViewDB::HaveCoin() delegate to GetCoin(), so it reports whether the outpoint can be read as an unspent Coin (not just whether the database contains any value).
Also have CDBWrapper::Read() and Exists() share a ReadRaw() helper instead of keeping separate LevelDB read implementations.

Testing: Add a unit test documenting that CCoinsViewCache::HaveInputs() checks the cache first and calls the backing view's GetCoin(), not HaveCoin(), on cache miss.

@DrahtBot

DrahtBot commented Jan 16, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/34320.

Reviews

See the guideline for information on the review process.

Type Reviewers
Concept ACK sedited
Stale ACK andrewtoth, Eunovo

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #35654 (txdb: reject undecodable first coin cursor key by l0rinc)
  • #34931 (validation: abort on DB unreadable coins instead of treating them as missing by furszy)
  • #34132 (coins,dbwrapper: remove error catcher, make point-read failures fatal by l0rinc)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

@maflcko

maflcko commented Jan 20, 2026

Copy link
Copy Markdown
Member

One tries to deserialize, the other just returns whether any value is associated with the key.
But we usually need the full value we probed for, and HaveCoin cannot cache the returned value, so it can trigger an extra lookup if HaveCoin uses Exists and the caller later needs the actual value.

Are there any flamegraphs or benchmarks, to see how this affects performance?

@l0rinc

l0rinc commented Jan 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Are there any flamegraphs or benchmarks, to see how this affects performance?

I'm not sure what to measure exactly because the current code was already delegating to GetCoin in most places.
The pruned IBD and -reindex-chainstate and AssumeUTXO loading benchmarks I started haven't finished yet - but I don't expect any change there.
If you can describe a scenario that you would find helpful, please let me know.

@l0rinc

l0rinc commented Jan 22, 2026

Copy link
Copy Markdown
Contributor Author

Are there any flamegraphs or benchmarks, to see how this affects performance?

Added assumeutxo load, reindex-chainstate and pruned IBD measurements to the PR description

@andrewtoth

andrewtoth commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor

I'm not sure what to measure exactly because the current code was already delegating to GetCoin in most places.

I'm not sure about this. CCoinsViewCache::HaveCoin seems to be the implementation that is called in all non-test places outside of coins.cpp, and only delegates to GetCoin if there's a cache miss. In CCoinsViewCache::HaveCoin we avoid copying Coin:

bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
    CCoinsMap::const_iterator it = FetchCoin(outpoint);
    return (it != cacheCoins.end() && !it->second.coin.IsSpent());
}

vs CCoinsViewCache::GetCoin where we return a copy of Coin:

std::optional<Coin> CCoinsViewCache::GetCoin(const COutPoint& outpoint) const
{
    if (auto it{FetchCoin(outpoint)}; it != cacheCoins.end() && !it->second.coin.IsSpent()) return it->second.coin;
    return std::nullopt;
}

@andrewtoth

andrewtoth commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor

we usually need the full value we probed for, and HaveCoin cannot cache the returned value, so it can trigger an extra lookup if HaveCoin uses Exists and the caller later needs the actual value.

I see 4 uses of HaveCoin

  1. In ConnectBlock, we ensure we do not already have outputs of a block for BIP30 checks.
  2. In ApplyTxInUndo, we ensure we do not already have the coin we are about to roll back to unspent.
  3. In MemPoolAccept::PreChecks, where we check that we have all inputs of a tx we are accepting to the mempool.
  4. In TxVerify, where we call HaveInputs.

For 1 and 2, we are checking for the non-existence of the coin so we won't need the full value. In this case not caching the value makes sense.
For 3, it is explicitly relying on the fact that the value is cached. The backend is thrown away after all input prevouts are added to the top level cache.
For 4, it is a peformance improvement that the value is cached.

I think 1 and 2 would benefit from CCoinsViewCache::HaveCoin delegating to the base's HaveCoin and not going through FetchCoin.
For 3 this seems like an abuse of the CCoinsView API. But, calling GetCoin instead there would result in unnecessary copying of the Coin. I'm not sure what the best solution is here.
For 4 the current behavior makes sense.

@l0rinc

l0rinc commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor Author

only delegates to GetCoin if there's a cache miss. In CCoinsViewCache::HaveCoin we avoid copying Coin

Disassembly with separate translation units indicates GetCoin() does a new + memcpy of the Coin and the caller immediately deletes it, even when only checking .has_value(). HaveCoin() does indeed avoid it, but the extra copy only happens on the unexpectedly-present coin path, since if it's expected, we usually want to cache it. If we want to avoid the extra copy, we can use AccessCoin, but we would duplicate the spentness check.

In this case not caching the value makes sense.

But there's nothing to cache since these will return an empty optional. For BIP30 and ApplyTxInUndo the missing-coin path dominates, so GetCoin() short-circuits on Read() failure without deserialization, so I/O is the same as Exists(), no coin-copy happens (and when it does we crash or reorg anyway). But given that validation until bip30-end takes less than 3 minutes on my benchmarking server (see #33817), I'd say it's irrelevant either way.

For 3 this seems like an abuse of the CCoinsView API. But, calling GetCoin instead there would result in unnecessary copying of the Coin. I'm not sure what the best solution is here.

This is a good point, the disassembly indicates there's no devirtualization and no inlining in CCoinsViewCache::HaveInputs and MemPoolAccept::PreChecks, so the copy is real - though a lot faster than disk access, so it's not actually measurable.
We can use AccessCoin here and with explicit IsSpent call instead which would avoid the call (according to the assembly):

if (AccessCoin(tx.vin[i].prevout).IsSpent()) {

and

if (m_view.AccessCoin(txin.prevout).IsSpent()) {

I have added a new benchmark as a first commit to check the performance of on-disk HaveInputs to make sure the performance is retained.

Benchmark baseline:

ns/tx tx/s err% total benchmark
998.95 1,001,046.69 0.8% 1.09 HaveInputsOnDisk

Benchmark with !GetCoin() instead of HaveCoin:

ns/tx tx/s err% total benchmark
985.57 1,014,640.63 0.8% 1.10 HaveInputsOnDisk

Replace remaining HaveCoin calls with GetCoin()/AccessCoin and remove the former

ns/tx tx/s err% total benchmark
983.17 1,017,118.55 0.3% 1.10 HaveInputsOnDisk

(ran it 5 times for each commit and copied the fastest (with smallest noise). The small difference is reproducible, but not very important as long as it's not measurably slower)

Benchmarking script and results on Linux
for commit in 3544b98927050956f68cb183bf2686f5c65e5ebb 8c568500442144fbcd457eccda5a1956aa98ca81; do \                                        
    git fetch origin $commit >/dev/null 2>&1 && git checkout $commit >/dev/null 2>&1 && echo "" && git log -1 --pretty='%h %s' && \
    rm -rf build >/dev/null 2>&1 && cmake -B build -DBUILD_BENCH=ON -DCMAKE_BUILD_TYPE=Release >/dev/null 2>&1 && \
    cmake --build build -j$(nproc) >/dev/null 2>&1 && \
    for _ in $(seq 5); do \
      sleep 5; \
      ./build/bin/bench_bitcoin -filter='HaveInputsOnDisk' -min-time=1000; \
    done; \
done

resulting in

3544b98927 bench: add on-disk HaveInputs benchmark

ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,137.20 467,902.92 0.0% 16,874.42 7,673.54 2.199 2,895.01 0.8% 1.09 HaveInputsOnDisk
ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,153.41 464,380.56 0.0% 16,873.94 7,729.93 2.183 2,894.99 0.8% 1.10 HaveInputsOnDisk
ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,148.36 465,471.81 0.1% 16,873.92 7,709.74 2.189 2,894.98 0.8% 1.10 HaveInputsOnDisk
ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,150.10 465,095.33 0.1% 16,873.85 7,718.44 2.186 2,894.99 0.8% 1.10 HaveInputsOnDisk
ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,135.95 468,175.11 0.0% 16,874.21 7,669.12 2.200 2,894.99 0.8% 1.10 HaveInputsOnDisk

8c56850044 coins: replace remaining HaveCoin calls with GetCoin()/AccessCoin and remove the former

ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,120.50 471,586.34 0.0% 16,874.75 7,611.58 2.217 2,897.27 0.8% 1.10 HaveInputsOnDisk
ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,178.86 458,955.50 0.5% 16,875.34 7,821.05 2.158 2,897.29 1.0% 1.08 HaveInputsOnDisk
ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,153.54 464,352.06 0.0% 16,875.12 7,731.71 2.183 2,897.26 0.8% 1.10 HaveInputsOnDisk
ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,137.40 467,857.52 0.0% 16,875.16 7,673.32 2.199 2,897.26 0.8% 1.10 HaveInputsOnDisk
ns/tx tx/s err% ins/tx cyc/tx IPC bra/tx miss% total benchmark
2,135.08 468,365.96 0.0% 16,875.23 7,663.44 2.202 2,897.27 0.8% 1.11 HaveInputsOnDisk

@l0rinc
l0rinc force-pushed the l0rinc/remove-HaveCoin branch from 9b4e044 to 8c56850 Compare January 25, 2026 15:28
@andrewtoth

Copy link
Copy Markdown
Contributor

If we want to avoid the extra copy, we can use AccessCoin, but we would duplicate the spentness check.

This tells us that HaveCoin is the right level of abstraction then, and is a useful method, no?

In this case not caching the value makes sense.

But there's nothing to cache since these will return an empty optional

Same as above.

We can use AccessCoin here and with explicit IsSpent call instead which would avoid the call (according to the assembly)

I think everywhere we use AccessCoin we assert the unspentness. This would now break that pattern and use AccessCoin to check existence via spentness. I think HaveCoin conveys intent better here.

Can we instead just remove HaveCoin on the db then, and the default implementation would just forward to !!GetCoin for it?

@l0rinc l0rinc changed the title coins: replace remaining HaveCoin calls with GetCoin coins: remove redundant and confusing CCoinsViewDB::HaveCoin Feb 1, 2026
@l0rinc

l0rinc commented Feb 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @andrewtoth, I didn't like the suggestion at first since we keep polluting the interface, but after applying your suggestion I'm fine with the results, it's simpler and better separated from the other similar PRs.

@l0rinc
l0rinc force-pushed the l0rinc/remove-HaveCoin branch 2 times, most recently from 67068ee to 3d25cbf Compare February 1, 2026 13:42
@l0rinc
l0rinc force-pushed the l0rinc/remove-HaveCoin branch from 3d25cbf to 4166ee8 Compare February 1, 2026 13:43
@DrahtBot DrahtBot removed the CI failed label Feb 1, 2026
Comment thread src/bench/coins_haveinputs.cpp Resolved
Comment thread src/bench/coins_haveinputs.cpp Resolved
Comment thread src/test/coins_tests.cpp Resolved
Comment thread src/test/coins_tests.cpp Resolved
Comment thread src/test/coins_tests.cpp Resolved
Comment thread src/coins.cpp Resolved
@l0rinc
l0rinc force-pushed the l0rinc/remove-HaveCoin branch 2 times, most recently from 23dd085 to 69fa15a Compare February 3, 2026 17:56
@DrahtBot

DrahtBot commented Feb 3, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task lint: https://github.com/bitcoin/bitcoin/actions/runs/21641577498/job/62382439018
LLM reason (✨ experimental): Lint check failed: direct use of std::filesystem was flagged by the std_filesystem lint rule.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@l0rinc

l0rinc commented May 18, 2026

Copy link
Copy Markdown
Contributor Author

Rebased, removed the contentious #35078 squash - ready for review again.

@l0rinc
l0rinc force-pushed the l0rinc/remove-HaveCoin branch from c01f70e to 46a8e39 Compare May 18, 2026 18:41
@l0rinc l0rinc changed the title coins: remove redundant and confusing CCoinsViewDB::HaveCoin coins: delegate CCoinsViewDB::HaveCoin to GetCoin May 18, 2026

@optout21 optout21 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I see, what this PR solves is the code duplication across ReadImpl and ExistsImpl. And it does it by touching Exists, Read, and HaveCoin. For the HaveCoin path the value is passed upwards unnecessarily, which is a minor regression.

I think a simpler solution is to get rid of ExistsImpl, and replace it with !!ReadImpl. Unless I miss something, this achieves the same.

In a diagram:

Original:
HaveCoin  ──>  Exists  ──>  ExistsImpl
GetCoin  ───>  Read  ────>  ReadImpl

PR34320:
    HaveCoin ─┐       Exists ─┐
┌─────────────┘               │
└─> GetCoin     ───>  Read  ──┴─>  ReadRaw  ──>  ReadImpl

Alternative:
HaveCoin  ──>  Exists  ─┐
                        │
GetCoin  ───>  Read  ───┴──>  ReadImpl

See concretely here:
https://github.com/optout21/bitcoin/commits/pr34320_alt/
It would mean the following diff instead of the 3 code-commits:

git diff 053194a8042ce29a6a840e0efd47d85b4fcef32e..d35223c8ffbd87f4895f938e0d5e833de65d85c3
diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp
index 3743d43482..f19e23308e 100644
--- a/src/dbwrapper.cpp
+++ b/src/dbwrapper.cpp
@@ -321,21 +321,6 @@ std::optional<std::string> CDBWrapper::ReadImpl(std::span<const std::byte> key)
     return strValue;
 }
 
-bool CDBWrapper::ExistsImpl(std::span<const std::byte> key) const
-{
-    leveldb::Slice slKey(CharCast(key.data()), key.size());
-
-    std::string strValue;
-    leveldb::Status status = DBContext().pdb->Get(DBContext().readoptions, slKey, &strValue);
-    if (!status.ok()) {
-        if (status.IsNotFound())
-            return false;
-        LogError("LevelDB read failure: %s", status.ToString());
-        HandleError(status);
-    }
-    return true;
-}
-
 size_t CDBWrapper::EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const
 {
     leveldb::Slice slKey1(CharCast(key1.data()), key1.size());
diff --git a/src/dbwrapper.h b/src/dbwrapper.h
index 51775ee636..2c786b7b54 100644
--- a/src/dbwrapper.h
+++ b/src/dbwrapper.h
@@ -190,7 +190,6 @@ private:
     inline static const std::string OBFUSCATION_KEY{"\000obfuscate_key", 14}; // explicit size to avoid truncation at leading \0
 
     std::optional<std::string> ReadImpl(std::span<const std::byte> key) const;
-    bool ExistsImpl(std::span<const std::byte> key) const;
     size_t EstimateSizeImpl(std::span<const std::byte> key1, std::span<const std::byte> key2) const;
     auto& DBContext() const LIFETIMEBOUND { return *Assert(m_db_context); }
 
@@ -235,7 +234,7 @@ public:
         DataStream ssKey{};
         ssKey.reserve(DBWRAPPER_PREALLOC_KEY_SIZE);
         ssKey << key;
-        return ExistsImpl(ssKey);
+        return !!ReadImpl(ssKey);
     }

Comment thread src/txdb.cpp Outdated
@@ -80,7 +80,7 @@ std::optional<Coin> CCoinsViewDB::GetCoin(const COutPoint& outpoint, bool) const

bool CCoinsViewDB::HaveCoin(const COutPoint& outpoint) const
{
return m_db->Exists(CoinEntry(&outpoint));
return !!GetCoin(outpoint, /*peek_only=*/false);

@optout21 optout21 May 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I expand on this in a top-level comment.
What I meant is that I don't see the benefit of this change ('Exists' is still there), but I see a small regression: that the value is returned unnecessarily to one higher level, and the exists-only intent is lost.

@l0rinc
l0rinc force-pushed the l0rinc/remove-HaveCoin branch from 46a8e39 to ccc0656 Compare May 22, 2026 07:25
@l0rinc

l0rinc commented May 22, 2026

Copy link
Copy Markdown
Contributor Author

As I see, what this PR solves is the code duplication across ReadImpl and ExistsImpl

That's part of the reason. The other reason here is that HaveCoin() is a coins-view API, not a raw DB-key API. A value that exists in LevelDB but cannot be decoded as an unspent Coin should not satisfy that contract. This also matches the direction of #34132/#34931, where unreadable coin entries should go through the typed read path instead of being treated as successful existence checks.

I think a simpler solution is to get rid of ExistsImpl, and replace it with !!ReadImpl. Unless I miss something, this achieves the same.

That wouldn't attempt deserialization and wouldn't cache the results.

I have rebased and dropped the benchmark for simplicity.

Comment thread src/txdb.cpp
@@ -86,7 +86,7 @@ std::optional<Coin> CCoinsViewDB::PeekCoin(const COutPoint& outpoint) const

bool CCoinsViewDB::HaveCoin(const COutPoint& outpoint) const
{
return m_db->Exists(CoinEntry(&outpoint));
return !!GetCoin(outpoint);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I would still prefer if the HaveCoin member function and virtual member function would be removed, and test code just call GetCoin(...) directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Andrew specifically mentioned he considers it the right level of abstraction, see: #34320 (comment)
@andrewtoth is that still your preference here?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is fine to keep it as a member for the coins view cache imo, but I don't think we should carry around dead virtual functions in the rest of them.

@optout21

Copy link
Copy Markdown
Contributor

A value that exists in LevelDB but cannot be decoded as an unspent Coin should not satisfy that contract.

That depends how the contract is understood/defined.
Can you explain a non-exceptional case when this can happen? (Outside edge cases like a corrupt database, that eventually results in a critical failure, so it's mostly irrelevant.)

That wouldn't attempt deserialization and wouldn't cache the results.

Can you elaborate more on caching? I can't see additional caching introduced with this change:

  • `CDBWrapper::Exists()' is affected, but ultimately the same operations are invoked (post-change), I see no change in caching.
  • CCoinsViewDB::HaveCoin() is affected, but ultimately the same operations are invoked (post-change), with the exception of extra Assert(!coin.IsSpent()) check, no change in caching.
  • CCoinsViewCache::HaveCoin() is not affected, and it does perform caching (even pre-change), as it calls FetchCoin().

This last point also means that for all usage through CCoinsViewCache -- which is virtually all UTXO set handling -- HaveCoin does go through deobfuscation and deserialization anyways.

Detailed pre- and post- call chain analysis follows (LLM-aided)
Details

CDBWrapper::Exists() -- Call Chain Comparison

Current Version (with local changes)

CDBWrapper::Exists(key)                        [dbwrapper.h:238-241]
  return !!ReadRaw(key)
    │
    └─► CDBWrapper::ReadRaw(key)               [dbwrapper.h:213-219]
          ssKey << key  // serialize
          return ReadImpl(ssKey)
            │
            └─► CDBWrapper::ReadImpl(span<byte>) [dbwrapper.cpp:315-327]
                  leveldb::DB::Get(readoptions, slKey, &strValue)
                  if IsNotFound → return nullopt
                  if other error → LogError + HandleError (throws)
                  return strValue              // full value returned as optional<string>
    │
    // optional<string> propagates back up through ReadRaw → Exists
    // Exists discards the value, returns just !!optional

Original Version (without local changes)

CDBWrapper::Exists(key)                        [old dbwrapper.h]
  ssKey << key  // serialize
  return ExistsImpl(ssKey)
    │
    └─► CDBWrapper::ExistsImpl(span<byte>)     [old dbwrapper.cpp, now deleted]
          leveldb::DB::Get(readoptions, slKey, &strValue)
          if IsNotFound → return false
          if other error → LogError + HandleError (throws)
          return true                          // bool only; strValue dies here

Key Differences

Aspect Original Current
Private impl method ExistsImpl (dedicated) ReadImpl (shared with Read)
LevelDB call pdb->Get() pdb->Get() (same)
Value after LevelDB Get strValue is local, destroyed immediately strValue returned as optional<string>, propagated up two levels, then discarded by !!
String lifetime Never leaves ExistsImpl Escapes ReadImpl, escapes ReadRaw, discarded in Exists
Code reuse Exists and Read had separate impl paths Exists reuses ReadRaw → ReadImpl
Stack overhead Lower — no string move up stack Extra std::string move through two return values

Notes

  • Both versions call leveldb::DB::Get(), which always fetches the full value. LevelDB has no cheaper "key probe" API, so there is no I/O difference.
  • The only runtime cost difference is the std::string move through two return levels in the current version, which the compiler may optimize away.
  • The trade-off is fewer lines of code (reuse of ReadRaw) in exchange for that minor overhead.

CCoinsViewDB::HaveCoin() — Call Chain Comparison

Current Version (with local changes)

CCoinsViewDB::HaveCoin(outpoint)               [txdb.cpp:87-90]
  return !!GetCoin(outpoint)
    │
    └─► CCoinsViewDB::GetCoin(outpoint)         [txdb.cpp:73-80]
          m_db->Read(CoinEntry(&outpoint), coin)
            │
            └─► CDBWrapper::Read(key, value)    [dbwrapper.h:222-235]
                  ReadRaw(key)
                    │
                    └─► CDBWrapper::ReadRaw(key) [dbwrapper.h:213-219]
                          ssKey << key  // serialize CoinEntry
                          return ReadImpl(ssKey)
                            │
                            └─► CDBWrapper::ReadImpl(span<byte>) [dbwrapper.cpp:315-327]
                                  leveldb::DB::Get(readoptions, slKey, &strValue)
                                  if IsNotFound → return nullopt
                                  if other error → LogError + HandleError (throws)
                                  return strValue  // optional<string>
                  if (!strValue) return false
                  m_obfuscation(ssValue)           // XOR deobfuscation
                  SpanReader{ssValue} >> coin      // deserialize into Coin object
                  return true
          if Read returned false → return nullopt
          Assert(!coin.IsSpent())                  // sanity check
          return coin                              // optional<Coin> with value
    │
    // optional<Coin> propagates back to HaveCoin
    // !! discards the fully-deserialized Coin, returns just bool

Original Version (without local changes)

CCoinsViewDB::HaveCoin(outpoint)               [old txdb.cpp]
  return m_db->Exists(CoinEntry(&outpoint))
    │
    └─► CDBWrapper::Exists(key)                [old dbwrapper.h]
          ssKey << key  // serialize CoinEntry
          return ExistsImpl(ssKey)
            │
            └─► CDBWrapper::ExistsImpl(span<byte>) [old dbwrapper.cpp, now deleted]
                  leveldb::DB::Get(readoptions, slKey, &strValue)
                  if IsNotFound → return false
                  if other error → LogError + HandleError (throws)
                  return true                  // bool only; strValue discarded

Key Differences

Aspect Original Current
Call depth 3 levels (HaveCoin → Exists → ExistsImpl) 6 levels (HaveCoin → GetCoin → Read → ReadRaw → ReadImpl → LevelDB)
LevelDB call pdb->Get() pdb->Get() (same)
Deobfuscation None — raw bytes discarded Yes — XOR applied to the value bytes
Deserialization None — raw bytes discarded Yes — full Coin object constructed
Sanity check None Assert(!coin.IsSpent())
Work discarded Raw strValue string (cheap) Fully constructed Coin object (expensive)
Return path bool returned directly from ExistsImpl optional<Coin> bubbles up, collapsed to bool by !!

Notes

  • Both versions issue one leveldb::DB::Get() call — there is no I/O difference.
  • The current version does substantially more CPU work for the same boolean result: it deobfuscates the raw bytes and deserializes them into a full Coin object (including reading CTxOut, amount, script, block height, coinbase flag), then immediately throws it all away via !!.
  • The original ExistsImpl discarded strValue before it ever left the function, never touching the value bytes beyond the LevelDB read.
  • The regression is a direct consequence of removing the dedicated ExistsImpl path and rerouting HaveCoin through GetCoin for code-reuse reasons.

@optout21

Copy link
Copy Markdown
Contributor

I find that it's relatively painless to remove HaveCoin from the CCoinsView interface (and from CCoinsViewDB), and keep only in the CCoinsViewCache class. HaveCoin is mostly called only on CCoinsViewCache (not on the interface!). (CC @sedited )

If the real goal here is slimming the interface, I suggest to do that and state that (but the current form of this PR I still find incoherent).

For minimal changes to remove HaveCoin, see optout21#15 .

@optout21

Copy link
Copy Markdown
Contributor

Continuing, I think the real design question raised here is: Is CCoinsView an interface:

A. For all coin stores, including CCoinsViewCache, or
B. For all coin stores that can be beneath CCoinsViewCache (but excluding itself)

A. does not fully hold currently, as there are several methods of CCoinsViewCache that are not on the interface, and invoked directly (HaveCoinInCache, AccessCoin, HaveInputs, etc.).
If HaveCoin is removed from the interface, that goes towards B., which is fine, as long as the scope of the interface is clear/clarified.

l0rinc and others added 4 commits June 23, 2026 11:16
Add unit tests covering `CCoinsViewCache::HaveInputs()`.
The tests document that `HaveInputs()` consults the cache first and that a cache miss pulls from the backing view via `GetCoin()`.
The spy view inherits from `CoinsViewEmpty` so only the `GetCoin()`/`HaveCoin()` interaction under test is customized.

Co-authored-by: Novo <[email protected]>
Split the raw LevelDB lookup into `CDBWrapper::ReadRaw()` so later commits can change typed `Read()` deserialization behavior without duplicating key serialization.

Move `Write()` below the read and existence helpers, and return from successful iterator decode paths inside the `try` blocks so this commit stays behavior-neutral.
`ExistsImpl` duplicates `CDBWrapper::ReadImpl()`: both issue a LevelDB `Get`, but only `ReadImpl()` keeps the returned bytes.

Introduce a small helper returning the raw value bytes as `std::string`, make `Read()` deserialize from it, and make `Exists()` just check whether the raw read succeeded.
After this series, `CCoinsViewDB::HaveCoin()` also goes through `GetCoin()` / `Read()`, while the remaining `CDBWrapper::Exists()` callers are infrequent metadata checks, so reusing `ReadRaw()` does not affect a performance-sensitive path.
`m_db->Exists(CoinEntry(&outpoint))` only checks whether some value is stored for the coin key, while `CCoinsViewDB::HaveCoin()` should match `GetCoin()` and report whether the outpoint can be read as an unspent `Coin`.

`CCoinsViewCache::HaveCoin()` already goes through `FetchCoin()` and `GetCoin()` on cache misses, so keep the required override but make it a thin adapter to `GetCoin()` instead of giving `CCoinsViewDB::HaveCoin()` its own `Exists()`-based semantics.
@l0rinc
l0rinc force-pushed the l0rinc/remove-HaveCoin branch from ccc0656 to dc4300b Compare June 23, 2026 18:26
hebasto added a commit that referenced this pull request Jul 17, 2026
…ially copyable types

3e8e21b txgraph: avoid moving primitive members (Lőrinc)
d9f94aa rpc: avoid moving RPC enum types (Lőrinc)
b67baed coins: avoid moving `COutPoint` values (Lőrinc)

Pull request description:

  Inspired by #34320 (comment).

  **Problem:** A few code paths use rvalue references or `std::move()` for types where moving provides no benefit.

  `EmplaceCoinInternalDANGER` took `COutPoint&&`, forcing callers to pass trivially copyable outpoints as rvalues even though the cache stores its own key.

  Some call sites also use `std::move()` on enum and primitive values, where it only adds noise.
  > [!NOTE]
  > `CheckTriviallyCopyableMove` remains `false` since `std::move()` on trivially copyable types can still be useful as intent documentation, for example to signal that a value should not be reused after a call.

  **Fix:** Take trivially copyable arguments by const reference where the callee only needs to store its own copy, and pass existing values directly at the call sites.

  Also remove `std::move()` from enum and primitive assignments where it has no semantic effect.

ACKs for top commit:
  maflcko:
    review ACK 3e8e21b 🖇
  hodlinator:
    re-ACK 3e8e21b
  andrewtoth:
    ACK 3e8e21b
  hebasto:
    ACK 3e8e21b, I have reviewed the code and it looks OK.

Tree-SHA512: cbe55b13290ae261bba359dc6e5a3bbdfb7ae9d31bdf8e0da2eef65a0df776e4081ceeac3c82731a631bda656a86b3789651fa1f4d87875cee1dc96351bdfd7c
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Jul 19, 2026
… for a few trivially copyable types

b871374 txgraph: avoid moving primitive members (Lőrinc)
1c048e9 rpc: avoid moving RPC enum types (Lőrinc)
74c1dc6 coins: avoid moving `COutPoint` values (Lőrinc)

Pull request description:

  Inspired by bitcoin/bitcoin#34320 (comment).

  **Problem:** A few code paths use rvalue references or `std::move()` for types where moving provides no benefit.

  `EmplaceCoinInternalDANGER` took `COutPoint&&`, forcing callers to pass trivially copyable outpoints as rvalues even though the cache stores its own key.

  Some call sites also use `std::move()` on enum and primitive values, where it only adds noise.
  > [!NOTE]
  > `CheckTriviallyCopyableMove` remains `false` since `std::move()` on trivially copyable types can still be useful as intent documentation, for example to signal that a value should not be reused after a call.

  **Fix:** Take trivially copyable arguments by const reference where the callee only needs to store its own copy, and pass existing values directly at the call sites.

  Also remove `std::move()` from enum and primitive assignments where it has no semantic effect.

ACKs for top commit:
  maflcko:
    review ACK b871374 🖇
  hodlinator:
    re-ACK b871374
  andrewtoth:
    ACK b871374
  hebasto:
    ACK b871374, I have reviewed the code and it looks OK.

Tree-SHA512: cbe55b13290ae261bba359dc6e5a3bbdfb7ae9d31bdf8e0da2eef65a0df776e4081ceeac3c82731a631bda656a86b3789651fa1f4d87875cee1dc96351bdfd7c
@l0rinc

l0rinc commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @optout21 for the thoughtful comments and for putting together the patch.
I did not manage to get back to this PR sooner, but I have now applied the cleanup in #34132, essentially cherry-picking your change there (with some minor cleanup) while preserving you as the commit author.
The result is much simpler this way, so I am closing this PR as superseded.

@l0rinc l0rinc closed this Aug 11, 2026
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Aug 19, 2026
… for a few trivially copyable types

3e8e21b2efcee4299f50030c37176ace29b315ec txgraph: avoid moving primitive members (Lőrinc)
d9f94aa882ae7ac5697d30c4478d9a1d633c3728 rpc: avoid moving RPC enum types (Lőrinc)
b67baed4e7e4c553426f1192a97725bc53b9df70 coins: avoid moving `COutPoint` values (Lőrinc)

Pull request description:

  Inspired by bitcoin/bitcoin#34320 (comment).

  **Problem:** A few code paths use rvalue references or `std::move()` for types where moving provides no benefit.

  `EmplaceCoinInternalDANGER` took `COutPoint&&`, forcing callers to pass trivially copyable outpoints as rvalues even though the cache stores its own key.

  Some call sites also use `std::move()` on enum and primitive values, where it only adds noise.
  > [!NOTE]
  > `CheckTriviallyCopyableMove` remains `false` since `std::move()` on trivially copyable types can still be useful as intent documentation, for example to signal that a value should not be reused after a call.

  **Fix:** Take trivially copyable arguments by const reference where the callee only needs to store its own copy, and pass existing values directly at the call sites.

  Also remove `std::move()` from enum and primitive assignments where it has no semantic effect.

ACKs for top commit:
  maflcko:
    review ACK 3e8e21b2efcee4299f50030c37176ace29b315ec 🖇
  hodlinator:
    re-ACK 3e8e21b2efcee4299f50030c37176ace29b315ec
  andrewtoth:
    ACK 3e8e21b2efcee4299f50030c37176ace29b315ec
  hebasto:
    ACK 3e8e21b2efcee4299f50030c37176ace29b315ec, I have reviewed the code and it looks OK.

Tree-SHA512: cbe55b13290ae261bba359dc6e5a3bbdfb7ae9d31bdf8e0da2eef65a0df776e4081ceeac3c82731a631bda656a86b3789651fa1f4d87875cee1dc96351bdfd7c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants