Skip to content

Commit 1ac1c33

Browse files
committed
[checkqueue] support user-defined return type through std::optional
The check type function now needs to return a std::optional<R> for some type R, and the check queue overall will return std::nullopt if all individual checks return that, or one of the non-nullopt values if there is at least one. For most tests, we use R=int, but for the actual validation code, we make it return the ScriptError.
1 parent ebe4cac commit 1ac1c33

8 files changed

+107
-92
lines changed

src/bench/checkqueue.cpp

+3-3
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ static void CCheckQueueSpeedPrevectorJob(benchmark::Bench& bench)
3434
explicit PrevectorJob(FastRandomContext& insecure_rand){
3535
p.resize(insecure_rand.randrange(PREVECTOR_SIZE*2));
3636
}
37-
bool operator()()
37+
std::optional<int> operator()()
3838
{
39-
return true;
39+
return std::nullopt;
4040
}
4141
};
4242

@@ -62,7 +62,7 @@ static void CCheckQueueSpeedPrevectorJob(benchmark::Bench& bench)
6262
}
6363
// control waits for completion by RAII, but
6464
// it is done explicitly here for clarity
65-
control.Wait();
65+
control.Complete();
6666
});
6767
}
6868
BENCHMARK(CCheckQueueSpeedPrevectorJob, benchmark::PriorityLevel::HIGH);

src/checkqueue.h

+39-26
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,24 @@
1111

1212
#include <algorithm>
1313
#include <iterator>
14+
#include <optional>
1415
#include <vector>
1516

