Skip to content

Commit

Permalink
fix random mutex initialization order issue
Browse files Browse the repository at this point in the history
  • Loading branch information
miltonf committed Jan 25, 2019
1 parent 24c319d commit 0cc6c53
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
15 changes: 11 additions & 4 deletions src/crypto/crypto.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,6 @@ namespace crypto {
#include "random.h"
}

boost::mutex random_lock;

static inline unsigned char *operator &(ec_point &point) {
return &reinterpret_cast<unsigned char &>(point);
}
Expand All @@ -88,6 +86,13 @@ namespace crypto {
return &reinterpret_cast<const unsigned char &>(scalar);
}

void generate_random_bytes_thread_safe(size_t N, uint8_t *bytes)
{
static boost::mutex random_lock;
boost::lock_guard<boost::mutex> lock(random_lock);
generate_random_bytes_not_thread_safe(N, bytes);
}

/* generate a random 32-byte (256-bit) integer and copy it to res */
static inline void random_scalar_not_thread_safe(ec_scalar &res) {
unsigned char tmp[64];
Expand All @@ -96,8 +101,10 @@ namespace crypto {
memcpy(&res, tmp, 32);
}
static inline void random_scalar(ec_scalar &res) {
boost::lock_guard<boost::mutex> lock(random_lock);
random_scalar_not_thread_safe(res);
unsigned char tmp[64];
generate_random_bytes_thread_safe(64, tmp);
sc_reduce(tmp);
memcpy(&res, tmp, 32);
}

void hash_to_scalar(const void *data, size_t length, ec_scalar &res) {
Expand Down
10 changes: 4 additions & 6 deletions src/crypto/crypto.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ namespace crypto {
#include "random.h"
}

extern boost::mutex random_lock;

#pragma pack(push, 1)
POD_CLASS ec_point {
char data[32];
Expand Down Expand Up @@ -149,20 +147,20 @@ namespace crypto {
const public_key *const *, std::size_t, const signature *);
};

void generate_random_bytes_thread_safe(size_t N, uint8_t *bytes);

/* Generate N random bytes
*/
inline void rand(size_t N, uint8_t *bytes) {
boost::lock_guard<boost::mutex> lock(random_lock);
generate_random_bytes_not_thread_safe(N, bytes);
generate_random_bytes_thread_safe(N, bytes);
}

/* Generate a value filled with random bytes.
*/
template<typename T>
typename std::enable_if<std::is_pod<T>::value, T>::type rand() {
typename std::remove_cv<T>::type res;
boost::lock_guard<boost::mutex> lock(random_lock);
generate_random_bytes_not_thread_safe(sizeof(T), &res);
generate_random_bytes_thread_safe(sizeof(T), (uint8_t*)&res);
return res;
}

Expand Down

0 comments on commit 0cc6c53

Please sign in to comment.