OpenCBDC Transaction Processor
Loading...
Searching...
No Matches
random_source.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 MIT Digital Currency Initiative,
2// Federal Reserve Bank of Boston
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include "random_source.hpp"
7
8#include <cassert>
9#include <cstring>
10#include <fstream>
11#include <random>
12
13namespace cbdc {
14 random_source::random_source(const std::string& source_file) {
15 std::ifstream m_source(source_file, std::ios::in | std::ios::binary);
16 assert(m_source.good());
17
18 std::array<char, std::tuple_size<hash_t>::value> dest{};
19 m_source.read(dest.data(), dest.size());
20 assert(m_source.gcount() == static_cast<std::streamsize>(dest.size()));
21 std::array<unsigned char, sizeof(dest)> dest_unsigned{};
22 std::memcpy(dest_unsigned.data(), dest.data(), dest.size());
23 m_sha.Write(dest_unsigned.data(), dest_unsigned.size());
24 }
25
27 std::unique_lock<std::mutex> l(m_mut);
28 result_type ret{};
29 std::array<unsigned char, sizeof(ret)> ret_arr{};
30 for(auto& v : ret_arr) {
31 if(m_buf.empty()) {
32 auto h = hash_at_index(m_counter++);
33 for(auto b : h) {
34 m_buf.push(b);
35 }
36 }
37 v = m_buf.front();
38 m_buf.pop();
39 }
40 std::memcpy(&ret, ret_arr.data(), ret_arr.size());
41 return ret;
42 }
43
45 hash_t ret{};
46 std::uniform_int_distribution<unsigned char> gen;
47 for(auto&& b : ret) {
48 b = gen(*this);
49 }
50 return ret;
51 }
52
53 auto random_source::hash_at_index(uint64_t idx) -> hash_t {
54 hash_t ret;
55 std::array<unsigned char, sizeof(idx)> idx_arr{};
56 std::memcpy(idx_arr.data(), &idx, sizeof(idx));
57 m_sha.Write(idx_arr.data(), sizeof(idx));
58 m_sha.Finalize(ret.data());
59 return ret;
60 }
61}
random_source(const std::string &source_file)
Constructor.
auto operator()() -> result_type
Returns a new random integer.
unsigned int result_type
auto random_hash() -> hash_t
Returns a random 32-byte hash value.
std::array< unsigned char, cbdc::hash_size > hash_t
SHA256 hash container.
Pseudorandom number generator (PRNG) for generating random data from a given entropy source.