Skip to content

Commit 806fc73

Browse files
Merge dashpay#5954: refactor: significant Mutex refactoring
acd0f49 refactor: significant Mutex refactoring (pasta) Pull request description: ## Issue being fixed or feature implemented Don't use generic names; recursive mutexes where not needed; etc ## What was done? Includes: RecursiveMutex -> Mutex, renaming of `cs` to something more meaningful, usage of atomics where trivially possible, introduce a method CQuorum::SetVerificationVector to avoid needing to lock an internal mutex externally ## How Has This Been Tested? Compiling ## Breaking Changes None ## Checklist: _Go over all the following points, and put an `x` in all the boxes that apply._ - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have added or updated relevant unit/integration/functional/e2e tests - [ ] I have made corresponding changes to the documentation - [x] I have assigned this pull request to a milestone _(for repository code-owners and collaborators only)_ Top commit has no ACKs. Tree-SHA512: 76d0ee37e348680bdcd8f03237d3fc1febbf908a9c13e6ddea7be52a35adfca35cde3001ce6ecb140d7dba950ad19519d34d137de17a073306e3e7b26cb95b70
2 parents 26cfbb0 + acd0f49 commit 806fc73

File tree

11 files changed

+134
-152
lines changed

11 files changed

+134
-152
lines changed

