Debian Codegraph @

src/crypto/rx-slow-hash.c

raw symbols SCIP
1 // Copyright (c) 2019-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 #include <assert.h>
30 #include <stddef.h>
31 #include <stdint.h>
32 #include <stdbool.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <limits.h>
38
39 #include "randomx.h"
40 #include "c_threads.h"
41 #include "hash-ops.h"
42 #include "misc_log_ex.h"
43
44 #define RX_LOGCAT "randomx"
45
46 // Report large page allocation failures as debug messages
47 #define alloc_err_msg(x) mdebug(RX_LOGCAT, x);
48
49 static CTHR_RWLOCK_TYPE main_dataset_lock = CTHR_RWLOCK_INIT;
50 static CTHR_RWLOCK_TYPE main_cache_lock = CTHR_RWLOCK_INIT;
51
52 static randomx_dataset *main_dataset = NULL;
53 static randomx_cache *main_cache = NULL;
54 static char main_seedhash[HASH_SIZE];
55 static int main_seedhash_set = 0;
56
57 static CTHR_RWLOCK_TYPE secondary_cache_lock = CTHR_RWLOCK_INIT;
58
59 static randomx_cache *secondary_cache = NULL;
60 static char secondary_seedhash[HASH_SIZE];
61 static int secondary_seedhash_set = 0;
62
63 #if defined(_MSC_VER)
64 #define THREADV __declspec(thread)
65 #else
66 #define THREADV __thread
67 #endif
68
69 static THREADV randomx_vm *main_vm_full = NULL;
70 static THREADV randomx_vm *main_vm_light = NULL;
71 static THREADV randomx_vm *secondary_vm_light = NULL;
72
73 static THREADV uint32_t miner_thread = 0;
74
75 static bool is_main(const char* seedhash) { return main_seedhash_set && (memcmp(seedhash, main_seedhash, HASH_SIZE) == 0); }
76 static bool is_secondary(const char* seedhash) { return secondary_seedhash_set && (memcmp(seedhash, secondary_seedhash, HASH_SIZE) == 0); }
77
78 static void local_abort(const char *msg)
79 {
80 merror(RX_LOGCAT, "%s", msg);
81 fprintf(stderr, "%s\n", msg);
82 #ifdef NDEBUG
83 _exit(1);
84 #else
85 abort();
86 #endif
87 }
88
89 static void hash2hex(const char* hash, char* hex) {
90 const char* d = "0123456789abcdef";
91 for (int i = 0; i < HASH_SIZE; ++i) {
92 const uint8_t b = hash[i];
93 hex[i * 2 + 0] = d[b >> 4];
94 hex[i * 2 + 1] = d[b & 15];
95 }
96 hex[HASH_SIZE * 2] = '\0';
97 }
98
99 static inline int disabled_flags(void) {
100 static int flags = -1;
101
102 if (flags != -1) {
103 return flags;
104 }
105
106 const char *env = getenv("MONERO_RANDOMX_UMASK");
107 if (!env) {
108 flags = 0;
109 }
110 else {
111 char* endptr;
112 long int value = strtol(env, &endptr, 0);
113 if (endptr != env && value >= 0 && value < INT_MAX) {
114 flags = value;
115 }
116 else {
117 flags = 0;
118 }
119 }
120
121 return flags;
122 }
123
124 static inline int enabled_flags(void) {
125 static int flags = -1;
126
127 if (flags != -1) {
128 return flags;
129 }
130
131 flags = randomx_get_flags();
132
133 return flags;
134 }
135
136 #define SEEDHASH_EPOCH_BLOCKS 2048 /* Must be same as BLOCKS_SYNCHRONIZING_MAX_COUNT in cryptonote_config.h */
137 #define SEEDHASH_EPOCH_LAG 64
138
139 static inline int is_power_of_2(uint64_t n) { return n && (n & (n-1)) == 0; }
140
141 static int get_seedhash_epoch_lag(void)
142 {
143 static unsigned int lag = (unsigned int)-1;
144 if (lag != (unsigned int)-1)
145 return lag;
146 const char *e = getenv("SEEDHASH_EPOCH_LAG");
147 if (e)
148 {
149 lag = atoi(e);
150 if (lag > SEEDHASH_EPOCH_LAG || !is_power_of_2(lag))
151 lag = SEEDHASH_EPOCH_LAG;
152 }
153 else
154 {
155 lag = SEEDHASH_EPOCH_LAG;
156 }
157 return lag;
158 }
159
160 static unsigned int get_seedhash_epoch_blocks(void)
161 {
162 static unsigned int blocks = (unsigned int)-1;
163 if (blocks != (unsigned int)-1)
164 return blocks;
165 const char *e = getenv("SEEDHASH_EPOCH_BLOCKS");
166 if (e)
167 {
168 blocks = atoi(e);
169 if (blocks < 2 || blocks > SEEDHASH_EPOCH_BLOCKS || !is_power_of_2(blocks))
170 blocks = SEEDHASH_EPOCH_BLOCKS;
171 }
172 else
173 {
174 blocks = SEEDHASH_EPOCH_BLOCKS;
175 }
176 return blocks;
177 }
178
179 uint64_t rx_seedheight(const uint64_t height) {
180 const uint64_t seedhash_epoch_lag = get_seedhash_epoch_lag();
181 const uint64_t seedhash_epoch_blocks = get_seedhash_epoch_blocks();
182 uint64_t s_height = (height <= seedhash_epoch_blocks+seedhash_epoch_lag) ? 0 :
183 (height - seedhash_epoch_lag - 1) & ~(seedhash_epoch_blocks-1);
184 return s_height;
185 }
186
187 void rx_seedheights(const uint64_t height, uint64_t *seedheight, uint64_t *nextheight) {
188 *seedheight = rx_seedheight(height);
189 *nextheight = rx_seedheight(height + get_seedhash_epoch_lag());
190 }
191
192 static void rx_alloc_dataset(randomx_flags flags, randomx_dataset** dataset, int ignore_env)
193 {
194 if (*dataset) {
195 return;
196 }
197
198 if (disabled_flags() & RANDOMX_FLAG_FULL_MEM) {
199 static int shown = 0;
200 if (!shown) {
201 shown = 1;
202 minfo(RX_LOGCAT, "RandomX dataset is disabled by MONERO_RANDOMX_UMASK environment variable.");
203 }
204 return;
205 }
206
207 if (!ignore_env && !getenv("MONERO_RANDOMX_FULL_MEM")) {
208 static int shown = 0;
209 if (!shown) {
210 shown = 1;
211 minfo(RX_LOGCAT, "RandomX dataset is not enabled by default. Use MONERO_RANDOMX_FULL_MEM environment variable to enable it.");
212 }
213 return;
214 }
215
216 *dataset = randomx_alloc_dataset((flags | RANDOMX_FLAG_LARGE_PAGES) & ~disabled_flags());
217 if (!*dataset) {
218 alloc_err_msg("Couldn't allocate RandomX dataset using large pages");
219 *dataset = randomx_alloc_dataset(flags & ~disabled_flags());
220 if (!*dataset) {
221 merror(RX_LOGCAT, "Couldn't allocate RandomX dataset");
222 }
223 }
224 }
225
226 static void rx_alloc_cache(randomx_flags flags, randomx_cache** cache)
227 {
228 if (*cache) {
229 return;
230 }
231
232 *cache = randomx_alloc_cache((flags | RANDOMX_FLAG_LARGE_PAGES) & ~disabled_flags());
233 if (!*cache) {
234 alloc_err_msg("Couldn't allocate RandomX cache using large pages");
235 *cache = randomx_alloc_cache(flags & ~disabled_flags());
236 if (!*cache) local_abort("Couldn't allocate RandomX cache");
237 }
238 }
239
240 static void rx_init_full_vm(randomx_flags flags, randomx_vm** vm)
241 {
242 if (*vm || !main_dataset || (disabled_flags() & RANDOMX_FLAG_FULL_MEM)) {
243 return;
244 }
245
246 if ((flags & RANDOMX_FLAG_JIT) && !miner_thread) {
247 flags |= RANDOMX_FLAG_SECURE;
248 }
249
250 *vm = randomx_create_vm((flags | RANDOMX_FLAG_LARGE_PAGES | RANDOMX_FLAG_FULL_MEM) & ~disabled_flags(), NULL, main_dataset);
251 if (!*vm) {
252 static int shown = 0;
253 if (!shown) {
254 shown = 1;
255 alloc_err_msg("Couldn't allocate RandomX full VM using large pages (will print only once)");
256 }
257 *vm = randomx_create_vm((flags | RANDOMX_FLAG_FULL_MEM) & ~disabled_flags(), NULL, main_dataset);
258 if (!*vm) {
259 merror(RX_LOGCAT, "Couldn't allocate RandomX full VM");
260 }
261 }
262 }
263
264 static void rx_init_light_vm(randomx_flags flags, randomx_vm** vm, randomx_cache* cache)
265 {
266 if (*vm) {
267 randomx_vm_set_cache(*vm, cache);
268 return;
269 }
270
271 if ((flags & RANDOMX_FLAG_JIT) && !miner_thread) {
272 flags |= RANDOMX_FLAG_SECURE;
273 }
274
275 flags &= ~RANDOMX_FLAG_FULL_MEM;
276
277 *vm = randomx_create_vm((flags | RANDOMX_FLAG_LARGE_PAGES) & ~disabled_flags(), cache, NULL);
278 if (!*vm) {
279 static int shown = 0;
280 if (!shown) {
281 shown = 1;
282 alloc_err_msg("Couldn't allocate RandomX light VM using large pages (will print only once)");
283 }
284 *vm = randomx_create_vm(flags & ~disabled_flags(), cache, NULL);
285 if (!*vm) local_abort("Couldn't allocate RandomX light VM");
286 }
287 }
288
289 typedef struct seedinfo {
290 randomx_cache *si_cache;
291 unsigned long si_start;
292 unsigned long si_count;
293 } seedinfo;
294
295 static CTHR_THREAD_RTYPE rx_seedthread(void *arg) {
296 seedinfo *si = arg;
297 randomx_init_dataset(main_dataset, si->si_cache, si->si_start, si->si_count);
298 CTHR_THREAD_RETURN;
299 }
300
301 static void rx_init_dataset(size_t max_threads) {
302 if (!main_dataset) {
303 return;
304 }
305
306 // leave 2 CPU cores for other tasks
307 const size_t num_threads = (max_threads < 4) ? 1 : (max_threads - 2);
308 seedinfo* si = malloc(num_threads * sizeof(seedinfo));
309 if (!si) local_abort("Couldn't allocate RandomX mining threadinfo");
310
311 const uint32_t delta = randomx_dataset_item_count() / num_threads;
312 uint32_t start = 0;
313
314 const size_t n1 = num_threads - 1;
315 for (size_t i = 0; i < n1; ++i) {
316 si[i].si_cache = main_cache;
317 si[i].si_start = start;
318 si[i].si_count = delta;
319 start += delta;
320 }
321
322 si[n1].si_cache = main_cache;
323 si[n1].si_start = start;
324 si[n1].si_count = randomx_dataset_item_count() - start;
325
326 CTHR_THREAD_TYPE *st = malloc(num_threads * sizeof(CTHR_THREAD_TYPE));
327 if (!st) local_abort("Couldn't allocate RandomX mining threadlist");
328
329 CTHR_RWLOCK_LOCK_READ(main_cache_lock);
330 for (size_t i = 0; i < n1; ++i) {
331 if (!CTHR_THREAD_CREATE(st[i], rx_seedthread, &si[i])) {
332 local_abort("Couldn't start RandomX seed thread");
333 }
334 }
335 randomx_init_dataset(main_dataset, si[n1].si_cache, si[n1].si_start, si[n1].si_count);
336 for (size_t i = 0; i < n1; ++i) CTHR_THREAD_JOIN(st[i]);
337 CTHR_RWLOCK_UNLOCK_READ(main_cache_lock);
338
339 free(st);
340 free(si);
341
342 minfo(RX_LOGCAT, "RandomX dataset initialized");
343 }
344
345 typedef struct thread_info {
346 char seedhash[HASH_SIZE];
347 size_t max_threads;
348 } thread_info;
349
350 static CTHR_THREAD_RTYPE rx_set_main_seedhash_thread(void *arg) {
351 thread_info* info = arg;
352
353 CTHR_RWLOCK_LOCK_WRITE(main_dataset_lock);
354 CTHR_RWLOCK_LOCK_WRITE(main_cache_lock);
355
356 // Double check that seedhash wasn't already updated
357 if (is_main(info->seedhash)) {
358 CTHR_RWLOCK_UNLOCK_WRITE(main_cache_lock);
359 CTHR_RWLOCK_UNLOCK_WRITE(main_dataset_lock);
360 free(info);
361 CTHR_THREAD_RETURN;
362 }
363 memcpy(main_seedhash, info->seedhash, HASH_SIZE);
364 main_seedhash_set = 1;
365
366 char buf[HASH_SIZE * 2 + 1];
367 hash2hex(main_seedhash, buf);
368 minfo(RX_LOGCAT, "RandomX new main seed hash is %s", buf);
369
370 const randomx_flags flags = enabled_flags() & ~disabled_flags();
371 rx_alloc_dataset(flags, &main_dataset, 0);
372 rx_alloc_cache(flags, &main_cache);
373
374 randomx_init_cache(main_cache, info->seedhash, HASH_SIZE);
375 minfo(RX_LOGCAT, "RandomX main cache initialized");
376
377 CTHR_RWLOCK_UNLOCK_WRITE(main_cache_lock);
378
379 // From this point, rx_slow_hash can calculate hashes in light mode, but dataset is not initialized yet
380 rx_init_dataset(info->max_threads);
381
382 CTHR_RWLOCK_UNLOCK_WRITE(main_dataset_lock);
383
384 free(info);
385 CTHR_THREAD_RETURN;
386 }
387
388 void rx_set_main_seedhash(const char *seedhash, size_t max_dataset_init_threads) {
389 // Early out if seedhash didn't change
390 if (is_main(seedhash)) {
391 return;
392 }
393
394 // Update main cache and dataset in the background
395 thread_info* info = malloc(sizeof(thread_info));
396 if (!info) local_abort("Couldn't allocate RandomX mining threadinfo");
397
398 memcpy(info->seedhash, seedhash, HASH_SIZE);
399 info->max_threads = max_dataset_init_threads;
400
401 CTHR_THREAD_TYPE t;
402 if (!CTHR_THREAD_CREATE(t, rx_set_main_seedhash_thread, info)) {
403 local_abort("Couldn't start RandomX seed thread");
404 }
405 CTHR_THREAD_CLOSE(t);
406 }
407
408 void rx_slow_hash(const char *seedhash, const void *data, size_t length, char *result_hash) {
409 const randomx_flags flags = enabled_flags() & ~disabled_flags();
410 int success = 0;
411
412 // Fast path (seedhash == main_seedhash)
413 // Multiple threads can run in parallel in fast or light mode, 1-2 ms or 10-15 ms per hash per thread
414 if (is_main(seedhash)) {
415 // If CTHR_RWLOCK_TRYLOCK_READ fails it means dataset is being initialized now, so use the light mode
416 if (main_dataset && CTHR_RWLOCK_TRYLOCK_READ(main_dataset_lock)) {
417 // Double check that main_seedhash didn't change
418 if (is_main(seedhash)) {
419 rx_init_full_vm(flags, &main_vm_full);
420 if (main_vm_full) {
421 randomx_calculate_hash(main_vm_full, data, length, result_hash);
422 success = 1;
423 }
424 }
425 CTHR_RWLOCK_UNLOCK_READ(main_dataset_lock);
426 } else {
427 CTHR_RWLOCK_LOCK_READ(main_cache_lock);
428 // Double check that main_seedhash didn't change
429 if (is_main(seedhash)) {
430 rx_init_light_vm(flags, &main_vm_light, main_cache);
431 randomx_calculate_hash(main_vm_light, data, length, result_hash);
432 success = 1;
433 }
434 CTHR_RWLOCK_UNLOCK_READ(main_cache_lock);
435 }
436 }
437
438 if (success) {
439 return;
440 }
441
442 char buf[HASH_SIZE * 2 + 1];
443
444 // Slow path (seedhash != main_seedhash, but seedhash == secondary_seedhash)
445 // Multiple threads can run in parallel in light mode, 10-15 ms per hash per thread
446 if (!secondary_cache) {
447 CTHR_RWLOCK_LOCK_WRITE(secondary_cache_lock);
448 if (!secondary_cache) {
449 hash2hex(seedhash, buf);
450 minfo(RX_LOGCAT, "RandomX new secondary seed hash is %s", buf);
451
452 rx_alloc_cache(flags, &secondary_cache);
453 randomx_init_cache(secondary_cache, seedhash, HASH_SIZE);
454 minfo(RX_LOGCAT, "RandomX secondary cache updated");
455 memcpy(secondary_seedhash, seedhash, HASH_SIZE);
456 secondary_seedhash_set = 1;
457 }
458 CTHR_RWLOCK_UNLOCK_WRITE(secondary_cache_lock);
459 }
460
461 CTHR_RWLOCK_LOCK_READ(secondary_cache_lock);
462 if (is_secondary(seedhash)) {
463 rx_init_light_vm(flags, &secondary_vm_light, secondary_cache);
464 randomx_calculate_hash(secondary_vm_light, data, length, result_hash);
465 success = 1;
466 }
467 CTHR_RWLOCK_UNLOCK_READ(secondary_cache_lock);
468
469 if (success) {
470 return;
471 }
472
473 // Slowest path (seedhash != main_seedhash, seedhash != secondary_seedhash)
474 // Only one thread runs at a time and updates secondary_seedhash if needed, up to 200-500 ms per hash
475 CTHR_RWLOCK_LOCK_WRITE(secondary_cache_lock);
476 if (!is_secondary(seedhash)) {
477 hash2hex(seedhash, buf);
478 minfo(RX_LOGCAT, "RandomX new secondary seed hash is %s", buf);
479
480 randomx_init_cache(secondary_cache, seedhash, HASH_SIZE);
481 minfo(RX_LOGCAT, "RandomX secondary cache updated");
482 memcpy(secondary_seedhash, seedhash, HASH_SIZE);
483 secondary_seedhash_set = 1;
484 }
485 rx_init_light_vm(flags, &secondary_vm_light, secondary_cache);
486 randomx_calculate_hash(secondary_vm_light, data, length, result_hash);
487 CTHR_RWLOCK_UNLOCK_WRITE(secondary_cache_lock);
488 }
489
490 void rx_set_miner_thread(uint32_t value, size_t max_dataset_init_threads) {
491 miner_thread = value;
492
493 // If dataset is not allocated yet, try to allocate and initialize it
494 CTHR_RWLOCK_LOCK_WRITE(main_dataset_lock);
495 if (main_dataset) {
496 CTHR_RWLOCK_UNLOCK_WRITE(main_dataset_lock);
497 return;
498 }
499
500 const randomx_flags flags = enabled_flags() & ~disabled_flags();
501 rx_alloc_dataset(flags, &main_dataset, 1);
502 rx_init_dataset(max_dataset_init_threads);
503
504 CTHR_RWLOCK_UNLOCK_WRITE(main_dataset_lock);
505 }
506
507 uint32_t rx_get_miner_thread() {
508 return miner_thread;
509 }
510
511 void rx_slow_hash_allocate_state() {}
512
513 static void rx_destroy_vm(randomx_vm** vm) {
514 if (*vm) {
515 randomx_destroy_vm(*vm);
516 *vm = NULL;
517 }
518 }
519
520 void rx_slow_hash_free_state() {
521 rx_destroy_vm(&main_vm_full);
522 rx_destroy_vm(&main_vm_light);
523 rx_destroy_vm(&secondary_vm_light);
524 }