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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use std::str;
use std::sync::Arc;
use byteorder::*;
use chrono::{DateTime, Local, Utc};
use futures::FutureExt;
use mut_static::MutStatic;
use parking_lot::RwLock;
use rand::prelude::*;
use rand::seq::SliceRandom;
use rand::thread_rng;
use rayon::prelude::*;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::util::*;
pub static MAX_BLOCK_SIZE: u32 = 1024 * 1024;
pub static ENABLE_DEBUG: bool = true;
pub static MAX_RETRY_COUNT: u8 = 10;
pub static ENTROPY_BANK_EXPIRE_MS: i64 = 60000;
pub static ENTROPY_BANK_SIZE: u32 = MAX_BLOCK_SIZE - 1;
#[macro_use]
lazy_static! {
static ref DEFAULT_ENTROPY_BANK: MutStatic<Arc<RwLock<EntropyBank>>> = MutStatic::new();
pub(crate) static ref REQWEST_CLIENT: MutStatic<Client> = MutStatic::new();
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EntropyBank {
bank: Option<Vec<u8>>,
timestamp: Option<DateTime<Utc>>,
name: Option<String>,
}
impl EntropyBank {
fn new(vector: Vec<u8>) -> Arc<RwLock<Self>> {
let now = DateTime::<Utc>::from_utc(Local::now().naive_utc(), Utc);
Arc::new(RwLock::new(Self {
bank: Some(vector),
timestamp: Some(now),
name: None,
}))
}
pub async fn new_async<'a>(size: u32) -> Result<Arc<RwLock<Self>>, QuantumError<'a>> {
get_data_async(size).await.and_then(move |data| {
Ok(EntropyBank::new(data))
})
}
pub fn default_entropy_bank_loaded_to_memory_and_is_valid() -> bool {
if DEFAULT_ENTROPY_BANK.is_set().unwrap() {
return !DEFAULT_ENTROPY_BANK.read().unwrap().read_recursive().did_expire();
}
false
}
pub fn save<'a>(&mut self, name: Option<String>) -> Result<(), QuantumError<'a>> {
let name = name.unwrap_or(ENTROPY_BANK_DEFAULT_FILE.to_string());
self.name = Some(name.to_string());
let obj = self.clone();
if let Err(_) = serialize_entity_to_disk(format!("{}cfg/{}.entropy", get_home_dir(), name), obj) {
return QuantumError::throw("[QuantumRandom] Unable to serialize entity to disk!");
}
Ok(())
}
pub async fn load<'a>(name_opt: Option<String>) -> Result<Arc<RwLock<Self>>, QuantumError<'a>> {
let name_is_none = name_opt.is_none();
let name = name_opt.unwrap_or(ENTROPY_BANK_DEFAULT_FILE.to_string());
let fname = sanitize_path(format!("{}cfg/{}.entropy", get_home_dir(), name));
if !entropy_file_exists() && name_is_none {
return QuantumError::throw("[QuantumRandom] Unable to get entropy bank (none exist!)");
}
println!("[QRandom::EntropyBank] Going to deserialize {}", &fname);
let res = deserialize_entity_from_disk::<EntropyBank>(fname);
if res.is_err() {
return QuantumError::throw("Unable to get entropy bank");
}
let l2m = Arc::new(RwLock::new(res.unwrap()));
let ret = Arc::clone(&l2m);
if name == ENTROPY_BANK_DEFAULT_FILE {
if let Err(_) = DEFAULT_ENTROPY_BANK.set(l2m) {
return QuantumError::throw("[QuantumRandom] Unable to set default entropy bank!");
}
}
Ok(ret)
}
pub fn replicate(&self) -> Arc<RwLock<Self>> {
Arc::new(RwLock::new(self.clone()))
}
pub fn did_expire(&self) -> bool {
let now = DateTime::<Utc>::from_utc(Local::now().naive_utc(), Utc).timestamp_millis();
now - self.timestamp.unwrap().timestamp_millis() >= ENTROPY_BANK_EXPIRE_MS
}
pub fn shuffle_and_get<'a>(&mut self, len: usize, save: bool) -> Result<Vec<u8>, QuantumError<'a>> {
println!("bank size: {}", self.bank.as_mut().unwrap().len());
self.bank.as_mut().unwrap().shuffle(&mut thread_rng());
if save {
if let Err(err) = self.save(self.name.clone()) {
return Err(err);
}
}
println!("bank size: {}", self.bank.as_mut().unwrap().len());
Ok(self.bank.as_ref().unwrap()[0..len].to_vec())
}
}
async fn get_raw_data_async<'a>(length: usize, mut _retry_count: usize) -> Result<Vec<u8>, QuantumError<'a>> {
if length as u32 > MAX_BLOCK_SIZE {
return QuantumError::throw(format!("[QuantumRandom] Error! You cannot call this function with a parameter greater than {}", MAX_BLOCK_SIZE));
}
if !REQWEST_CLIENT.is_set().unwrap() {
if let Err(_) = REQWEST_CLIENT.set(Client::new()) {
return QuantumError::throw("[QuantumRandom] Unable to interface with Reqwest!");
}
}
providers::anu_edu_download(length).await.and_then(|mut resp| {
let data = resp.text().unwrap();
if ENABLE_DEBUG {
println!("[QuantumRandom] Recv: {}", data);
}
Ok(data)
}).or_else(|err| {
QuantumError::throw(format!("[QuantumRandom] Unable to download data! Reason: {}", err.to_string()))
}).and_then(move |input| extract_values_anu(length, input))
.and_then(|vector| Ok(vector))
}
mod providers {
use reqwest::Error;
use reqwest::Response;
use super::REQWEST_CLIENT;
pub(crate) async fn anu_edu_download(len_total: usize) -> Result<Response, Error> {
let (length, size) = {
if len_total <= 1024 {
(1, len_total)
} else {
let val = (len_total as f64) / (1024 as f64);
let len = math::round::ceil(val, 0) as usize;
(len, 1024)
}
};
let url = format!("https://qrng.anu.edu.au/API/jsonI.php?length={}&type=hex16&size={}", length, size);
let url = url.as_str();
REQWEST_CLIENT.read().unwrap().get(url).send()
}
}
pub fn extract_values_anu<'a>(len_expected: usize, data: String) -> Result<Vec<u8>, QuantumError<'a>> {
if !data.contains("\"success\":true") {
return QuantumError::throw("[QuantumRandom] Data downloaded, but invalid data detected!");
}
let parts = substring(data, "[", "]").replace("\"", "").replace(",", "").into_bytes().par_chunks(2).take(len_expected).map(|arr| unsafe {
u8::from_str_radix(str::from_utf8_unchecked(arr), 16).unwrap() ^ random::<u8>()
}).collect::<Vec<u8>>();
if ENABLE_DEBUG {
println!("Total # of parts: {}", parts.len());
}
if parts.len() != len_expected {
return QuantumError::throw("[QuantumRandom] Invalid input length!");
}
Ok(parts)
}
async fn get_data_async<'a>(length: u32) -> Result<Vec<u8>, QuantumError<'a>> {
let mut futures0 = vec![];
let mut iter_count = 0;
if length < MAX_BLOCK_SIZE {
futures0.push(get_raw_data_async(length as usize, 0));
iter_count += 1;
} else {
let mut amt_left = length;
while amt_left > MAX_BLOCK_SIZE {
futures0.push(get_raw_data_async(MAX_BLOCK_SIZE as usize, 0));
amt_left -= MAX_BLOCK_SIZE;
iter_count += 1;
}
if amt_left >= 1 {
futures0.push(get_raw_data_async(amt_left as usize, 0));
iter_count += 1;
}
}
if iter_count != futures0.len() {
return QuantumError::throw("[QuantumRandom] unable to setup asynchronous split streams");
}
futures::future::join_all(futures0).map(|arr| {
let mut vec = Vec::<u8>::with_capacity(length as usize);
for res in arr {
match res {
Ok(mut res) => {
vec.append(&mut res);
}
Err(err) => {
return Err(err);
}
}
}
Ok(vec)
}).await
}
#[allow(dead_code)]
async fn next_u8s_eb<'a>(len: usize) -> Result<Vec<u8>, QuantumError<'a>> {
EntropyBank::load(None).await.and_then(move |res| {
if let Ok(res) = res.write().shuffle_and_get(len, false) {
Ok(res)
} else {
QuantumError::throw("[QuantumRandom] Unable to load entropy bank")
}
})
}
async fn get_data<'a>(length: usize) -> Result<Vec<u8>, QuantumError<'a>> {
get_data_async(length as u32).await
}
pub async fn next_u8s<'a>(len: usize) -> Result<Vec<u8>, QuantumError<'a>> {
get_data(len).await
}
pub async fn next_u16s<'a>(len: usize) -> Result<Vec<u16>, QuantumError<'a>> {
get_data(len * 2).await.and_then(move |res| {
Ok(res.par_chunks(2).take(len).map(|chunk| {
BigEndian::read_u16(chunk)
}).collect::<Vec<u16>>())
}).map_err(|err| err)
}
pub async fn next_u32s<'a>(len: usize) -> Result<Vec<u32>, QuantumError<'a>> {
get_data(len * 4).await.and_then(move |res| {
Ok(res.par_chunks(4).take(len).map(|chunk| {
BigEndian::read_u32(chunk)
}).collect::<Vec<u32>>())
}).map_err(|err| err)
}
pub async fn next_u64s<'a>(len: usize) -> Result<Vec<u64>, QuantumError<'a>> {
get_data(len * 8).await.and_then(move |res| {
Ok(res.par_chunks(8).take(len).map(|chunk| {
BigEndian::read_u64(chunk)
}).collect::<Vec<u64>>())
}).map_err(|err| err)
}
pub async fn next_u128s<'a>(len: usize) -> Result<Vec<u128>, QuantumError<'a>> {
get_data(len * 16).await.and_then(move |res| {
Ok(res.par_chunks(16).take(len).map(|chunk| {
BigEndian::read_u128(chunk)
}).collect::<Vec<u128>>())
}).map_err(|err| err)
}
pub async fn next_i8s<'a>(len: usize) -> Result<Vec<i8>, QuantumError<'a>> {
get_data(len).await.and_then(|res| {
Ok(res.iter().map(|byte| {
u8_to_i8(byte)
}).collect::<Vec<i8>>())
})
}
pub async fn next_i16s<'a>(len: usize) -> Result<Vec<i16>, QuantumError<'a>> {
get_data(len * 2).await.and_then(move |res| {
Ok(res.par_chunks(2).take(len).map(|chunk| {
u16_to_i16(&BigEndian::read_u16(chunk))
}).collect::<Vec<i16>>())
}).map_err(|err| err)
}
pub async fn next_i32s<'a>(len: usize) -> Result<Vec<i32>, QuantumError<'a>> {
get_data(len * 4).await.and_then(move |res| {
Ok(res.par_chunks(4).take(len).map(|chunk| {
u32_to_i32(&BigEndian::read_u32(chunk))
}).collect::<Vec<i32>>())
}).map_err(|err| err)
}
pub async fn next_i64s<'a>(len: usize) -> Result<Vec<i64>, QuantumError<'a>> {
get_data(len * 8).await.and_then(move |res| {
Ok(res.par_chunks(8).take(len).map(|chunk| {
u64_to_i64(&BigEndian::read_u64(chunk))
}).collect::<Vec<i64>>())
}).map_err(|err| err)
}
pub async fn next_i128s<'a>(len: usize) -> Result<Vec<i128>, QuantumError<'a>> {
get_data(len * 16).await.and_then(move |res| {
Ok(res.par_chunks(16).take(len).map(|chunk| {
u128_to_i128(&BigEndian::read_u128(chunk))
}).collect::<Vec<i128>>())
}).map_err(|err| err)
}
fn substring<T: AsRef<str>>(arr: T, start: &str, end: &str) -> String {
let arr = arr.as_ref();
let start_idx = arr.find(start).unwrap();
let end_idx = arr.find(end).unwrap();
arr.chars().skip(start_idx + 1).take(end_idx - start_idx - 1).collect()
}
#[inline]
fn u8_to_i8(input: &u8) -> i8 {
let limit = i8::max_value() as u8;
if *input >= limit {
(*input - limit) as i8
} else {
*input as i8 - limit as i8
}
}
#[inline]
fn u16_to_i16(input: &u16) -> i16 {
let limit = i16::max_value() as u16;
if *input >= limit {
(*input - limit) as i16
} else {
*input as i16 - limit as i16
}
}
#[inline]
fn u32_to_i32(input: &u32) -> i32 {
let limit = i32::max_value() as u32;
if *input >= limit {
(*input - limit) as i32
} else {
*input as i32 - limit as i32
}
}
#[inline]
fn u64_to_i64(input: &u64) -> i64 {
let limit = i64::max_value() as u64;
if *input >= limit {
(*input - limit) as i64
} else {
*input as i64 - limit as i64
}
}
#[inline]
fn u128_to_i128(input: &u128) -> i128 {
let limit = i128::max_value() as u128;
if *input >= limit {
(*input - limit) as i128
} else {
*input as i128 - limit as i128
}
}