Skip to content

Commit

Permalink
Add perf counter data to GetStrongRandBytes state in scheduler
Browse files Browse the repository at this point in the history
Cherry-picked from: 888cce5
  • Loading branch information
TheBlueMatt authored and xanimo committed Mar 27, 2024
1 parent 1233452 commit acbaa5d
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

#include <stdlib.h>
#include <limits>
#include <chrono>
#include <thread>

#ifndef WIN32
#include <sys/time.h>
Expand Down Expand Up @@ -129,6 +131,23 @@ void GetRandBytes(unsigned char* buf, int num)
}
}

static void AddDataToRng(void* data, size_t len);

void RandAddSeedSleep()
{
int64_t nPerfCounter1 = GetPerformanceCounter();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
int64_t nPerfCounter2 = GetPerformanceCounter();

// Combine with and update state
AddDataToRng(&nPerfCounter1, sizeof(nPerfCounter1));
AddDataToRng(&nPerfCounter2, sizeof(nPerfCounter2));

memory_cleanse(&nPerfCounter1, sizeof(nPerfCounter1));
memory_cleanse(&nPerfCounter2, sizeof(nPerfCounter2));
}


static std::mutex cs_rng_state;
static unsigned char rng_state[32] = {0};
static uint64_t rng_counter = 0;
Expand Down
7 changes: 7 additions & 0 deletions src/random.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ uint64_t GetRand(uint64_t nMax);
int GetRandInt(int nMax);
uint256 GetRandHash();

/**
* Add a little bit of randomness to the output of GetStrongRangBytes.
* This sleeps for a millisecond, so should only be called when there is
* no other work to be done.
*/
void RandAddSeedSleep();

/**
* Function to gather random data from multiple sources, failing whenever any
* of those source fail to provide a result.
Expand Down
6 changes: 6 additions & 0 deletions src/scheduler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#include "scheduler.h"

#include "random.h"
#include "reverselock.h"

#include <assert.h>
Expand Down Expand Up @@ -38,6 +39,11 @@ void CScheduler::serviceQueue()
// is called.
while (!shouldStop()) {
try {
if (!shouldStop() && taskQueue.empty()) {
reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
// Use this chance to get a tiny bit more entropy
RandAddSeedSleep();
}
while (!shouldStop() && taskQueue.empty()) {
// Wait until there is something to do.
newTaskScheduled.wait(lock);
Expand Down

0 comments on commit acbaa5d

Please sign in to comment.