diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp index 3212f6d3701..3c574f89391 100644 --- a/src/dbwrapper.cpp +++ b/src/dbwrapper.cpp @@ -371,6 +371,8 @@ void CDBIterator::SeekImpl(std::span key) std::span CDBIterator::GetKeyImpl() const { + // The returned span borrows from the current iterator entry and is only + // valid until the iterator is advanced. return MakeByteSpan(m_impl_iter->iter->key()); } diff --git a/src/dbwrapper.h b/src/dbwrapper.h index f0cfe2dcfee..4710af16d9e 100644 --- a/src/dbwrapper.h +++ b/src/dbwrapper.h @@ -154,7 +154,7 @@ public: template bool GetKey(K& key) { try { - DataStream ssKey{GetKeyImpl()}; + SpanReader ssKey{GetKeyImpl()}; ssKey >> key; } catch (const std::exception&) { return false; diff --git a/src/test/dbwrapper_tests.cpp b/src/test/dbwrapper_tests.cpp index 19e70dedc1e..a57b77e3aeb 100644 --- a/src/test/dbwrapper_tests.cpp +++ b/src/test/dbwrapper_tests.cpp @@ -202,11 +202,15 @@ BOOST_AUTO_TEST_CASE(dbwrapper_iterator) uint256 in2 = m_rng.rand256(); dbw.Write(key2, in2); - std::unique_ptr it(const_cast(dbw).NewIterator()); + std::unique_ptr it(dbw.NewIterator()); // Be sure to seek past the obfuscation key (if it exists) it->Seek(key); + // A failed key decode must not consume the current iterator entry. + uint16_t key_too_large{0}; + BOOST_CHECK(!it->GetKey(key_too_large)); + uint8_t key_res; uint256 val_res;