1617
/**
1718
* Queue for verifications that have to be performed.
1819
* The verifications are represented by a type T, which must provide an
19-
* operator(), returning a bool.
20+
* operator(), returning an std::optional<R>.
21+
*
22+
* The overall result of the computation is std::nullopt if all invocations
23+
* return std::nullopt, or one of the other results otherwise.
2024
*
2125
* One thread (the master) is assumed to push batches of verifications
2226
* onto the queue, where they are processed by N-1 worker threads. When
2327
* the master is done adding work, it temporarily joins the worker pool
2428
* as an N'th worker, until all jobs are done.
29+
*
2530
*/
26-
template <typename T>
31+
template <typename T, typename R = std::remove_cvref_t<decltype(std::declval<T>()().value())>>
2732
class CCheckQueue
2833
{
2934
private:
@@ -47,7 +52,7 @@ class CCheckQueue
4752
int nTotal GUARDED_BY(m_mutex){0};
4853

4954
//! The temporary evaluation result.
50-
bool fAllOk GUARDED_BY(m_mutex){true};
55+
std::optional<R> m_result GUARDED_BY(m_mutex);
5156

5257
/**
5358
* Number of verifications that haven't completed yet.
@@ -62,24 +67,28 @@ class CCheckQueue
6267
std::vector<std::thread> m_worker_threads;
6368
bool m_request_stop GUARDED_BY(m_mutex){false};
6469

65-
/** Internal function that does bulk of the verification work. */
66-
bool Loop(bool fMaster) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
70+
/** Internal function that does bulk of the verification work. If fMaster, return the final result. */
71+
std::optional<R> Loop(bool fMaster) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
6772
{
6873
std::condition_variable& cond = fMaster ? m_master_cv : m_worker_cv;
6974
std::vector<T> vChecks;
7075
vChecks.reserve(nBatchSize);
7176
unsigned int nNow = 0;
72-
bool fOk = true;
77+
std::optional<R> local_result;
78+
bool do_work;
7379
do {
7480
{
7581
WAIT_LOCK(m_mutex, lock);
7682
// first do the clean-up of the previous loop run (allowing us to do it in the same critsect)
7783
if (nNow) {
78-
fAllOk &= fOk;
84+
if (local_result.has_value() && !m_result.has_value()) {
85+
std::swap(local_result, m_result);
86+
}
7987
nTodo -= nNow;
80-
if (nTodo == 0 && !fMaster)
88+
if (nTodo == 0 && !fMaster) {
8189
// We processed the last element; inform the master it can exit and return the result
8290
m_master_cv.notify_one();
91+
}
8392
} else {
8493
// first iteration
8594
nTotal++;
@@ -88,18 +97,19 @@ class CCheckQueue
8897
while (queue.empty() && !m_request_stop) {
8998
if (fMaster && nTodo == 0) {
9099
nTotal--;
91-
bool fRet = fAllOk;
100+
std::optional<R> to_return = std::move(m_result);
92101
// reset the status for new work later
93-
fAllOk = true;
102+
m_result = std::nullopt;
94103
// return the current status
95-
return fRet;
104+
return to_return;
96105
}
97106
nIdle++;
98107
cond.wait(lock); // wait
99108
nIdle--;
100109
}
101110
if (m_request_stop) {
102-
return false;
111+
// return value does not matter, because m_request_stop is only set in the destructor.
112+
return std::nullopt;
103113
}
104114

105115
// Decide how many work units to process now.
@@ -112,12 +122,15 @@ class CCheckQueue
112122
vChecks.assign(std::make_move_iterator(start_it), std::make_move_iterator(queue.end()));
113123
queue.erase(start_it, queue.end());
114124
// Check whether we need to do work at all
115-
fOk = fAllOk;
125+
do_work = !m_result.has_value();
116126
}
117127
// execute work
118-
for (T& check : vChecks)
119-
if (fOk)
120-
fOk = check();
128+
if (do_work) {
129+
for (T& check : vChecks) {
130+
local_result = check();
131+
if (local_result.has_value()) break;
132+
}
133+
}
121134
vChecks.clear();
122135
} while (true);
123136
}
@@ -146,8 +159,9 @@ class CCheckQueue
146159
CCheckQueue(CCheckQueue&&) = delete;
147160
CCheckQueue& operator=(CCheckQueue&&) = delete;
148161

149-
//! Wait until execution finishes, and return whether all evaluations were successful.
150-
bool Wait() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
162+
//! Join the execution until completion. If at least one evaluation wasn't successful, return
163+
//! its error.
164+
std::optional<R> Complete() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
151165
{
152166
return Loop(true /* master thread */);
153167
}
@@ -188,11 +202,11 @@ class CCheckQueue
188202
* RAII-style controller object for a CCheckQueue that guarantees the passed
189203
* queue is finished before continuing.
190204
*/
191-
template <typename T>
205+
template <typename T, typename R = std::remove_cvref_t<decltype(std::declval<T>()().value())>>
192206
class CCheckQueueControl
193207
{
194208
private:
195-
CCheckQueue<T> * const pqueue;
209+
CCheckQueue<T, R> * const pqueue;
196210
bool fDone;
197211

198212
public:
@@ -207,13 +221,12 @@ class CCheckQueueControl
207221
}
208222
}
209223

210-
bool Wait()
224+
std::optional<R> Complete()
211225
{
212-
if (pqueue == nullptr)
213-
return true;
214-
bool fRet = pqueue->Wait();
226+
if (pqueue == nullptr) return std::nullopt;
227+
auto ret = pqueue->Complete();
215228
fDone = true;
216-
return fRet;
229+
return ret;
217230
}
218231

219232
void Add(std::vector<T>&& vChecks)
@@ -226,7 +239,7 @@ class CCheckQueueControl
226239
~CCheckQueueControl()
227240
{
228241
if (!fDone)
229-
Wait();
242+
Complete();
230243
if (pqueue != nullptr) {
231244
LEAVE_CRITICAL_SECTION(pqueue->m_control_mutex);
232245
}

src/test/checkqueue_tests.cpp

+34-36
Original file line numberDiff line numberDiff line change
@@ -42,50 +42,48 @@ static const unsigned int QUEUE_BATCH_SIZE = 128;
4242
static const int SCRIPT_CHECK_THREADS = 3;
4343

4444
struct FakeCheck {
45-
bool operator()() const
45+
std::optional<int> operator()() const
4646
{
47-
return true;
47+
return std::nullopt;
4848
}
4949
};
5050

5151
struct FakeCheckCheckCompletion {
5252
static std::atomic<size_t> n_calls;
53-
bool operator()()
53+
std::optional<int> operator()()
5454
{
5555
n_calls.fetch_add(1, std::memory_order_relaxed);
56-
return true;
56+
return std::nullopt;
5757
}
5858
};
5959

60-
struct FailingCheck {
61-
bool fails;
62-
FailingCheck(bool _fails) : fails(_fails){};
63-
bool operator()() const
64-
{
65-
return !fails;
66-
}
60+
struct FixedCheck
61+
{
62+
std::optional<int> m_result;
63+
FixedCheck(std::optional<int> result) : m_result(result){};
64+
std::optional<int> operator()() const { return m_result; }
6765
};
6866

6967
struct UniqueCheck {
7068
static Mutex m;
7169
static std::unordered_multiset<size_t> results GUARDED_BY(m);
7270
size_t check_id;
7371
UniqueCheck(size_t check_id_in) : check_id(check_id_in){};
74-
bool operator()()
72+
std::optional<int> operator()()
7573
{
7674
LOCK(m);
7775
results.insert(check_id);
78-
return true;
76+
return std::nullopt;
7977
}
8078
};
8179

8280

8381
struct MemoryCheck {
8482
static std::atomic<size_t> fake_allocated_memory;
8583
bool b {false};
86-
bool operator()() const
84+
std::optional<int> operator()() const
8785
{
88-
return true;
86+
return std::nullopt;
8987
}
9088
MemoryCheck(const MemoryCheck& x)
9189
{
@@ -110,9 +108,9 @@ struct FrozenCleanupCheck {
110108
static std::condition_variable cv;
111109
static std::mutex m;
112110
bool should_freeze{true};
113-
bool operator()() const
111+
std::optional<int> operator()() const
114112
{
115-
return true;
113+
return std::nullopt;
116114
}
117115
FrozenCleanupCheck() = default;
118116
~FrozenCleanupCheck()
@@ -149,7 +147,7 @@ std::atomic<size_t> MemoryCheck::fake_allocated_memory{0};
149147
// Queue Typedefs
150148
typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue;
151149
typedef CCheckQueue<FakeCheck> Standard_Queue;
152-
typedef CCheckQueue<FailingCheck> Failing_Queue;
150+
typedef CCheckQueue<FixedCheck> Fixed_Queue;
153151
typedef CCheckQueue<UniqueCheck> Unique_Queue;
154152
typedef CCheckQueue<MemoryCheck> Memory_Queue;
155153
typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue;
@@ -174,7 +172,7 @@ void CheckQueueTest::Correct_Queue_range(std::vector<size_t> range)
174172
total -= vChecks.size();
175173
control.Add(std::move(vChecks));
176174
}
177-
BOOST_REQUIRE(control.Wait());
175+
BOOST_REQUIRE(!control.Complete().has_value());
178176
BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i);
179177
}
180178
}
@@ -217,45 +215,45 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random)
217215
}
218216

