libbtc
bitcoinclibrary
random.c
Go to the documentation of this file.
1 /*
2 
3  The MIT License (MIT)
4 
5  Copyright (c) 2015 Douglas J. Bakkum
6 
7  Permission is hereby granted, free of charge, to any person obtaining
8  a copy of this software and associated documentation files (the "Software"),
9  to deal in the Software without restriction, including without limitation
10  the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  and/or sell copies of the Software, and to permit persons to whom the
12  Software is furnished to do so, subject to the following conditions:
13 
14  The above copyright notice and this permission notice shall be included
15  in all copies or substantial portions of the Software.
16 
17  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
21  OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23  OTHER DEALINGS IN THE SOFTWARE.
24 
25 */
26 
27 #include "random.h"
28 
29 #include "libbtc-config.h"
30 
31 #include <assert.h>
32 #include <string.h>
33 #include <stdio.h>
34 #include <time.h>
35 
36 
37 #ifdef TESTING
38 void random_init(void)
39 {
40  srand(time(NULL));
41 }
42 
43 
44 btc_bool random_bytes(uint8_t* buf, uint32_t len, uint8_t update_seed)
45 {
46  (void)update_seed;
47  for (uint32_t i = 0; i < len; i++) {
48  buf[i] = rand();
49  }
50 
51  return true;
52 }
53 #elif FILE_RANDOM
54 void random_init(void) {}
55 
56 
57 btc_bool random_bytes(uint8_t* buf, uint32_t len, const uint8_t update_seed)
58 {
59  (void)update_seed; //unused
60  FILE* frand = fopen(RANDOM_DEVICE, "r");
61  if (!frand) {
62  return false;
63  }
64 
65  size_t len_read = fread(buf, 1, len, frand);
66  assert(len_read == len);
67  fclose(frand);
68  return true;
69 }
70 #else
71 //provide extern interface
72 #endif
uint8_t btc_bool
Definition: btc.h:34
btc_bool random_bytes(uint8_t *buf, uint32_t len, const uint8_t update_seed)
Definition: random.c:57
size_t len
Definition: buffer.h:16
#define RANDOM_DEVICE
Definition: libbtc-config.h:75
void random_init(void)
Definition: random.c:54