forked from ciphrex/mSIGNA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentropysource.cpp
112 lines (89 loc) · 2.25 KB
/
entropysource.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
///////////////////////////////////////////////////////////////////////////////
//
// mSIGNA
//
// entropydialog.cpp
//
// Copyright (c) 2014 Eric Lombrozo
//
// All Rights Reserved.
#include "entropysource.h"
#include "entropydialog.h"
#include <logger/logger.h>
#include <CoinCore/random.h>
#include <QApplication>
#include <thread>
#include <chrono>
#include <stdexcept>
using namespace std;
class EntropySource
{
public:
EntropySource() : m_bSeeded(false) { }
bool isSeeded() const { return m_bSeeded; }
void seed(bool reseed = false);
void join();
private:
bool m_bSeeded;
thread m_thread;
};
void EntropySource::seed(bool reseed)
{
if (m_bSeeded && !reseed) return;
if (!m_thread.joinable())
{
LOGGER(trace) << "Starting entropy thread." << std::endl;
m_thread = thread([&]() {
secure_random_bytes(32);
m_bSeeded = true;
});
}
}
void EntropySource::join()
{
if (m_thread.joinable())
{
LOGGER(trace) << "Joining entropy thread (2)..." << std::endl;
m_thread.join();
LOGGER(trace) << "Entropy thread has exited (2)." << std::endl;
}
else
{
LOGGER(trace) << "Entropy thread has already exited." << std::endl;
}
}
static EntropySource entropySource;
void seedEntropySource(bool reseed, bool showDialog, QWidget* parent)
{
if (entropySource.isSeeded() && !reseed) return;
EntropyDialog dlg(parent);
if (showDialog)
{
dlg.setModal(true);
dlg.setResult(QDialog::Accepted);
dlg.show();
}
entropySource.seed(reseed);
while (!entropySource.isSeeded())
{
qApp->processEvents();
if (showDialog && dlg.result() == QDialog::Rejected) throw runtime_error("Entropy seeding operation canceled.");
this_thread::sleep_for(std::chrono::microseconds(200));
}
LOGGER(trace) << "Joining entropy thread (1)..." << std::endl;
entropySource.join();
LOGGER(trace) << "Entropy thread has exited (1)." << std::endl;
if (showDialog)
{
dlg.hide();
}
}
void joinEntropyThread()
{
entropySource.join();
}
secure_bytes_t getRandomBytes(int n, QWidget* parent)
{
//seedEntropySource(false, parent);
return secure_random_bytes(n);
}