219217

220-
/** Test that failing checks are caught */
218+
/** Test that distinct failing checks are caught */
221219
BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure)
222220
{
223-
auto fail_queue = std::make_unique<Failing_Queue>(QUEUE_BATCH_SIZE, SCRIPT_CHECK_THREADS);
221+
auto fixed_queue = std::make_unique<Fixed_Queue>(QUEUE_BATCH_SIZE, SCRIPT_CHECK_THREADS);
224222
for (size_t i = 0; i < 1001; ++i) {
225-
CCheckQueueControl<FailingCheck> control(fail_queue.get());
223+
CCheckQueueControl<FixedCheck> control(fixed_queue.get());
226224
size_t remaining = i;
227225
while (remaining) {
228226
size_t r = m_rng.randrange(10);
229227

230-
std::vector<FailingCheck> vChecks;
228+
std::vector<FixedCheck> vChecks;
231229
vChecks.reserve(r);
232230
for (size_t k = 0; k < r && remaining; k++, remaining--)
233-
vChecks.emplace_back(remaining == 1);
231+
vChecks.emplace_back(remaining == 1 ? std::make_optional<int>(17 * i) : std::nullopt);
234232
control.Add(std::move(vChecks));
235233
}
236-
bool success = control.Wait();
234+
auto result = control.Complete();
237235
if (i > 0) {
238-
BOOST_REQUIRE(!success);
239-
} else if (i == 0) {
240-
BOOST_REQUIRE(success);
236+
BOOST_REQUIRE(result.has_value() && *result == static_cast<int>(17 * i));
237+
} else {
238+
BOOST_REQUIRE(!result.has_value());
241239
}
242240
}
243241
}
244242
// Test that a block validation which fails does not interfere with
245243
// future blocks, ie, the bad state is cleared.
246244
BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure)
247245
{
248-
auto fail_queue = std::make_unique<Failing_Queue>(QUEUE_BATCH_SIZE, SCRIPT_CHECK_THREADS);
246+
auto fail_queue = std::make_unique<Fixed_Queue>(QUEUE_BATCH_SIZE, SCRIPT_CHECK_THREADS);
249247
for (auto times = 0; times < 10; ++times) {
250248
for (const bool end_fails : {true, false}) {
251-
CCheckQueueControl<FailingCheck> control(fail_queue.get());
249+
CCheckQueueControl<FixedCheck> control(fail_queue.get());
252250
{
253-
std::vector<FailingCheck> vChecks;
254-
vChecks.resize(100, false);
255-
vChecks[99] = end_fails;
251+
std::vector<FixedCheck> vChecks;
252+
vChecks.resize(100, FixedCheck(std::nullopt));
253+
vChecks[99] = FixedCheck(end_fails ? std::make_optional<int>(2) : std::nullopt);
256254
control.Add(std::move(vChecks));
257255
}
258-
bool r =control.Wait();
256+
bool r = !control.Complete().has_value();
259257
BOOST_REQUIRE(r != end_fails);
260258
}
261259
}
@@ -329,8 +327,8 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup)
329327
CCheckQueueControl<FrozenCleanupCheck> control(queue.get());
330328
std::vector<FrozenCleanupCheck> vChecks(1);
331329
control.Add(std::move(vChecks));
332-
bool waitResult = control.Wait(); // Hangs here
333-
assert(waitResult);
330+
auto result = control.Complete(); // Hangs here
331+
assert(!result);
334332
});
335333
{
336334
std::unique_lock<std::mutex> l(FrozenCleanupCheck::m);

src/test/fuzz/checkqueue.cpp

+5-4
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@ struct DumbCheck {
1919
{
2020
}
2121

22-
bool operator()() const
22+
std::optional<int> operator()() const
2323
{
24-
return result;
24+
if (result) return std::nullopt;
25+
return 1;
2526
}
2627
};
2728
} // namespace
@@ -45,14 +46,14 @@ FUZZ_TARGET(checkqueue)
4546
check_queue_1.Add(std::move(checks_1));
4647
}
4748
if (fuzzed_data_provider.ConsumeBool()) {
48-
(void)check_queue_1.Wait();
49+
(void)check_queue_1.Complete();
4950
}
5051

5152
CCheckQueueControl<DumbCheck> check_queue_control{&check_queue_2};
5253
if (fuzzed_data_provider.ConsumeBool()) {
5354
check_queue_control.Add(std::move(checks_2));
5455
}
5556
if (fuzzed_data_provider.ConsumeBool()) {
56-
(void)check_queue_control.Wait();
57+
(void)check_queue_control.Complete();
5758
}
5859
}

src/test/script_p2sh_tests.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ BOOST_AUTO_TEST_CASE(sign)
121121
{
122122
CScript sigSave = txTo[i].vin[0].scriptSig;
123123
txTo[i].vin[0].scriptSig = txTo[j].vin[0].scriptSig;
124-
bool sigOK = CScriptCheck(txFrom.vout[txTo[i].vin[0].prevout.n], CTransaction(txTo[i]), signature_cache, 0, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, false, &txdata)();
124+
bool sigOK = !CScriptCheck(txFrom.vout[txTo[i].vin[0].prevout.n], CTransaction(txTo[i]), signature_cache, 0, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, false, &txdata)().has_value();
125125
if (i == j)
126126
BOOST_CHECK_MESSAGE(sigOK, strprintf("VerifySignature %d %d", i, j));
127127
else

0 commit comments

Comments
 (0)