Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2015-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <sync.h>6#include <test/util/common.h>8#include <boost/test/unit_test.hpp>10#include <stdexcept>12BOOST_AUTO_TEST_SUITE(reverselock_tests)14BOOST_AUTO_TEST_CASE(reverselock_basics)15{16Mutex mutex;17WAIT_LOCK(mutex, lock);19BOOST_CHECK(lock.owns_lock());20AssertLockHeld(mutex);21{22REVERSE_LOCK(lock, mutex);23AssertLockNotHeld(mutex);24BOOST_CHECK(!lock.owns_lock());25}26BOOST_CHECK(lock.owns_lock());27}29BOOST_AUTO_TEST_CASE(reverselock_multiple)30{31Mutex mutex2;32Mutex mutex;33WAIT_LOCK(mutex2, lock2);34WAIT_LOCK(mutex, lock);36// Make sure undoing two locks succeeds37{38REVERSE_LOCK(lock, mutex);39BOOST_CHECK(!lock.owns_lock());40REVERSE_LOCK(lock2, mutex2);41BOOST_CHECK(!lock2.owns_lock());42}43BOOST_CHECK(lock.owns_lock());44BOOST_CHECK(lock2.owns_lock());45}47BOOST_AUTO_TEST_CASE(reverselock_errors)48{49Mutex mutex2;50Mutex mutex;51WAIT_LOCK(mutex2, lock2);52WAIT_LOCK(mutex, lock);54#ifdef DEBUG_LOCKORDER55bool prev = g_debug_lockorder_abort;56g_debug_lockorder_abort = false;58// Make sure trying to reverse lock a previous lock fails59BOOST_CHECK_EXCEPTION(REVERSE_LOCK(lock2, mutex2), std::logic_error, HasReason{"mutex2 was not most recent critical section locked"});60BOOST_CHECK(lock2.owns_lock());62g_debug_lockorder_abort = prev;63#endif65// Make sure trying to reverse lock an unlocked lock fails66lock.unlock();68BOOST_CHECK(!lock.owns_lock());70BOOST_CHECK_EXCEPTION(REVERSE_LOCK(lock, mutex), std::system_error,71[](const std::system_error& e) { return e.code() == std::errc::operation_not_permitted; });73BOOST_CHECK(!lock.owns_lock());75// Locking the original lock after it has been taken by a reverse lock76// makes no sense. Ensure that the original lock no longer owns the lock77// after giving it to a reverse one.79lock.lock();80BOOST_CHECK(lock.owns_lock());81{82REVERSE_LOCK(lock, mutex);83BOOST_CHECK(!lock.owns_lock());84}86BOOST_CHECK(lock.owns_lock());87}89BOOST_AUTO_TEST_SUITE_END()
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.