src/llmq/debug.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,13 +138,13 @@ UniValue CDKGDebugStatus::ToJson(CDeterministicMNManager& dmnman, const Chainsta
138138

139139
void CDKGDebugManager::GetLocalDebugStatus(llmq::CDKGDebugStatus& ret) const
140140
{
141-
LOCK(cs);
141+
LOCK(cs_lockStatus);
142142
ret = localStatus;
143143
}
144144

145145
void CDKGDebugManager::ResetLocalSessionStatus(Consensus::LLMQType llmqType, int quorumIndex)
146146
{
147-
LOCK(cs);
147+
LOCK(cs_lockStatus);
148148

149149
auto it = localStatus.sessions.find(std::make_pair(llmqType, quorumIndex));
150150
if (it == localStatus.sessions.end()) {
@@ -157,7 +157,7 @@ void CDKGDebugManager::ResetLocalSessionStatus(Consensus::LLMQType llmqType, int
157157

158158
void CDKGDebugManager::InitLocalSessionStatus(const Consensus::LLMQParams& llmqParams, int quorumIndex, const uint256& quorumHash, int quorumHeight)
159159
{
160-
LOCK(cs);
160+
LOCK(cs_lockStatus);
161161

162162
auto it = localStatus.sessions.find(std::make_pair(llmqParams.type, quorumIndex));
163163
if (it == localStatus.sessions.end()) {
@@ -176,7 +176,7 @@ void CDKGDebugManager::InitLocalSessionStatus(const Consensus::LLMQParams& llmqP
176176

177177
void CDKGDebugManager::UpdateLocalSessionStatus(Consensus::LLMQType llmqType, int quorumIndex, std::function<bool(CDKGDebugSessionStatus& status)>&& func)
178178
{
179-
LOCK(cs);
179+
LOCK(cs_lockStatus);
180180

181181
auto it = localStatus.sessions.find(std::make_pair(llmqType, quorumIndex));
182182
if (it == localStatus.sessions.end()) {
@@ -190,7 +190,7 @@ void CDKGDebugManager::UpdateLocalSessionStatus(Consensus::LLMQType llmqType, in
190190

191191
void CDKGDebugManager::UpdateLocalMemberStatus(Consensus::LLMQType llmqType, int quorumIndex, size_t memberIdx, std::function<bool(CDKGDebugMemberStatus& status)>&& func)
192192
{
193-
LOCK(cs);
193+
LOCK(cs_lockStatus);
194194

195195
auto it = localStatus.sessions.find(std::make_pair(llmqType, quorumIndex));
196196
if (it == localStatus.sessions.end()) {

src/llmq/debug.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,8 @@ class CDKGDebugStatus
9696
class CDKGDebugManager
9797
{
9898
private:
99-
mutable RecursiveMutex cs;
100-
CDKGDebugStatus localStatus GUARDED_BY(cs);
99+
mutable Mutex cs_lockStatus;
100+
CDKGDebugStatus localStatus GUARDED_BY(cs_lockStatus);
101101

102102
public:
103103
CDKGDebugManager();

src/llmq/dkgsession.cpp

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -261,8 +261,6 @@ bool CDKGSession::PreVerifyMessage(const CDKGContribution& qc, bool& retBan) con
261261

262262
void CDKGSession::ReceiveMessage(const CDKGContribution& qc, bool& retBan)
263263
{
264-
LOCK(cs_pending);
265-
266264
CDKGLogger logger(*this, __func__, __LINE__);
267265

268266
retBan = false;
@@ -336,15 +334,11 @@ void CDKGSession::ReceiveMessage(const CDKGContribution& qc, bool& retBan)
336334

337335
logger.Batch("decrypted our contribution share. time=%d", t2.count());
338336

339-
bool verifyPending = false;
340337
receivedSkContributions[member->idx] = skContribution;
341338
vecEncryptedContributions[member->idx] = qc.contributions;
339+
LOCK(cs_pending);
342340
pendingContributionVerifications.emplace_back(member->idx);
343341
if (pendingContributionVerifications.size() >= 32) {
344-
verifyPending = true;
345-
}
346-
347-
if (verifyPending) {
348342
VerifyPendingContributions();
349343
}
350344
}

src/llmq/dkgsession.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -308,13 +308,13 @@ class CDKGSession
308308
// we expect to only receive a single vvec and contribution per member, but we must also be able to relay
309309
// conflicting messages as otherwise an attacker might be able to broadcast conflicting (valid+invalid) messages
310310
// and thus split the quorum. Such members are later removed from the quorum.
311-
mutable RecursiveMutex invCs;
311+
mutable Mutex invCs;
312312
std::map<uint256, CDKGContribution> contributions GUARDED_BY(invCs);
313313
std::map<uint256, CDKGComplaint> complaints GUARDED_BY(invCs);
314314
std::map<uint256, CDKGJustification> justifications GUARDED_BY(invCs);
315315
std::map<uint256, CDKGPrematureCommitment> prematureCommitments GUARDED_BY(invCs);
316316

317-
mutable RecursiveMutex cs_pending;
317+
mutable Mutex cs_pending;
318318
std::vector<size_t> pendingContributionVerifications GUARDED_BY(cs_pending);
319319

320320
// filled by ReceivePrematureCommitment and used by FinalizeCommitments

src/llmq/dkgsessionhandler.cpp

Lines changed: 26 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ void CDKGPendingMessages::PushPendingMessage(NodeId from, PeerManager* peerman,
7676
EraseObjectRequest(from, CInv(invType, hash));
7777
}
7878

79-
LOCK(cs);
79+
LOCK(cs_messages);
8080

8181
if (messagesPerNode[from] >= maxMessagesPerNode) {
8282
// TODO ban?
@@ -95,7 +95,7 @@ void CDKGPendingMessages::PushPendingMessage(NodeId from, PeerManager* peerman,
9595

9696
std::list<CDKGPendingMessages::BinaryMessage> CDKGPendingMessages::PopPendingMessages(size_t maxCount)
9797
{
98-
LOCK(cs);
98+
LOCK(cs_messages);
9999

100100
std::list<BinaryMessage> ret;
101101
while (!pendingMessages.empty() && ret.size() < maxCount) {
@@ -108,7 +108,7 @@ std::list<CDKGPendingMessages::BinaryMessage> CDKGPendingMessages::PopPendingMes
108108

109109
bool CDKGPendingMessages::HasSeen(const uint256& hash) const
110110
{
111-
LOCK(cs);
111+
LOCK(cs_messages);
112112
return seenMessages.count(hash) != 0;
113113
}
114114

@@ -120,7 +120,7 @@ void CDKGPendingMessages::Misbehaving(const NodeId from, const int score)
120120

121121
void CDKGPendingMessages::Clear()
122122
{
123-
LOCK(cs);
123+
LOCK(cs_messages);
124124
pendingMessages.clear();
125125
messagesPerNode.clear();
126126
seenMessages.clear();
@@ -135,7 +135,7 @@ void CDKGSessionHandler::UpdatedBlockTip(const CBlockIndex* pindexNew)
135135
if (quorumIndex > 0 && !IsQuorumRotationEnabled(params, pindexNew)) {
136136
return;
137137
}
138-
LOCK(cs);
138+
LOCK(cs_phase_qhash);
139139

140140
int quorumStageInt = (pindexNew->nHeight - quorumIndex) % params.dkgInterval;
141141

@@ -207,7 +207,7 @@ bool CDKGSessionHandler::InitNewQuorum(const CBlockIndex* pQuorumBaseBlockIndex)
207207

208208
std::pair<QuorumPhase, uint256> CDKGSessionHandler::GetPhaseAndQuorumHash() const
209209
{
210-
LOCK(cs);
210+
LOCK(cs_phase_qhash);
211211
return std::make_pair(phase, quorumHash);
212212
}
213213

@@ -304,9 +304,8 @@ void CDKGSessionHandler::SleepBeforePhase(QuorumPhase curPhase,
304304

305305
int64_t sleepTime = (int64_t)(adjustedPhaseSleepTimePerMember * curSession->GetMyMemberIndex().value_or(0));
306306
int64_t endTime = GetTimeMillis() + sleepTime;
307-
int heightTmp{-1};
308-
int heightStart{-1};
309-
heightTmp = heightStart = WITH_LOCK(cs, return currentHeight);
307+
int heightTmp{currentHeight.load()};
308+
int heightStart{heightTmp};
310309

311310
LogPrint(BCLog::LLMQ_DKG, "CDKGSessionManager::%s -- %s qi[%d] - starting sleep for %d ms, curPhase=%d\n", __func__, params.name, quorumIndex, sleepTime, ToUnderlying(curPhase));
312311

@@ -315,22 +314,20 @@ void CDKGSessionHandler::SleepBeforePhase(QuorumPhase curPhase,
315314
LogPrint(BCLog::LLMQ_DKG, "CDKGSessionManager::%s -- %s qi[%d] - aborting due to stop/shutdown requested\n", __func__, params.name, quorumIndex);
316315
throw AbortPhaseException();
317316
}
318-
{
319-
LOCK(cs);
320-
if (currentHeight > heightTmp) {
321-
// New block(s) just came in
322-
int64_t expectedBlockTime = (currentHeight - heightStart) * Params().GetConsensus().nPowTargetSpacing * 1000;
323-
if (expectedBlockTime > sleepTime) {
324-
// Blocks came faster than we expected, jump into the phase func asap
325-
break;
326-
}
327-
heightTmp = currentHeight;
328-
}
329-
if (phase != curPhase || quorumHash != expectedQuorumHash) {
330-
// Something went wrong and/or we missed quite a few blocks and it's just too late now
331-
LogPrint(BCLog::LLMQ_DKG, "CDKGSessionManager::%s -- %s qi[%d] - aborting due unexpected phase/expectedQuorumHash change\n", __func__, params.name, quorumIndex);
332-
throw AbortPhaseException();
317+
auto cur_height = currentHeight.load();
318+
if (cur_height > heightTmp) {
319+
// New block(s) just came in
320+
int64_t expectedBlockTime = (cur_height - heightStart) * Params().GetConsensus().nPowTargetSpacing * 1000;
321+
if (expectedBlockTime > sleepTime) {
322+
// Blocks came faster than we expected, jump into the phase func asap
323+
break;
333324
}
325+
heightTmp = cur_height;
326+
}
327+
if (WITH_LOCK(cs_phase_qhash, return phase != curPhase || quorumHash != expectedQuorumHash)) {
328+
// Something went wrong and/or we missed quite a few blocks and it's just too late now
329+
LogPrint(BCLog::LLMQ_DKG, "CDKGSessionManager::%s -- %s qi[%d] - aborting due unexpected phase/expectedQuorumHash change\n", __func__, params.name, quorumIndex);
330+
throw AbortPhaseException();
334331
}
335332
if (!runWhileWaiting()) {
336333
UninterruptibleSleep(std::chrono::milliseconds{100});
@@ -505,18 +502,13 @@ bool ProcessPendingMessageBatch(CDKGSession& session, CDKGPendingMessages& pendi
505502

506503
void CDKGSessionHandler::HandleDKGRound()
507504
{
508-
uint256 curQuorumHash;
509-
510505
WaitForNextPhase(std::nullopt, QuorumPhase::Initialized);
511506

512-
{
513-
LOCK(cs);
514-
pendingContributions.Clear();
515-
pendingComplaints.Clear();
516-
pendingJustifications.Clear();
517-
pendingPrematureCommitments.Clear();
518-
curQuorumHash = quorumHash;
519-
}
507+
pendingContributions.Clear();
508+
pendingComplaints.Clear();
509+
pendingJustifications.Clear();
510+
pendingPrematureCommitments.Clear();
511+
uint256 curQuorumHash = WITH_LOCK(cs_phase_qhash, return quorumHash);
520512

521513
const CBlockIndex* pQuorumBaseBlockIndex = WITH_LOCK(cs_main, return m_chainstate.m_blockman.LookupBlockIndex(curQuorumHash));
522514

src/llmq/dkgsessionhandler.h

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,13 @@ class CDKGPendingMessages
5454
using BinaryMessage = std::pair<NodeId, std::shared_ptr<CDataStream>>;
5555

5656
private:
57-
mutable RecursiveMutex cs;
5857
std::atomic<PeerManager*> m_peerman{nullptr};
5958
const int invType;
60-
size_t maxMessagesPerNode GUARDED_BY(cs);
61-
std::list<BinaryMessage> pendingMessages GUARDED_BY(cs);
62-
std::map<NodeId, size_t> messagesPerNode GUARDED_BY(cs);
63-
std::set<uint256> seenMessages GUARDED_BY(cs);
59+
const size_t maxMessagesPerNode;
60+
mutable Mutex cs_messages;
61+
std::list<BinaryMessage> pendingMessages GUARDED_BY(cs_messages);
62+
std::map<NodeId, size_t> messagesPerNode GUARDED_BY(cs_messages);
63+
std::set<uint256> seenMessages GUARDED_BY(cs_messages);
6464

6565
public:
6666
explicit CDKGPendingMessages(size_t _maxMessagesPerNode, int _invType) :
@@ -117,7 +117,6 @@ class CDKGSessionHandler
117117
friend class CDKGSessionManager;
118118

119119
private:
120-
mutable RecursiveMutex cs;
121120
std::atomic<bool> stopRequested{false};
122121

123122
CBLSWorker& blsWorker;
@@ -134,9 +133,10 @@ class CDKGSessionHandler
134133
const Consensus::LLMQParams params;
135134
const int quorumIndex;
136135

137-
QuorumPhase phase GUARDED_BY(cs) {QuorumPhase::Idle};
138-
int currentHeight GUARDED_BY(cs) {-1};
139-
uint256 quorumHash GUARDED_BY(cs);
136+
std::atomic<int> currentHeight {-1};
137+
mutable Mutex cs_phase_qhash;
138+
QuorumPhase phase GUARDED_BY(cs_phase_qhash) {QuorumPhase::Idle};
139+
uint256 quorumHash GUARDED_BY(cs_phase_qhash);
140140

141141
std::unique_ptr<CDKGSession> curSession;
142142
std::thread phaseHandlerThread;

src/llmq/dkgsessionmgr.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ bool CDKGSessionManager::GetContribution(const uint256& hash, CDKGContribution&
293293

294294
for (const auto& p : dkgSessionHandlers) {
295295
const auto& dkgType = p.second;
296-
LOCK(dkgType.cs);
296+
LOCK(dkgType.cs_phase_qhash);
297297
if (dkgType.phase < QuorumPhase::Initialized || dkgType.phase > QuorumPhase::Contribute) {
298298
continue;
299299
}
@@ -314,7 +314,7 @@ bool CDKGSessionManager::GetComplaint(const uint256& hash, CDKGComplaint& ret) c
314314

315315
for (const auto& p : dkgSessionHandlers) {
316316
const auto& dkgType = p.second;
317-
LOCK(dkgType.cs);
317+
LOCK(dkgType.cs_phase_qhash);
318318
if (dkgType.phase < QuorumPhase::Contribute || dkgType.phase > QuorumPhase::Complain) {
319319
continue;
320320
}
@@ -335,7 +335,7 @@ bool CDKGSessionManager::GetJustification(const uint256& hash, CDKGJustification
335335

336336
for (const auto& p : dkgSessionHandlers) {
337337
const auto& dkgType = p.second;
338-
LOCK(dkgType.cs);
338+
LOCK(dkgType.cs_phase_qhash);
339339
if (dkgType.phase < QuorumPhase::Complain || dkgType.phase > QuorumPhase::Justify) {
340340
continue;
341341
}
@@ -356,7 +356,7 @@ bool CDKGSessionManager::GetPrematureCommitment(const uint256& hash, CDKGPrematu
356356

357357
for (const auto& p : dkgSessionHandlers) {
358358
const auto& dkgType = p.second;
359-
LOCK(dkgType.cs);
359+
LOCK(dkgType.cs_phase_qhash);
360360
if (dkgType.phase < QuorumPhase::Justify || dkgType.phase > QuorumPhase::Commit) {
361361
continue;
362362
}

0 commit comments

Comments
 (0)