Debian Codegraph @

src/crypto/slow-hash.c

raw symbols SCIP
1 // Copyright (c) 2014-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 // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
30
31 #include <assert.h>
32 #include <stddef.h>
33 #include <stdint.h>
34 #include <string.h>
35 #include <stdio.h>
36 #include <unistd.h>
37
38 #include "int-util.h"
39 #include "hash-ops.h"
40 #include "oaes_lib.h"
41 #include "variant2_int_sqrt.h"
42 #include "variant4_random_math.h"
43 #include "CryptonightR_JIT.h"
44
45 #include <errno.h>
46
47 #define MEMORY (1 << 21) // 2MB scratchpad
48 #define ITER (1 << 20)
49 #define AES_BLOCK_SIZE 16
50 #define AES_KEY_SIZE 32
51 #define INIT_SIZE_BLK 8
52 #define INIT_SIZE_BYTE (INIT_SIZE_BLK * AES_BLOCK_SIZE)
53
54 #if defined(_MSC_VER)
55 #define THREADV __declspec(thread)
56 #else
57 #define THREADV __thread
58 #endif
59
60 extern void aesb_single_round(const uint8_t *in, uint8_t *out, const uint8_t *expandedKey);
61 extern void aesb_pseudo_round(const uint8_t *in, uint8_t *out, const uint8_t *expandedKey);
62
63 static void local_abort(const char *msg)
64 {
65 fprintf(stderr, "%s\n", msg);
66 #ifdef NDEBUG
67 _exit(1);
68 #else
69 abort();
70 #endif
71 }
72
73 volatile int use_v4_jit_flag = -1;
74
75 static inline int use_v4_jit(void)
76 {
77 #if defined(__x86_64__)
78
79 if (use_v4_jit_flag != -1)
80 return use_v4_jit_flag;
81
82 const char *env = getenv("MONERO_USE_CNV4_JIT");
83 if (!env) {
84 use_v4_jit_flag = 1;
85 }
86 else if (!strcmp(env, "0") || !strcmp(env, "no")) {
87 use_v4_jit_flag = 0;
88 }
89 else {
90 use_v4_jit_flag = 1;
91 }
92 return use_v4_jit_flag;
93 #else
94 return 0;
95 #endif
96 }
97
98 #if defined(__x86_64__) || defined(__aarch64__)
99 static inline int force_software_aes(void)
100 {
101 static int use = -1;
102
103 if (use != -1)
104 return use;
105
106 const char *env = getenv("MONERO_USE_SOFTWARE_AES");
107 if (!env) {
108 use = 0;
109 }
110 else if (!strcmp(env, "0") || !strcmp(env, "no")) {
111 use = 0;
112 }
113 else {
114 use = 1;
115 }
116 return use;
117 }
118 #endif
119
120 #define VARIANT1_1(p) \
121 do if (variant == 1) \
122 { \
123 const uint8_t tmp = ((const uint8_t*)(p))[11]; \
124 static const uint32_t table = 0x75310; \
125 const uint8_t index = (((tmp >> 3) & 6) | (tmp & 1)) << 1; \
126 ((uint8_t*)(p))[11] = tmp ^ ((table >> index) & 0x30); \
127 } while(0)
128
129 #define VARIANT1_2(p) \
130 do if (variant == 1) \
131 { \
132 xor64(p, tweak1_2); \
133 } while(0)
134
135 #define VARIANT1_CHECK() \
136 do if (length < 43) \
137 { \
138 fprintf(stderr, "Cryptonight variant 1 needs at least 43 bytes of data"); \
139 _exit(1); \
140 } while(0)
141
142 #define NONCE_POINTER (((const uint8_t*)data)+35)
143
144 #define VARIANT1_PORTABLE_INIT() \
145 uint8_t tweak1_2[8]; \
146 do if (variant == 1) \
147 { \
148 VARIANT1_CHECK(); \
149 memcpy(&tweak1_2, &state.hs.b[192], sizeof(tweak1_2)); \
150 xor64(tweak1_2, NONCE_POINTER); \
151 } while(0)
152
153 #define VARIANT1_INIT64() \
154 if (variant == 1) \
155 { \
156 VARIANT1_CHECK(); \
157 } \
158 const uint64_t tweak1_2 = (variant == 1) ? (state.hs.w[24] ^ (*((const uint64_t*)NONCE_POINTER))) : 0
159
160 #define VARIANT2_INIT64() \
161 uint64_t division_result = 0; \
162 uint64_t sqrt_result = 0; \
163 do if (variant >= 2) \
164 { \
165 U64(b)[2] = state.hs.w[8] ^ state.hs.w[10]; \
166 U64(b)[3] = state.hs.w[9] ^ state.hs.w[11]; \
167 division_result = SWAP64LE(state.hs.w[12]); \
168 sqrt_result = SWAP64LE(state.hs.w[13]); \
169 } while (0)
170
171 #define VARIANT2_PORTABLE_INIT() \
172 uint64_t division_result = 0; \
173 uint64_t sqrt_result = 0; \
174 do if (variant >= 2) \
175 { \
176 memcpy(b + AES_BLOCK_SIZE, state.hs.b + 64, AES_BLOCK_SIZE); \
177 xor64(b + AES_BLOCK_SIZE, state.hs.b + 80); \
178 xor64(b + AES_BLOCK_SIZE + 8, state.hs.b + 88); \
179 division_result = SWAP64LE(state.hs.w[12]); \
180 sqrt_result = SWAP64LE(state.hs.w[13]); \
181 } while (0)
182
183 #define VARIANT2_SHUFFLE_ADD_SSE2(base_ptr, offset) \
184 do if (variant >= 2) \
185 { \
186 __m128i chunk1 = _mm_load_si128((__m128i *)((base_ptr) + ((offset) ^ 0x10))); \
187 const __m128i chunk2 = _mm_load_si128((__m128i *)((base_ptr) + ((offset) ^ 0x20))); \
188 const __m128i chunk3 = _mm_load_si128((__m128i *)((base_ptr) + ((offset) ^ 0x30))); \
189 _mm_store_si128((__m128i *)((base_ptr) + ((offset) ^ 0x10)), _mm_add_epi64(chunk3, _b1)); \
190 _mm_store_si128((__m128i *)((base_ptr) + ((offset) ^ 0x20)), _mm_add_epi64(chunk1, _b)); \
191 _mm_store_si128((__m128i *)((base_ptr) + ((offset) ^ 0x30)), _mm_add_epi64(chunk2, _a)); \
192 if (variant >= 4) \
193 { \
194 chunk1 = _mm_xor_si128(chunk1, chunk2); \
195 _c = _mm_xor_si128(_c, chunk3); \
196 _c = _mm_xor_si128(_c, chunk1); \
197 } \
198 } while (0)
199
200 #define VARIANT2_SHUFFLE_ADD_NEON(base_ptr, offset) \
201 do if (variant >= 2) \
202 { \
203 uint64x2_t chunk1 = vld1q_u64(U64((base_ptr) + ((offset) ^ 0x10))); \
204 const uint64x2_t chunk2 = vld1q_u64(U64((base_ptr) + ((offset) ^ 0x20))); \
205 const uint64x2_t chunk3 = vld1q_u64(U64((base_ptr) + ((offset) ^ 0x30))); \
206 vst1q_u64(U64((base_ptr) + ((offset) ^ 0x10)), vaddq_u64(chunk3, vreinterpretq_u64_u8(_b1))); \
207 vst1q_u64(U64((base_ptr) + ((offset) ^ 0x20)), vaddq_u64(chunk1, vreinterpretq_u64_u8(_b))); \
208 vst1q_u64(U64((base_ptr) + ((offset) ^ 0x30)), vaddq_u64(chunk2, vreinterpretq_u64_u8(_a))); \
209 if (variant >= 4) \
210 { \
211 chunk1 = veorq_u64(chunk1, chunk2); \
212 _c = vreinterpretq_u8_u64(veorq_u64(vreinterpretq_u64_u8(_c), chunk3)); \
213 _c = vreinterpretq_u8_u64(veorq_u64(vreinterpretq_u64_u8(_c), chunk1)); \
214 } \
215 } while (0)
216
217 #define VARIANT2_PORTABLE_SHUFFLE_ADD(out, a_, base_ptr, offset) \
218 do if (variant >= 2) \
219 { \
220 uint64_t* chunk1 = U64((base_ptr) + ((offset) ^ 0x10)); \
221 uint64_t* chunk2 = U64((base_ptr) + ((offset) ^ 0x20)); \
222 uint64_t* chunk3 = U64((base_ptr) + ((offset) ^ 0x30)); \
223 \
224 uint64_t chunk1_old[2] = { SWAP64LE(chunk1[0]), SWAP64LE(chunk1[1]) }; \
225 const uint64_t chunk2_old[2] = { SWAP64LE(chunk2[0]), SWAP64LE(chunk2[1]) }; \
226 const uint64_t chunk3_old[2] = { SWAP64LE(chunk3[0]), SWAP64LE(chunk3[1]) }; \
227 \
228 uint64_t b1[2]; \
229 memcpy_swap64le(b1, b + 16, 2); \
230 chunk1[0] = SWAP64LE(chunk3_old[0] + b1[0]); \
231 chunk1[1] = SWAP64LE(chunk3_old[1] + b1[1]); \
232 \
233 uint64_t a0[2]; \
234 memcpy_swap64le(a0, a_, 2); \
235 chunk3[0] = SWAP64LE(chunk2_old[0] + a0[0]); \
236 chunk3[1] = SWAP64LE(chunk2_old[1] + a0[1]); \
237 \
238 uint64_t b0[2]; \
239 memcpy_swap64le(b0, b, 2); \
240 chunk2[0] = SWAP64LE(chunk1_old[0] + b0[0]); \
241 chunk2[1] = SWAP64LE(chunk1_old[1] + b0[1]); \
242 if (variant >= 4) \
243 { \
244 uint64_t out_copy[2]; \
245 memcpy_swap64le(out_copy, out, 2); \
246 chunk1_old[0] ^= chunk2_old[0]; \
247 chunk1_old[1] ^= chunk2_old[1]; \
248 out_copy[0] ^= chunk3_old[0]; \
249 out_copy[1] ^= chunk3_old[1]; \
250 out_copy[0] ^= chunk1_old[0]; \
251 out_copy[1] ^= chunk1_old[1]; \
252 memcpy_swap64le(out, out_copy, 2); \
253 } \
254 } while (0)
255
256 #define VARIANT2_INTEGER_MATH_DIVISION_STEP(b, ptr) \
257 uint64_t tmpx = division_result ^ (sqrt_result << 32); \
258 ((uint64_t*)(b))[0] ^= SWAP64LE(tmpx); \
259 { \
260 const uint64_t dividend = SWAP64LE(((uint64_t*)(ptr))[1]); \
261 const uint32_t divisor = (SWAP64LE(((uint64_t*)(ptr))[0]) + (uint32_t)(sqrt_result << 1)) | 0x80000001UL; \
262 division_result = ((uint32_t)(dividend / divisor)) + \
263 (((uint64_t)(dividend % divisor)) << 32); \
264 } \
265 const uint64_t sqrt_input = SWAP64LE(((uint64_t*)(ptr))[0]) + division_result
266
267 #define VARIANT2_INTEGER_MATH_SSE2(b, ptr) \
268 do if ((variant == 2) || (variant == 3)) \
269 { \
270 VARIANT2_INTEGER_MATH_DIVISION_STEP(b, ptr); \
271 VARIANT2_INTEGER_MATH_SQRT_STEP_SSE2(); \
272 VARIANT2_INTEGER_MATH_SQRT_FIXUP(sqrt_result); \
273 } while(0)
274
275 #if defined DBL_MANT_DIG && (DBL_MANT_DIG >= 50)
276 // double precision floating point type has enough bits of precision on current platform
277 #define VARIANT2_PORTABLE_INTEGER_MATH(b, ptr) \
278 do if ((variant == 2) || (variant == 3)) \
279 { \
280 VARIANT2_INTEGER_MATH_DIVISION_STEP(b, ptr); \
281 VARIANT2_INTEGER_MATH_SQRT_STEP_FP64(); \
282 VARIANT2_INTEGER_MATH_SQRT_FIXUP(sqrt_result); \
283 } while (0)
284 #else
285 // double precision floating point type is not good enough on current platform
286 // fall back to the reference code (integer only)
287 #define VARIANT2_PORTABLE_INTEGER_MATH(b, ptr) \
288 do if ((variant == 2) || (variant == 3)) \
289 { \
290 VARIANT2_INTEGER_MATH_DIVISION_STEP(b, ptr); \
291 VARIANT2_INTEGER_MATH_SQRT_STEP_REF(); \
292 } while (0)
293 #endif
294
295 #define VARIANT2_2_PORTABLE() \
296 if (variant == 2 || variant == 3) { \
297 xor_blocks(long_state + (j ^ 0x10), d); \
298 xor_blocks(d, long_state + (j ^ 0x20)); \
299 }
300
301 #define VARIANT2_2() \
302 do if (variant == 2 || variant == 3) \
303 { \
304 *U64(local_hp_state + (j ^ 0x10)) ^= SWAP64LE(hi); \
305 *(U64(local_hp_state + (j ^ 0x10)) + 1) ^= SWAP64LE(lo); \
306 hi ^= SWAP64LE(*U64(local_hp_state + (j ^ 0x20))); \
307 lo ^= SWAP64LE(*(U64(local_hp_state + (j ^ 0x20)) + 1)); \
308 } while (0)
309
310 #define V4_REG_LOAD(dst, src) \
311 do { \
312 memcpy((dst), (src), sizeof(v4_reg)); \
313 if (sizeof(v4_reg) == sizeof(uint32_t)) \
314 *(dst) = SWAP32LE(*(dst)); \
315 else \
316 *(dst) = SWAP64LE(*(dst)); \
317 } while (0)
318
319 #define VARIANT4_RANDOM_MATH_INIT() \
320 v4_reg r[9]; \
321 struct V4_Instruction code[NUM_INSTRUCTIONS_MAX + 1]; \
322 int jit = use_v4_jit(); \
323 do if (variant >= 4) \
324 { \
325 for (int i = 0; i < 4; ++i) \
326 V4_REG_LOAD(r + i, (uint8_t*)(state.hs.w + 12) + sizeof(v4_reg) * i); \
327 v4_random_math_init(code, height); \
328 if (jit) \
329 { \
330 int ret = v4_generate_JIT_code(code, hp_jitfunc, 4096); \
331 if (ret < 0) \
332 local_abort("Error generating CryptonightR code"); \
333 } \
334 } while (0)
335
336 #define VARIANT4_RANDOM_MATH(a, b, r, _b, _b1) \
337 do if (variant >= 4) \
338 { \
339 uint64_t t[2]; \
340 memcpy(t, b, sizeof(uint64_t)); \
341 \
342 if (sizeof(v4_reg) == sizeof(uint32_t)) \
343 t[0] ^= SWAP64LE((r[0] + r[1]) | ((uint64_t)(r[2] + r[3]) << 32)); \
344 else \
345 t[0] ^= SWAP64LE((r[0] + r[1]) ^ (r[2] + r[3])); \
346 \
347 memcpy(b, t, sizeof(uint64_t)); \
348 \
349 V4_REG_LOAD(r + 4, a); \
350 V4_REG_LOAD(r + 5, (uint64_t*)(a) + 1); \
351 V4_REG_LOAD(r + 6, _b); \
352 V4_REG_LOAD(r + 7, _b1); \
353 V4_REG_LOAD(r + 8, (uint64_t*)(_b1) + 1); \
354 \
355 if (jit) \
356 (*hp_jitfunc)(r); \
357 else \
358 v4_random_math(code, r); \
359 \
360 memcpy(t, a, sizeof(uint64_t) * 2); \
361 \
362 if (sizeof(v4_reg) == sizeof(uint32_t)) { \
363 t[0] ^= SWAP64LE(r[2] | ((uint64_t)(r[3]) << 32)); \
364 t[1] ^= SWAP64LE(r[0] | ((uint64_t)(r[1]) << 32)); \
365 } else { \
366 t[0] ^= SWAP64LE(r[2] ^ r[3]); \
367 t[1] ^= SWAP64LE(r[0] ^ r[1]); \
368 } \
369 memcpy(a, t, sizeof(uint64_t) * 2); \
370 } while (0)
371
372
373 #if !defined NO_AES && (defined(__x86_64__) || (defined(_MSC_VER) && defined(_WIN64)))
374 // Optimised code below, uses x86-specific intrinsics, SSE2, AES-NI
375 // Fall back to more portable code is down at the bottom
376
377 #include <emmintrin.h>
378
379 #if defined(_MSC_VER)
380 #include <intrin.h>
381 #include <windows.h>
382 #define STATIC
383 #define INLINE __inline
384 #if !defined(RDATA_ALIGN16)
385 #define RDATA_ALIGN16 __declspec(align(16))
386 #endif
387 #elif defined(__MINGW32__)
388 #include <intrin.h>
389 #include <windows.h>
390 #define STATIC static
391 #define INLINE inline
392 #if !defined(RDATA_ALIGN16)
393 #define RDATA_ALIGN16 __attribute__ ((aligned(16)))
394 #endif
395 #else
396 #include <wmmintrin.h>
397 #include <sys/mman.h>
398 #define STATIC static
399 #define INLINE inline
400 #if !defined(RDATA_ALIGN16)
401 #define RDATA_ALIGN16 __attribute__ ((aligned(16)))
402 #endif
403 #endif
404
405 #if defined(__INTEL_COMPILER)
406 #define ASM __asm__
407 #elif !defined(_MSC_VER)
408 #define ASM __asm__
409 #else
410 #define ASM __asm
411 #endif
412
413 #define TOTALBLOCKS (MEMORY / AES_BLOCK_SIZE)
414
415 #define U64(x) ((uint64_t *) (x))
416 #define R128(x) ((__m128i *) (x))
417
418 #define state_index(x) (((*((uint64_t *)x) >> 4) & (TOTALBLOCKS - 1)) << 4)
419 #if defined(_MSC_VER)
420 #if !defined(_WIN64)
421 #define __mul() lo = mul128(c[0], b[0], &hi);
422 #else
423 #define __mul() lo = _umul128(c[0], b[0], &hi);
424 #endif
425 #else
426 #if defined(__x86_64__)
427 #define __mul() ASM("mulq %3\n\t" : "=d"(hi), "=a"(lo) : "%a" (c[0]), "rm" (b[0]) : "cc");
428 #else
429 #define __mul() lo = mul128(c[0], b[0], &hi);
430 #endif
431 #endif
432
433 #define pre_aes() \
434 j = state_index(a); \
435 _c = _mm_load_si128(R128(&local_hp_state[j])); \
436 _a = _mm_load_si128(R128(a)); \
437
438 /*
439 * An SSE-optimized implementation of the second half of CryptoNight step 3.
440 * After using AES to mix a scratchpad value into _c (done by the caller),
441 * this macro xors it with _b and stores the result back to the same index (j) that it
442 * loaded the scratchpad value from. It then performs a second random memory
443 * read/write from the scratchpad, but this time mixes the values using a 64
444 * bit multiply.
445 * This code is based upon an optimized implementation by dga.
446 */
447 #define post_aes() \
448 VARIANT2_SHUFFLE_ADD_SSE2(local_hp_state, j); \
449 _mm_store_si128(R128(c), _c); \
450 _mm_store_si128(R128(&local_hp_state[j]), _mm_xor_si128(_b, _c)); \
451 VARIANT1_1(&local_hp_state[j]); \
452 j = state_index(c); \
453 p = U64(&local_hp_state[j]); \
454 b[0] = p[0]; b[1] = p[1]; \
455 VARIANT2_INTEGER_MATH_SSE2(b, c); \
456 VARIANT4_RANDOM_MATH(a, b, r, &_b, &_b1); \
457 __mul(); \
458 VARIANT2_2(); \
459 VARIANT2_SHUFFLE_ADD_SSE2(local_hp_state, j); \
460 a[0] += hi; a[1] += lo; \
461 p = U64(&local_hp_state[j]); \
462 p[0] = a[0]; p[1] = a[1]; \
463 a[0] ^= b[0]; a[1] ^= b[1]; \
464 VARIANT1_2(p + 1); \
465 _b1 = _b; \
466 _b = _c; \
467
468 #pragma pack(push, 1)
469 union cn_slow_hash_state
470 {
471 union hash_state hs;
472 struct
473 {
474 uint8_t k[64];
475 uint8_t init[INIT_SIZE_BYTE];
476 };
477 };
478 #pragma pack(pop)
479
480 THREADV uint8_t *hp_state = NULL;
481 THREADV int hp_allocated = 0;
482 THREADV v4_random_math_JIT_func hp_jitfunc = NULL;
483 THREADV uint8_t *hp_jitfunc_memory = NULL;
484 THREADV int hp_jitfunc_allocated = 0;
485
486 #if defined(_MSC_VER)
487 #define cpuid(info,x) __cpuidex(info,x,0)
488 #else
489 void cpuid(int CPUInfo[4], int InfoType)
490 {
491 ASM __volatile__
492 (
493 "cpuid":
494 "=a" (CPUInfo[0]),
495 "=b" (CPUInfo[1]),
496 "=c" (CPUInfo[2]),
497 "=d" (CPUInfo[3]) :
498 "a" (InfoType), "c" (0)
499 );
500 }
501 #endif
502
503 /**
504 * @brief a = (a xor b), where a and b point to 128 bit values
505 */
506
507 STATIC INLINE void xor_blocks(uint8_t *a, const uint8_t *b)
508 {
509 U64(a)[0] ^= U64(b)[0];
510 U64(a)[1] ^= U64(b)[1];
511 }
512
513 STATIC INLINE void xor64(uint64_t *a, const uint64_t b)
514 {
515 *a ^= b;
516 }
517
518 /**
519 * @brief uses cpuid to determine if the CPU supports the AES instructions
520 * @return true if the CPU supports AES, false otherwise
521 */
522
523
524 STATIC INLINE int check_aes_hw(void)
525 {
526 int cpuid_results[4];
527 static int supported = -1;
528
529 if(supported >= 0)
530 return supported;
531
532 cpuid(cpuid_results,1);
533 return supported = cpuid_results[2] & (1 << 25);
534 }
535
536 STATIC INLINE void aes_256_assist1(__m128i* t1, __m128i * t2)
537 {
538 __m128i t4;
539 *t2 = _mm_shuffle_epi32(*t2, 0xff);
540 t4 = _mm_slli_si128(*t1, 0x04);
541 *t1 = _mm_xor_si128(*t1, t4);
542 t4 = _mm_slli_si128(t4, 0x04);
543 *t1 = _mm_xor_si128(*t1, t4);
544 t4 = _mm_slli_si128(t4, 0x04);
545 *t1 = _mm_xor_si128(*t1, t4);
546 *t1 = _mm_xor_si128(*t1, *t2);
547 }
548
549 STATIC INLINE void aes_256_assist2(__m128i* t1, __m128i * t3)
550 {
551 __m128i t2, t4;
552 t4 = _mm_aeskeygenassist_si128(*t1, 0x00);
553 t2 = _mm_shuffle_epi32(t4, 0xaa);
554 t4 = _mm_slli_si128(*t3, 0x04);
555 *t3 = _mm_xor_si128(*t3, t4);
556 t4 = _mm_slli_si128(t4, 0x04);
557 *t3 = _mm_xor_si128(*t3, t4);
558 t4 = _mm_slli_si128(t4, 0x04);
559 *t3 = _mm_xor_si128(*t3, t4);
560 *t3 = _mm_xor_si128(*t3, t2);
561 }
562
563 /**
564 * @brief expands 'key' into a form it can be used for AES encryption.
565 *
566 * This is an SSE-optimized implementation of AES key schedule generation. It
567 * expands the key into multiple round keys, each of which is used in one round
568 * of the AES encryption used to fill (and later, extract randomness from)
569 * the large 2MB buffer. Note that CryptoNight does not use a completely
570 * standard AES encryption for its buffer expansion, so do not copy this
571 * function outside of Monero without caution! This version uses the hardware
572 * AESKEYGENASSIST instruction to speed key generation, and thus requires
573 * CPU AES support.
574 * For more information about these functions, see page 19 of Intel's AES instructions
575 * white paper:
576 * https://www.intel.com/content/dam/doc/white-paper/advanced-encryption-standard-new-instructions-set-paper.pdf
577 *
578 * @param key the input 128 bit key
579 * @param expandedKey An output buffer to hold the generated key schedule
580 */
581
582 STATIC INLINE void aes_expand_key(const uint8_t *key, uint8_t *expandedKey)
583 {
584 __m128i *ek = R128(expandedKey);
585 __m128i t1, t2, t3;
586
587 t1 = _mm_loadu_si128(R128(key));
588 t3 = _mm_loadu_si128(R128(key + 16));
589
590 ek[0] = t1;
591 ek[1] = t3;
592
593 t2 = _mm_aeskeygenassist_si128(t3, 0x01);
594 aes_256_assist1(&t1, &t2);
595 ek[2] = t1;
596 aes_256_assist2(&t1, &t3);
597 ek[3] = t3;
598
599 t2 = _mm_aeskeygenassist_si128(t3, 0x02);
600 aes_256_assist1(&t1, &t2);
601 ek[4] = t1;
602 aes_256_assist2(&t1, &t3);
603 ek[5] = t3;
604
605 t2 = _mm_aeskeygenassist_si128(t3, 0x04);
606 aes_256_assist1(&t1, &t2);
607 ek[6] = t1;
608 aes_256_assist2(&t1, &t3);
609 ek[7] = t3;
610
611 t2 = _mm_aeskeygenassist_si128(t3, 0x08);
612 aes_256_assist1(&t1, &t2);
613 ek[8] = t1;
614 aes_256_assist2(&t1, &t3);
615 ek[9] = t3;
616
617 t2 = _mm_aeskeygenassist_si128(t3, 0x10);
618 aes_256_assist1(&t1, &t2);
619 ek[10] = t1;
620 }
621
622 /**
623 * @brief a "pseudo" round of AES (similar to but slightly different from normal AES encryption)
624 *
625 * To fill its 2MB scratch buffer, CryptoNight uses a nonstandard implementation
626 * of AES encryption: It applies 10 rounds of the basic AES encryption operation
627 * to an input 128 bit chunk of data <in>. Unlike normal AES, however, this is
628 * all it does; it does not perform the initial AddRoundKey step (this is done
629 * in subsequent steps by aesenc_si128), and it does not use the simpler final round.
630 * Hence, this is a "pseudo" round - though the function actually implements 10 rounds together.
631 *
632 * Note that unlike aesb_pseudo_round, this function works on multiple data chunks.
633 *
634 * @param in a pointer to nblocks * 128 bits of data to be encrypted
635 * @param out a pointer to an nblocks * 128 bit buffer where the output will be stored
636 * @param expandedKey the expanded AES key
637 * @param nblocks the number of 128 blocks of data to be encrypted
638 */
639
640 STATIC INLINE void aes_pseudo_round(const uint8_t *in, uint8_t *out,
641 const uint8_t *expandedKey, int nblocks)
642 {
643 __m128i *k = R128(expandedKey);
644 __m128i d;
645 int i;
646
647 for(i = 0; i < nblocks; i++)
648 {
649 d = _mm_loadu_si128(R128(in + i * AES_BLOCK_SIZE));
650 d = _mm_aesenc_si128(d, *R128(&k[0]));
651 d = _mm_aesenc_si128(d, *R128(&k[1]));
652 d = _mm_aesenc_si128(d, *R128(&k[2]));
653 d = _mm_aesenc_si128(d, *R128(&k[3]));
654 d = _mm_aesenc_si128(d, *R128(&k[4]));
655 d = _mm_aesenc_si128(d, *R128(&k[5]));
656 d = _mm_aesenc_si128(d, *R128(&k[6]));
657 d = _mm_aesenc_si128(d, *R128(&k[7]));
658 d = _mm_aesenc_si128(d, *R128(&k[8]));
659 d = _mm_aesenc_si128(d, *R128(&k[9]));
660 _mm_storeu_si128((R128(out + i * AES_BLOCK_SIZE)), d);
661 }
662 }
663
664 /**
665 * @brief aes_pseudo_round that loads data from *in and xors it with *xor first
666 *
667 * This function performs the same operations as aes_pseudo_round, but before
668 * performing the encryption of each 128 bit block from <in>, it xors
669 * it with the corresponding block from <xor>.
670 *
671 * @param in a pointer to nblocks * 128 bits of data to be encrypted
672 * @param out a pointer to an nblocks * 128 bit buffer where the output will be stored
673 * @param expandedKey the expanded AES key
674 * @param xor a pointer to an nblocks * 128 bit buffer that is xored into in before encryption (in is left unmodified)
675 * @param nblocks the number of 128 blocks of data to be encrypted
676 */
677
678 STATIC INLINE void aes_pseudo_round_xor(const uint8_t *in, uint8_t *out,
679 const uint8_t *expandedKey, const uint8_t *xor, int nblocks)
680 {
681 __m128i *k = R128(expandedKey);
682 __m128i *x = R128(xor);
683 __m128i d;
684 int i;
685
686 for(i = 0; i < nblocks; i++)
687 {
688 d = _mm_loadu_si128(R128(in + i * AES_BLOCK_SIZE));
689 d = _mm_xor_si128(d, *R128(x++));
690 d = _mm_aesenc_si128(d, *R128(&k[0]));
691 d = _mm_aesenc_si128(d, *R128(&k[1]));
692 d = _mm_aesenc_si128(d, *R128(&k[2]));
693 d = _mm_aesenc_si128(d, *R128(&k[3]));
694 d = _mm_aesenc_si128(d, *R128(&k[4]));
695 d = _mm_aesenc_si128(d, *R128(&k[5]));
696 d = _mm_aesenc_si128(d, *R128(&k[6]));
697 d = _mm_aesenc_si128(d, *R128(&k[7]));
698 d = _mm_aesenc_si128(d, *R128(&k[8]));
699 d = _mm_aesenc_si128(d, *R128(&k[9]));
700 _mm_storeu_si128((R128(out + i * AES_BLOCK_SIZE)), d);
701 }
702 }
703
704 #if defined(_MSC_VER) || defined(__MINGW32__)
705 BOOL SetLockPagesPrivilege(HANDLE hProcess, BOOL bEnable)
706 {
707 struct
708 {
709 DWORD count;
710 LUID_AND_ATTRIBUTES privilege[1];
711 } info;
712
713 HANDLE token;
714 if(!OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES, &token))
715 return FALSE;
716
717 info.count = 1;
718 info.privilege[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
719
720 if(!LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &(info.privilege[0].Luid)))
721 return FALSE;
722
723 if(!AdjustTokenPrivileges(token, FALSE, (PTOKEN_PRIVILEGES) &info, 0, NULL, NULL))
724 return FALSE;
725
726 if (GetLastError() != ERROR_SUCCESS)
727 return FALSE;
728
729 CloseHandle(token);
730
731 return TRUE;
732
733 }
734 #endif
735
736 /**
737 * @brief allocate the 2MB scratch buffer using OS support for huge pages, if available
738 *
739 * This function tries to allocate the 2MB scratch buffer using a single
740 * 2MB "huge page" (instead of the usual 4KB page sizes) to reduce TLB misses
741 * during the random accesses to the scratch buffer. This is one of the
742 * important speed optimizations needed to make CryptoNight faster.
743 *
744 * No parameters. Updates a thread-local pointer, hp_state, to point to
745 * the allocated buffer.
746 */
747
748 void cn_slow_hash_allocate_state(void)
749 {
750 if(hp_state != NULL)
751 return;
752
753 #if defined(_MSC_VER) || defined(__MINGW32__)
754 SetLockPagesPrivilege(GetCurrentProcess(), TRUE);
755 hp_state = (uint8_t *) VirtualAlloc(hp_state, MEMORY, MEM_LARGE_PAGES |
756 MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
757 #else
758 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
759 defined(__DragonFly__) || defined(__NetBSD__)
760 hp_state = mmap(0, MEMORY, PROT_READ | PROT_WRITE,
761 MAP_PRIVATE | MAP_ANON, -1, 0);
762 #else
763 hp_state = mmap(0, MEMORY, PROT_READ | PROT_WRITE,
764 MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0);
765 #endif
766 if(hp_state == MAP_FAILED)
767 hp_state = NULL;
768 #endif
769 hp_allocated = 1;
770 if(hp_state == NULL)
771 {
772 hp_allocated = 0;
773 hp_state = (uint8_t *) malloc(MEMORY);
774 }
775
776
777 #if defined(_MSC_VER) || defined(__MINGW32__)
778 hp_jitfunc_memory = (uint8_t *) VirtualAlloc(hp_jitfunc_memory, 4096 + 4095,
779 MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
780 #else
781 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
782 defined(__DragonFly__) || defined(__NetBSD__)
783 #ifdef __NetBSD__
784 #define RESERVED_FLAGS PROT_MPROTECT(PROT_EXEC)
785 #else
786 #define RESERVED_FLAGS 0
787 #endif
788 hp_jitfunc_memory = mmap(0, 4096 + 4096, PROT_READ | PROT_WRITE | RESERVED_FLAGS,
789 MAP_PRIVATE | MAP_ANON, -1, 0);
790 #else
791 hp_jitfunc_memory = mmap(0, 4096 + 4096, PROT_READ | PROT_WRITE | PROT_EXEC,
792 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
793 #endif
794 if(hp_jitfunc_memory == MAP_FAILED)
795 hp_jitfunc_memory = NULL;
796 #endif
797 hp_jitfunc_allocated = 1;
798 if (hp_jitfunc_memory == NULL)
799 {
800 hp_jitfunc_allocated = 0;
801 hp_jitfunc_memory = malloc(4096 + 4095);
802 }
803 hp_jitfunc = (v4_random_math_JIT_func)((size_t)(hp_jitfunc_memory + 4095) & ~4095);
804 }
805
806 /**
807 *@brief frees the state allocated by slow_hash_allocate_state
808 */
809
810 void cn_slow_hash_free_state(void)
811 {
812 if(hp_state == NULL)
813 return;
814
815 if(!hp_allocated)
816 free(hp_state);
817 else
818 {
819 #if defined(_MSC_VER) || defined(__MINGW32__)
820 VirtualFree(hp_state, 0, MEM_RELEASE);
821 #else
822 munmap(hp_state, MEMORY);
823 #endif
824 }
825
826 if(!hp_jitfunc_allocated)
827 free(hp_jitfunc_memory);
828 else
829 {
830 #if defined(_MSC_VER) || defined(__MINGW32__)
831 VirtualFree(hp_jitfunc_memory, 0, MEM_RELEASE);
832 #else
833 munmap(hp_jitfunc_memory, 4096 + 4095);
834 #endif
835 }
836
837 hp_state = NULL;
838 hp_allocated = 0;
839 hp_jitfunc = NULL;
840 hp_jitfunc_memory = NULL;
841 hp_jitfunc_allocated = 0;
842 }
843
844 /**
845 * @brief the hash function implementing CryptoNight, used for the Monero proof-of-work
846 *
847 * Computes the hash of <data> (which consists of <length> bytes), returning the
848 * hash in <hash>. The CryptoNight hash operates by first using Keccak 1600,
849 * the 1600 bit variant of the Keccak hash used in SHA-3, to create a 200 byte
850 * buffer of pseudorandom data by hashing the supplied data. It then uses this
851 * random data to fill a large 2MB buffer with pseudorandom data by iteratively
852 * encrypting it using 10 rounds of AES per entry. After this initialization,
853 * it executes 524,288 rounds of mixing through the random 2MB buffer using
854 * AES (typically provided in hardware on modern CPUs) and a 64 bit multiply.
855 * Finally, it re-mixes this large buffer back into
856 * the 200 byte "text" buffer, and then hashes this buffer using one of four
857 * pseudorandomly selected hash functions (Blake, Groestl, JH, or Skein)
858 * to populate the output.
859 *
860 * The 2MB buffer and choice of functions for mixing are designed to make the
861 * algorithm "CPU-friendly" (and thus, reduce the advantage of GPU, FPGA,
862 * or ASIC-based implementations): the functions used are fast on modern
863 * CPUs, and the 2MB size matches the typical amount of L3 cache available per
864 * core on 2013-era CPUs. When available, this implementation will use hardware
865 * AES support on x86 CPUs.
866 *
867 * A diagram of the inner loop of this function can be found at
868 * https://www.cs.cmu.edu/~dga/crypto/xmr/cryptonight.png
869 *
870 * @param data the data to hash
871 * @param length the length in bytes of the data
872 * @param hash a pointer to a buffer in which the final 256 bit hash will be stored
873 */
874 void cn_slow_hash(const void *data, size_t length, char *hash, int variant, int prehashed, uint64_t height)
875 {
876 RDATA_ALIGN16 uint8_t expandedKey[240]; /* These buffers are aligned to use later with SSE functions */
877
878 uint8_t text[INIT_SIZE_BYTE];
879 RDATA_ALIGN16 uint64_t a[2];
880 RDATA_ALIGN16 uint64_t b[4];
881 RDATA_ALIGN16 uint64_t c[2];
882 union cn_slow_hash_state state;
883 __m128i _a, _b, _b1, _c;
884 uint64_t hi, lo;
885
886 size_t i, j;
887 uint64_t *p = NULL;
888 oaes_ctx *aes_ctx = NULL;
889 int useAes = !force_software_aes() && check_aes_hw();
890
891 static void (*const extra_hashes[4])(const void *, size_t, char *) =
892 {
893 hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein
894 };
895
896 // this isn't supposed to happen, but guard against it for now.
897 if(hp_state == NULL)
898 cn_slow_hash_allocate_state();
899
900 // locals to avoid constant TLS dereferencing
901 uint8_t *local_hp_state = hp_state;
902
903 /* CryptoNight Step 1: Use Keccak1600 to initialize the 'state' (and 'text') buffers from the data. */
904 if (prehashed) {
905 memcpy(&state.hs, data, length);
906 } else {
907 hash_process(&state.hs, data, length);
908 }
909 memcpy(text, state.init, INIT_SIZE_BYTE);
910
911 VARIANT1_INIT64();
912 VARIANT2_INIT64();
913 VARIANT4_RANDOM_MATH_INIT();
914
915 /* CryptoNight Step 2: Iteratively encrypt the results from Keccak to fill
916 * the 2MB large random access buffer.
917 */
918
919 if(useAes)
920 {
921 aes_expand_key(state.hs.b, expandedKey);
922 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
923 {
924 aes_pseudo_round(text, text, expandedKey, INIT_SIZE_BLK);
925 memcpy(&local_hp_state[i * INIT_SIZE_BYTE], text, INIT_SIZE_BYTE);
926 }
927 }
928 else
929 {
930 aes_ctx = (oaes_ctx *) oaes_alloc();
931 oaes_key_import_data(aes_ctx, state.hs.b, AES_KEY_SIZE);
932 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
933 {
934 for(j = 0; j < INIT_SIZE_BLK; j++)
935 aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], aes_ctx->key->exp_data);
936
937 memcpy(&local_hp_state[i * INIT_SIZE_BYTE], text, INIT_SIZE_BYTE);
938 }
939 }
940
941 U64(a)[0] = U64(&state.k[0])[0] ^ U64(&state.k[32])[0];
942 U64(a)[1] = U64(&state.k[0])[1] ^ U64(&state.k[32])[1];
943 U64(b)[0] = U64(&state.k[16])[0] ^ U64(&state.k[48])[0];
944 U64(b)[1] = U64(&state.k[16])[1] ^ U64(&state.k[48])[1];
945
946 /* CryptoNight Step 3: Bounce randomly 1,048,576 times (1<<20) through the mixing buffer,
947 * using 524,288 iterations of the following mixing function. Each execution
948 * performs two reads and writes from the mixing buffer.
949 */
950
951 _b = _mm_load_si128(R128(b));
952 _b1 = _mm_load_si128(R128(b) + 1);
953 // Two independent versions, one with AES, one without, to ensure that
954 // the useAes test is only performed once, not every iteration.
955 if(useAes)
956 {
957 for(i = 0; i < ITER / 2; i++)
958 {
959 pre_aes();
960 _c = _mm_aesenc_si128(_c, _a);
961 post_aes();
962 }
963 }
964 else
965 {
966 for(i = 0; i < ITER / 2; i++)
967 {
968 pre_aes();
969 aesb_single_round((uint8_t *) &_c, (uint8_t *) &_c, (uint8_t *) &_a);
970 post_aes();
971 }
972 }
973
974 /* CryptoNight Step 4: Sequentially pass through the mixing buffer and use 10 rounds
975 * of AES encryption to mix the random data back into the 'text' buffer. 'text'
976 * was originally created with the output of Keccak1600. */
977
978 memcpy(text, state.init, INIT_SIZE_BYTE);
979 if(useAes)
980 {
981 aes_expand_key(&state.hs.b[32], expandedKey);
982 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
983 {
984 // add the xor to the pseudo round
985 aes_pseudo_round_xor(text, text, expandedKey, &local_hp_state[i * INIT_SIZE_BYTE], INIT_SIZE_BLK);
986 }
987 }
988 else
989 {
990 oaes_key_import_data(aes_ctx, &state.hs.b[32], AES_KEY_SIZE);
991 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
992 {
993 for(j = 0; j < INIT_SIZE_BLK; j++)
994 {
995 xor_blocks(&text[j * AES_BLOCK_SIZE], &local_hp_state[i * INIT_SIZE_BYTE + j * AES_BLOCK_SIZE]);
996 aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], aes_ctx->key->exp_data);
997 }
998 }
999 oaes_free((OAES_CTX **) &aes_ctx);
1000 }
1001
1002 /* CryptoNight Step 5: Apply Keccak to the state again, and then
1003 * use the resulting data to select which of four finalizer
1004 * hash functions to apply to the data (Blake, Groestl, JH, or Skein).
1005 * Use this hash to squeeze the state array down
1006 * to the final 256 bit hash output.
1007 */
1008
1009 memcpy(state.init, text, INIT_SIZE_BYTE);
1010 hash_permutation(&state.hs);
1011 extra_hashes[state.hs.b[0] & 3](&state, 200, hash);
1012 }
1013
1014 #elif !defined NO_AES && (defined(__arm__) || defined(__aarch64__))
1015 #ifdef __aarch64__
1016 #include <sys/mman.h>
1017 THREADV uint8_t *hp_state = NULL;
1018 THREADV int hp_malloced = 0;
1019
1020 void cn_slow_hash_allocate_state(void)
1021 {
1022 if(hp_state != NULL)
1023 return;
1024
1025 #ifndef MAP_HUGETLB
1026 #define MAP_HUGETLB 0
1027 #endif
1028 hp_state = mmap(0, MEMORY, PROT_READ | PROT_WRITE,
1029 MAP_PRIVATE | MAP_ANON | MAP_HUGETLB, -1, 0);
1030
1031 if(hp_state == MAP_FAILED)
1032 hp_state = NULL;
1033 if(hp_state == NULL)
1034 {
1035 hp_malloced = 1;
1036 hp_state = (uint8_t *) malloc(MEMORY);
1037 }
1038 }
1039
1040 void cn_slow_hash_free_state(void)
1041 {
1042 if(hp_state == NULL)
1043 return;
1044
1045 if (hp_malloced)
1046 free(hp_state);
1047 else
1048 munmap(hp_state, MEMORY);
1049 hp_state = NULL;
1050 hp_malloced = 0;
1051 }
1052 #else
1053 void cn_slow_hash_allocate_state(void)
1054 {
1055 // Do nothing, this is just to maintain compatibility with the upgraded slow-hash.c
1056 return;
1057 }
1058
1059 void cn_slow_hash_free_state(void)
1060 {
1061 // As above
1062 return;
1063 }
1064 #endif
1065
1066 #if defined(__GNUC__)
1067 #define RDATA_ALIGN16 __attribute__ ((aligned(16)))
1068 #define STATIC static
1069 #define INLINE inline
1070 #else
1071 #define RDATA_ALIGN16
1072 #define STATIC static
1073 #define INLINE
1074 #endif
1075
1076 #define U64(x) ((uint64_t *) (x))
1077
1078 #define hp_jitfunc ((v4_random_math_JIT_func)NULL)
1079
1080 STATIC INLINE void xor64(uint64_t *a, const uint64_t b)
1081 {
1082 *a ^= b;
1083 }
1084
1085 #pragma pack(push, 1)
1086 union cn_slow_hash_state
1087 {
1088 union hash_state hs;
1089 struct
1090 {
1091 uint8_t k[64];
1092 uint8_t init[INIT_SIZE_BYTE];
1093 };
1094 };
1095 #pragma pack(pop)
1096
1097 #if defined(__aarch64__) && defined(__ARM_FEATURE_CRYPTO)
1098
1099 /* ARMv8-A optimized with NEON and AES instructions.
1100 * Copied from the x86-64 AES-NI implementation. It has much the same
1101 * characteristics as x86-64: there's no 64x64=128 multiplier for vectors,
1102 * and moving between vector and regular registers stalls the pipeline.
1103 */
1104 #include <arm_neon.h>
1105 #ifndef __APPLE__
1106 #include <sys/auxv.h>
1107 #include <asm/hwcap.h>
1108 #endif
1109
1110 STATIC INLINE int check_aes_hw(void)
1111 {
1112 #ifdef __APPLE__
1113 return 1;
1114 #else
1115 static int supported = -1;
1116
1117 if(supported < 0)
1118 supported = (getauxval(AT_HWCAP) & HWCAP_AES) != 0;
1119 return supported;
1120 #endif
1121 }
1122
1123 #define TOTALBLOCKS (MEMORY / AES_BLOCK_SIZE)
1124
1125 #define state_index(x) (((*((uint64_t *)x) >> 4) & (TOTALBLOCKS - 1)) << 4)
1126 #define __mul() __asm__("mul %0, %1, %2\n\t" : "=r"(lo) : "r"(c[0]), "r"(b[0]) ); \
1127 __asm__("umulh %0, %1, %2\n\t" : "=r"(hi) : "r"(c[0]), "r"(b[0]) );
1128
1129 #define pre_aes() \
1130 j = state_index(a); \
1131 _c = vld1q_u8(&local_hp_state[j]); \
1132 _a = vld1q_u8((const uint8_t *)a); \
1133
1134 #define post_aes() \
1135 VARIANT2_SHUFFLE_ADD_NEON(local_hp_state, j); \
1136 vst1q_u8((uint8_t *)c, _c); \
1137 vst1q_u8(&local_hp_state[j], veorq_u8(_b, _c)); \
1138 VARIANT1_1(&local_hp_state[j]); \
1139 j = state_index(c); \
1140 p = U64(&local_hp_state[j]); \
1141 b[0] = p[0]; b[1] = p[1]; \
1142 VARIANT2_PORTABLE_INTEGER_MATH(b, c); \
1143 VARIANT4_RANDOM_MATH(a, b, r, &_b, &_b1); \
1144 __mul(); \
1145 VARIANT2_2(); \
1146 VARIANT2_SHUFFLE_ADD_NEON(local_hp_state, j); \
1147 a[0] += hi; a[1] += lo; \
1148 p = U64(&local_hp_state[j]); \
1149 p[0] = a[0]; p[1] = a[1]; \
1150 a[0] ^= b[0]; a[1] ^= b[1]; \
1151 VARIANT1_2(p + 1); \
1152 _b1 = _b; \
1153 _b = _c; \
1154
1155
1156 /* Note: this was based on a standard 256bit key schedule but
1157 * it's been shortened since Cryptonight doesn't use the full
1158 * key schedule. Don't try to use this for vanilla AES.
1159 */
1160 static void aes_expand_key(const uint8_t *key, uint8_t *expandedKey) {
1161 static const int rcon[] = {
1162 0x01,0x01,0x01,0x01,
1163 0x0c0f0e0d,0x0c0f0e0d,0x0c0f0e0d,0x0c0f0e0d, // rotate-n-splat
1164 0x1b,0x1b,0x1b,0x1b };
1165 __asm__(
1166 " eor v0.16b,v0.16b,v0.16b\n"
1167 " ld1 {v3.16b},[%0],#16\n"
1168 " ld1 {v1.4s,v2.4s},[%2],#32\n"
1169 " ld1 {v4.16b},[%0]\n"
1170 " mov w2,#5\n"
1171 " st1 {v3.4s},[%1],#16\n"
1172 "\n"
1173 "1:\n"
1174 " tbl v6.16b,{v4.16b},v2.16b\n"
1175 " ext v5.16b,v0.16b,v3.16b,#12\n"
1176 " st1 {v4.4s},[%1],#16\n"
1177 " aese v6.16b,v0.16b\n"
1178 " subs w2,w2,#1\n"
1179 "\n"
1180 " eor v3.16b,v3.16b,v5.16b\n"
1181 " ext v5.16b,v0.16b,v5.16b,#12\n"
1182 " eor v3.16b,v3.16b,v5.16b\n"
1183 " ext v5.16b,v0.16b,v5.16b,#12\n"
1184 " eor v6.16b,v6.16b,v1.16b\n"
1185 " eor v3.16b,v3.16b,v5.16b\n"
1186 " shl v1.16b,v1.16b,#1\n"
1187 " eor v3.16b,v3.16b,v6.16b\n"
1188 " st1 {v3.4s},[%1],#16\n"
1189 " b.eq 2f\n"
1190 "\n"
1191 " dup v6.4s,v3.s[3] // just splat\n"
1192 " ext v5.16b,v0.16b,v4.16b,#12\n"
1193 " aese v6.16b,v0.16b\n"
1194 "\n"
1195 " eor v4.16b,v4.16b,v5.16b\n"
1196 " ext v5.16b,v0.16b,v5.16b,#12\n"
1197 " eor v4.16b,v4.16b,v5.16b\n"
1198 " ext v5.16b,v0.16b,v5.16b,#12\n"
1199 " eor v4.16b,v4.16b,v5.16b\n"
1200 "\n"
1201 " eor v4.16b,v4.16b,v6.16b\n"
1202 " b 1b\n"
1203 "\n"
1204 "2:\n" : : "r"(key), "r"(expandedKey), "r"(rcon));
1205 }
1206
1207 /* An ordinary AES round is a sequence of SubBytes, ShiftRows, MixColumns, AddRoundKey. There
1208 * is also an InitialRound which consists solely of AddRoundKey. The ARM instructions slice
1209 * this sequence differently; the aese instruction performs AddRoundKey, SubBytes, ShiftRows.
1210 * The aesmc instruction does the MixColumns. Since the aese instruction moves the AddRoundKey
1211 * up front, and Cryptonight's hash skips the InitialRound step, we have to kludge it here by
1212 * feeding in a vector of zeros for our first step. Also we have to do our own Xor explicitly
1213 * at the last step, to provide the AddRoundKey that the ARM instructions omit.
1214 */
1215 STATIC INLINE void aes_pseudo_round(const uint8_t *in, uint8_t *out, const uint8_t *expandedKey, int nblocks)
1216 {
1217 const uint8x16_t *k = (const uint8x16_t *)expandedKey, zero = {0};
1218 int i;
1219
1220 for (i=0; i<nblocks; i++)
1221 {
1222 uint8x16_t tmp = vld1q_u8(in + i * AES_BLOCK_SIZE);
1223 tmp = vaeseq_u8(tmp, zero);
1224 tmp = vaesmcq_u8(tmp);
1225 tmp = vaeseq_u8(tmp, k[0]);
1226 tmp = vaesmcq_u8(tmp);
1227 tmp = vaeseq_u8(tmp, k[1]);
1228 tmp = vaesmcq_u8(tmp);
1229 tmp = vaeseq_u8(tmp, k[2]);
1230 tmp = vaesmcq_u8(tmp);
1231 tmp = vaeseq_u8(tmp, k[3]);
1232 tmp = vaesmcq_u8(tmp);
1233 tmp = vaeseq_u8(tmp, k[4]);
1234 tmp = vaesmcq_u8(tmp);
1235 tmp = vaeseq_u8(tmp, k[5]);
1236 tmp = vaesmcq_u8(tmp);
1237 tmp = vaeseq_u8(tmp, k[6]);
1238 tmp = vaesmcq_u8(tmp);
1239 tmp = vaeseq_u8(tmp, k[7]);
1240 tmp = vaesmcq_u8(tmp);
1241 tmp = vaeseq_u8(tmp, k[8]);
1242 tmp = vaesmcq_u8(tmp);
1243 tmp = veorq_u8(tmp, k[9]);
1244 vst1q_u8(out + i * AES_BLOCK_SIZE, tmp);
1245 }
1246 }
1247
1248 STATIC INLINE void aes_pseudo_round_xor(const uint8_t *in, uint8_t *out, const uint8_t *expandedKey, const uint8_t *xor, int nblocks)
1249 {
1250 const uint8x16_t *k = (const uint8x16_t *)expandedKey;
1251 const uint8x16_t *x = (const uint8x16_t *)xor;
1252 int i;
1253
1254 for (i=0; i<nblocks; i++)
1255 {
1256 uint8x16_t tmp = vld1q_u8(in + i * AES_BLOCK_SIZE);
1257 tmp = vaeseq_u8(tmp, x[i]);
1258 tmp = vaesmcq_u8(tmp);
1259 tmp = vaeseq_u8(tmp, k[0]);
1260 tmp = vaesmcq_u8(tmp);
1261 tmp = vaeseq_u8(tmp, k[1]);
1262 tmp = vaesmcq_u8(tmp);
1263 tmp = vaeseq_u8(tmp, k[2]);
1264 tmp = vaesmcq_u8(tmp);
1265 tmp = vaeseq_u8(tmp, k[3]);
1266 tmp = vaesmcq_u8(tmp);
1267 tmp = vaeseq_u8(tmp, k[4]);
1268 tmp = vaesmcq_u8(tmp);
1269 tmp = vaeseq_u8(tmp, k[5]);
1270 tmp = vaesmcq_u8(tmp);
1271 tmp = vaeseq_u8(tmp, k[6]);
1272 tmp = vaesmcq_u8(tmp);
1273 tmp = vaeseq_u8(tmp, k[7]);
1274 tmp = vaesmcq_u8(tmp);
1275 tmp = vaeseq_u8(tmp, k[8]);
1276 tmp = vaesmcq_u8(tmp);
1277 tmp = veorq_u8(tmp, k[9]);
1278 vst1q_u8(out + i * AES_BLOCK_SIZE, tmp);
1279 }
1280 }
1281
1282 #ifdef FORCE_USE_HEAP
1283 STATIC INLINE void* aligned_malloc(size_t size, size_t align)
1284 {
1285 void *result;
1286 #ifdef _MSC_VER
1287 result = _aligned_malloc(size, align);
1288 #else
1289 if (posix_memalign(&result, align, size)) result = NULL;
1290 #endif
1291 return result;
1292 }
1293
1294 STATIC INLINE void aligned_free(void *ptr)
1295 {
1296 #ifdef _MSC_VER
1297 _aligned_free(ptr);
1298 #else
1299 free(ptr);
1300 #endif
1301 }
1302 #endif /* FORCE_USE_HEAP */
1303
1304 STATIC INLINE void xor_blocks(uint8_t* a, const uint8_t* b)
1305 {
1306 U64(a)[0] ^= U64(b)[0];
1307 U64(a)[1] ^= U64(b)[1];
1308 }
1309
1310 void cn_slow_hash(const void *data, size_t length, char *hash, int variant, int prehashed, uint64_t height)
1311 {
1312 RDATA_ALIGN16 uint8_t expandedKey[240];
1313
1314 uint8_t *local_hp_state;
1315 uint8_t text[INIT_SIZE_BYTE];
1316 RDATA_ALIGN16 uint64_t a[2];
1317 RDATA_ALIGN16 uint64_t b[4];
1318 RDATA_ALIGN16 uint64_t c[2];
1319 union cn_slow_hash_state state;
1320 uint8x16_t _a, _b, _b1, _c, zero = {0};
1321 uint64_t hi, lo;
1322
1323 size_t i, j;
1324 uint64_t *p = NULL;
1325 oaes_ctx *aes_ctx = NULL;
1326 int useAes = !force_software_aes() && check_aes_hw();
1327
1328 static void (*const extra_hashes[4])(const void *, size_t, char *) =
1329 {
1330 hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein
1331 };
1332
1333 // this isn't supposed to happen, but guard against it for now.
1334 if(hp_state == NULL)
1335 cn_slow_hash_allocate_state();
1336
1337 // locals to avoid constant TLS dereferencing
1338 local_hp_state = hp_state;
1339
1340 // locals to avoid constant TLS dereferencing
1341 /* CryptoNight Step 1: Use Keccak1600 to initialize the 'state' (and 'text') buffers from the data. */
1342
1343 if (prehashed) {
1344 memcpy(&state.hs, data, length);
1345 } else {
1346 hash_process(&state.hs, data, length);
1347 }
1348 memcpy(text, state.init, INIT_SIZE_BYTE);
1349
1350 VARIANT1_INIT64();
1351 VARIANT2_INIT64();
1352 VARIANT4_RANDOM_MATH_INIT();
1353
1354 /* CryptoNight Step 2: Iteratively encrypt the results from Keccak to fill
1355 * the 2MB large random access buffer.
1356 */
1357
1358 if(useAes)
1359 {
1360 aes_expand_key(state.hs.b, expandedKey);
1361 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
1362 {
1363 aes_pseudo_round(text, text, expandedKey, INIT_SIZE_BLK);
1364 memcpy(&local_hp_state[i * INIT_SIZE_BYTE], text, INIT_SIZE_BYTE);
1365 }
1366 }
1367 else
1368 {
1369 aes_ctx = (oaes_ctx *) oaes_alloc();
1370 oaes_key_import_data(aes_ctx, state.hs.b, AES_KEY_SIZE);
1371 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
1372 {
1373 for(j = 0; j < INIT_SIZE_BLK; j++)
1374 aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], aes_ctx->key->exp_data);
1375
1376 memcpy(&local_hp_state[i * INIT_SIZE_BYTE], text, INIT_SIZE_BYTE);
1377 }
1378 }
1379
1380 U64(a)[0] = U64(&state.k[0])[0] ^ U64(&state.k[32])[0];
1381 U64(a)[1] = U64(&state.k[0])[1] ^ U64(&state.k[32])[1];
1382 U64(b)[0] = U64(&state.k[16])[0] ^ U64(&state.k[48])[0];
1383 U64(b)[1] = U64(&state.k[16])[1] ^ U64(&state.k[48])[1];
1384
1385 /* CryptoNight Step 3: Bounce randomly 1,048,576 times (1<<20) through the mixing buffer,
1386 * using 524,288 iterations of the following mixing function. Each execution
1387 * performs two reads and writes from the mixing buffer.
1388 */
1389
1390 _b = vld1q_u8((const uint8_t *)b);
1391 _b1 = vld1q_u8(((const uint8_t *)b) + AES_BLOCK_SIZE);
1392
1393 if(useAes)
1394 {
1395 for(i = 0; i < ITER / 2; i++)
1396 {
1397 pre_aes();
1398 _c = vaeseq_u8(_c, zero);
1399 _c = vaesmcq_u8(_c);
1400 _c = veorq_u8(_c, _a);
1401 post_aes();
1402 }
1403 }
1404 else
1405 {
1406 for(i = 0; i < ITER / 2; i++)
1407 {
1408 pre_aes();
1409 aesb_single_round((uint8_t *) &_c, (uint8_t *) &_c, (uint8_t *) &_a);
1410 post_aes();
1411 }
1412
1413 }
1414
1415 /* CryptoNight Step 4: Sequentially pass through the mixing buffer and use 10 rounds
1416 * of AES encryption to mix the random data back into the 'text' buffer. 'text'
1417 * was originally created with the output of Keccak1600. */
1418
1419 memcpy(text, state.init, INIT_SIZE_BYTE);
1420
1421 if(useAes)
1422 {
1423 aes_expand_key(&state.hs.b[32], expandedKey);
1424 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
1425 {
1426 // add the xor to the pseudo round
1427 aes_pseudo_round_xor(text, text, expandedKey, &local_hp_state[i * INIT_SIZE_BYTE], INIT_SIZE_BLK);
1428 }
1429 }
1430 else
1431 {
1432 oaes_key_import_data(aes_ctx, &state.hs.b[32], AES_KEY_SIZE);
1433 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
1434 {
1435 for(j = 0; j < INIT_SIZE_BLK; j++)
1436 {
1437 xor_blocks(&text[j * AES_BLOCK_SIZE], &local_hp_state[i * INIT_SIZE_BYTE + j * AES_BLOCK_SIZE]);
1438 aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], aes_ctx->key->exp_data);
1439 }
1440 }
1441 oaes_free((OAES_CTX **) &aes_ctx);
1442 }
1443
1444 /* CryptoNight Step 5: Apply Keccak to the state again, and then
1445 * use the resulting data to select which of four finalizer
1446 * hash functions to apply to the data (Blake, Groestl, JH, or Skein).
1447 * Use this hash to squeeze the state array down
1448 * to the final 256 bit hash output.
1449 */
1450
1451 memcpy(state.init, text, INIT_SIZE_BYTE);
1452 hash_permutation(&state.hs);
1453 extra_hashes[state.hs.b[0] & 3](&state, 200, hash);
1454 }
1455 #else /* aarch64 && crypto */
1456
1457 // ND: Some minor optimizations for ARMv7 (raspberrry pi 2), effect seems to be ~40-50% faster.
1458 // Needs more work.
1459
1460 #ifdef NO_OPTIMIZED_MULTIPLY_ON_ARM
1461 /* The asm corresponds to this C code */
1462 #define SHORT uint32_t
1463 #define LONG uint64_t
1464
1465 void mul(const uint8_t *ca, const uint8_t *cb, uint8_t *cres) {
1466 const SHORT *aa = (SHORT *)ca;
1467 const SHORT *bb = (SHORT *)cb;
1468 SHORT *res = (SHORT *)cres;
1469 union {
1470 SHORT tmp[8];
1471 LONG ltmp[4];
1472 } t;
1473 LONG A = aa[1];
1474 LONG a = aa[0];
1475 LONG B = bb[1];
1476 LONG b = bb[0];
1477
1478 // Aa * Bb = ab + aB_ + Ab_ + AB__
1479 t.ltmp[0] = a * b;
1480 t.ltmp[1] = a * B;
1481 t.ltmp[2] = A * b;
1482 t.ltmp[3] = A * B;
1483
1484 res[2] = t.tmp[0];
1485 t.ltmp[1] += t.tmp[1];
1486 t.ltmp[1] += t.tmp[4];
1487 t.ltmp[3] += t.tmp[3];
1488 t.ltmp[3] += t.tmp[5];
1489 res[3] = t.tmp[2];
1490 res[0] = t.tmp[6];
1491 res[1] = t.tmp[7];
1492 }
1493 #else // !NO_OPTIMIZED_MULTIPLY_ON_ARM
1494
1495 #ifdef __aarch64__ /* ARM64, no crypto */
1496 #define mul(a, b, c) cn_mul128((const uint64_t *)a, (const uint64_t *)b, (uint64_t *)c)
1497 STATIC void cn_mul128(const uint64_t *a, const uint64_t *b, uint64_t *r)
1498 {
1499 uint64_t lo, hi;
1500 __asm__("mul %0, %1, %2\n\t" : "=r"(lo) : "r"(a[0]), "r"(b[0]) );
1501 __asm__("umulh %0, %1, %2\n\t" : "=r"(hi) : "r"(a[0]), "r"(b[0]) );
1502 r[0] = hi;
1503 r[1] = lo;
1504 }
1505 #else /* ARM32 */
1506 #define mul(a, b, c) cn_mul128((const uint32_t *)a, (const uint32_t *)b, (uint32_t *)c)
1507 STATIC void cn_mul128(const uint32_t *aa, const uint32_t *bb, uint32_t *r)
1508 {
1509 uint32_t t0, t1, t2=0, t3=0;
1510 __asm__ __volatile__(
1511 "umull %[t0], %[t1], %[a], %[b]\n\t"
1512 "str %[t0], %[ll]\n\t"
1513
1514 // accumulating with 0 can never overflow/carry
1515 "eor %[t0], %[t0]\n\t"
1516 "umlal %[t1], %[t0], %[a], %[B]\n\t"
1517
1518 "umlal %[t1], %[t2], %[A], %[b]\n\t"
1519 "str %[t1], %[lh]\n\t"
1520
1521 "umlal %[t0], %[t3], %[A], %[B]\n\t"
1522
1523 // final add may have a carry
1524 "adds %[t0], %[t0], %[t2]\n\t"
1525 "adc %[t1], %[t3], #0\n\t"
1526
1527 "str %[t0], %[hl]\n\t"
1528 "str %[t1], %[hh]\n\t"
1529 : [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"+r"(t2), [t3]"+r"(t3), [hl]"=m"(r[0]), [hh]"=m"(r[1]), [ll]"=m"(r[2]), [lh]"=m"(r[3])
1530 : [A]"r"(aa[1]), [a]"r"(aa[0]), [B]"r"(bb[1]), [b]"r"(bb[0])
1531 : "cc");
1532 }
1533 #endif /* !aarch64 */
1534 #endif // NO_OPTIMIZED_MULTIPLY_ON_ARM
1535
1536 STATIC INLINE void copy_block(uint8_t* dst, const uint8_t* src)
1537 {
1538 memcpy(dst, src, AES_BLOCK_SIZE);
1539 }
1540
1541 STATIC INLINE void sum_half_blocks(uint8_t* a, const uint8_t* b)
1542 {
1543 uint64_t a0, a1, b0, b1;
1544 a0 = U64(a)[0];
1545 a1 = U64(a)[1];
1546 b0 = U64(b)[0];
1547 b1 = U64(b)[1];
1548 a0 += b0;
1549 a1 += b1;
1550 U64(a)[0] = a0;
1551 U64(a)[1] = a1;
1552 }
1553
1554 STATIC INLINE void swap_blocks(uint8_t *a, uint8_t *b)
1555 {
1556 uint64_t t[2];
1557 U64(t)[0] = U64(a)[0];
1558 U64(t)[1] = U64(a)[1];
1559 U64(a)[0] = U64(b)[0];
1560 U64(a)[1] = U64(b)[1];
1561 U64(b)[0] = U64(t)[0];
1562 U64(b)[1] = U64(t)[1];
1563 }
1564
1565 STATIC INLINE void xor_blocks(uint8_t* a, const uint8_t* b)
1566 {
1567 U64(a)[0] ^= U64(b)[0];
1568 U64(a)[1] ^= U64(b)[1];
1569 }
1570
1571 void cn_slow_hash(const void *data, size_t length, char *hash, int variant, int prehashed, uint64_t height)
1572 {
1573 uint8_t text[INIT_SIZE_BYTE];
1574 uint8_t a[AES_BLOCK_SIZE];
1575 uint8_t a1[AES_BLOCK_SIZE];
1576 uint8_t b[AES_BLOCK_SIZE * 2];
1577 uint8_t c[AES_BLOCK_SIZE];
1578 uint8_t c1[AES_BLOCK_SIZE];
1579 uint8_t d[AES_BLOCK_SIZE];
1580 uint8_t aes_key[AES_KEY_SIZE];
1581 RDATA_ALIGN16 uint8_t expandedKey[256];
1582
1583 union cn_slow_hash_state state;
1584
1585 size_t i, j;
1586 uint8_t *p = NULL;
1587 oaes_ctx *aes_ctx;
1588 static void (*const extra_hashes[4])(const void *, size_t, char *) =
1589 {
1590 hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein
1591 };
1592
1593 #ifndef FORCE_USE_HEAP
1594 uint8_t long_state[MEMORY];
1595 #else
1596 uint8_t *long_state = (uint8_t *)malloc(MEMORY);
1597 #endif
1598
1599 if (prehashed) {
1600 memcpy(&state.hs, data, length);
1601 } else {
1602 hash_process(&state.hs, data, length);
1603 }
1604 memcpy(text, state.init, INIT_SIZE_BYTE);
1605
1606 aes_ctx = (oaes_ctx *) oaes_alloc();
1607 oaes_key_import_data(aes_ctx, state.hs.b, AES_KEY_SIZE);
1608
1609 VARIANT1_INIT64();
1610 VARIANT2_INIT64();
1611 VARIANT4_RANDOM_MATH_INIT();
1612
1613 // use aligned data
1614 memcpy(expandedKey, aes_ctx->key->exp_data, aes_ctx->key->exp_data_len);
1615 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
1616 {
1617 for(j = 0; j < INIT_SIZE_BLK; j++)
1618 aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], expandedKey);
1619 memcpy(&long_state[i * INIT_SIZE_BYTE], text, INIT_SIZE_BYTE);
1620 }
1621
1622 U64(a)[0] = U64(&state.k[0])[0] ^ U64(&state.k[32])[0];
1623 U64(a)[1] = U64(&state.k[0])[1] ^ U64(&state.k[32])[1];
1624 U64(b)[0] = U64(&state.k[16])[0] ^ U64(&state.k[48])[0];
1625 U64(b)[1] = U64(&state.k[16])[1] ^ U64(&state.k[48])[1];
1626
1627 for(i = 0; i < ITER / 2; i++)
1628 {
1629 #define MASK ((uint32_t)(((MEMORY / AES_BLOCK_SIZE) - 1) << 4))
1630 #define state_index(x) ((*(uint32_t *) x) & MASK)
1631
1632 // Iteration 1
1633 j = state_index(a);
1634 p = &long_state[j];
1635 aesb_single_round(p, c1, a);
1636
1637 VARIANT2_PORTABLE_SHUFFLE_ADD(c1, a, long_state, j);
1638 copy_block(p, c1);
1639 xor_blocks(p, b);
1640 VARIANT1_1(p);
1641
1642 // Iteration 2
1643 j = state_index(c1);
1644 p = &long_state[j];
1645 copy_block(c, p);
1646
1647 copy_block(a1, a);
1648 VARIANT2_PORTABLE_INTEGER_MATH(c, c1);
1649 VARIANT4_RANDOM_MATH(a1, c, r, b, b + AES_BLOCK_SIZE);
1650 mul(c1, c, d);
1651 VARIANT2_2_PORTABLE();
1652 VARIANT2_PORTABLE_SHUFFLE_ADD(c1, a, long_state, j);
1653 sum_half_blocks(a1, d);
1654 swap_blocks(a1, c);
1655 xor_blocks(a1, c);
1656 VARIANT1_2(U64(c) + 1);
1657 copy_block(p, c);
1658
1659 if (variant >= 2) {
1660 copy_block(b + AES_BLOCK_SIZE, b);
1661 }
1662 copy_block(b, c1);
1663 copy_block(a, a1);
1664 }
1665
1666 memcpy(text, state.init, INIT_SIZE_BYTE);
1667 oaes_key_import_data(aes_ctx, &state.hs.b[32], AES_KEY_SIZE);
1668 memcpy(expandedKey, aes_ctx->key->exp_data, aes_ctx->key->exp_data_len);
1669 for(i = 0; i < MEMORY / INIT_SIZE_BYTE; i++)
1670 {
1671 for(j = 0; j < INIT_SIZE_BLK; j++)
1672 {
1673 xor_blocks(&text[j * AES_BLOCK_SIZE], &long_state[i * INIT_SIZE_BYTE + j * AES_BLOCK_SIZE]);
1674 aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], expandedKey);
1675 }
1676 }
1677
1678 oaes_free((OAES_CTX **) &aes_ctx);
1679 memcpy(state.init, text, INIT_SIZE_BYTE);
1680 hash_permutation(&state.hs);
1681 extra_hashes[state.hs.b[0] & 3](&state, 200, hash);
1682 #ifdef FORCE_USE_HEAP
1683 free(long_state);
1684 #endif
1685 }
1686 #endif /* !aarch64 || !crypto */
1687
1688 #else
1689 // Portable implementation as a fallback
1690
1691 #define hp_jitfunc ((v4_random_math_JIT_func)NULL)
1692
1693 void cn_slow_hash_allocate_state(void)
1694 {
1695 // Do nothing, this is just to maintain compatibility with the upgraded slow-hash.c
1696 return;
1697 }
1698
1699 void cn_slow_hash_free_state(void)
1700 {
1701 // As above
1702 return;
1703 }
1704
1705 static void (*const extra_hashes[4])(const void *, size_t, char *) = {
1706 hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein
1707 };
1708
1709 static size_t e2i(const uint8_t* a, size_t count) { return (SWAP64LE(*((uint64_t*)a)) / AES_BLOCK_SIZE) & (count - 1); }
1710
1711 static void mul(const uint8_t* a, const uint8_t* b, uint8_t* res) {
1712 uint64_t a0, b0;
1713 uint64_t hi, lo;
1714
1715 a0 = SWAP64LE(((uint64_t*)a)[0]);
1716 b0 = SWAP64LE(((uint64_t*)b)[0]);
1717 lo = mul128(a0, b0, &hi);
1718 ((uint64_t*)res)[0] = SWAP64LE(hi);
1719 ((uint64_t*)res)[1] = SWAP64LE(lo);
1720 }
1721
1722 static void sum_half_blocks(uint8_t* a, const uint8_t* b) {
1723 uint64_t a0, a1, b0, b1;
1724
1725 a0 = SWAP64LE(((uint64_t*)a)[0]);
1726 a1 = SWAP64LE(((uint64_t*)a)[1]);
1727 b0 = SWAP64LE(((uint64_t*)b)[0]);
1728 b1 = SWAP64LE(((uint64_t*)b)[1]);
1729 a0 += b0;
1730 a1 += b1;
1731 ((uint64_t*)a)[0] = SWAP64LE(a0);
1732 ((uint64_t*)a)[1] = SWAP64LE(a1);
1733 }
1734 #define U64(x) ((uint64_t *) (x))
1735
1736 static void copy_block(uint8_t* dst, const uint8_t* src) {
1737 memcpy(dst, src, AES_BLOCK_SIZE);
1738 }
1739
1740 static void swap_blocks(uint8_t *a, uint8_t *b){
1741 uint64_t t[2];
1742 U64(t)[0] = U64(a)[0];
1743 U64(t)[1] = U64(a)[1];
1744 U64(a)[0] = U64(b)[0];
1745 U64(a)[1] = U64(b)[1];
1746 U64(b)[0] = U64(t)[0];
1747 U64(b)[1] = U64(t)[1];
1748 }
1749
1750 static void xor_blocks(uint8_t* a, const uint8_t* b) {
1751 size_t i;
1752 for (i = 0; i < AES_BLOCK_SIZE; i++) {
1753 a[i] ^= b[i];
1754 }
1755 }
1756
1757 static void xor64(uint8_t* left, const uint8_t* right)
1758 {
1759 size_t i;
1760 for (i = 0; i < 8; ++i)
1761 {
1762 left[i] ^= right[i];
1763 }
1764 }
1765
1766 #pragma pack(push, 1)
1767 union cn_slow_hash_state {
1768 union hash_state hs;
1769 struct {
1770 uint8_t k[64];
1771 uint8_t init[INIT_SIZE_BYTE];
1772 };
1773 };
1774 #pragma pack(pop)
1775
1776 void cn_slow_hash(const void *data, size_t length, char *hash, int variant, int prehashed, uint64_t height) {
1777 #ifndef FORCE_USE_HEAP
1778 uint8_t long_state[MEMORY];
1779 #else
1780 uint8_t *long_state = (uint8_t *)malloc(MEMORY);
1781 #endif
1782
1783 union cn_slow_hash_state state;
1784 uint8_t text[INIT_SIZE_BYTE];
1785 uint8_t a[AES_BLOCK_SIZE];
1786 uint8_t a1[AES_BLOCK_SIZE];
1787 uint8_t b[AES_BLOCK_SIZE * 2];
1788 uint8_t c1[AES_BLOCK_SIZE];
1789 uint8_t c2[AES_BLOCK_SIZE];
1790 uint8_t d[AES_BLOCK_SIZE];
1791 size_t i, j;
1792 uint8_t aes_key[AES_KEY_SIZE];
1793 oaes_ctx *aes_ctx;
1794
1795 if (prehashed) {
1796 memcpy(&state.hs, data, length);
1797 } else {
1798 hash_process(&state.hs, data, length);
1799 }
1800 memcpy(text, state.init, INIT_SIZE_BYTE);
1801 memcpy(aes_key, state.hs.b, AES_KEY_SIZE);
1802 aes_ctx = (oaes_ctx *) oaes_alloc();
1803
1804 VARIANT1_PORTABLE_INIT();
1805 VARIANT2_PORTABLE_INIT();
1806 VARIANT4_RANDOM_MATH_INIT();
1807
1808 oaes_key_import_data(aes_ctx, aes_key, AES_KEY_SIZE);
1809 for (i = 0; i < MEMORY / INIT_SIZE_BYTE; i++) {
1810 for (j = 0; j < INIT_SIZE_BLK; j++) {
1811 aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], aes_ctx->key->exp_data);
1812 }
1813 memcpy(&long_state[i * INIT_SIZE_BYTE], text, INIT_SIZE_BYTE);
1814 }
1815
1816 for (i = 0; i < AES_BLOCK_SIZE; i++) {
1817 a[i] = state.k[ i] ^ state.k[AES_BLOCK_SIZE * 2 + i];
1818 b[i] = state.k[AES_BLOCK_SIZE + i] ^ state.k[AES_BLOCK_SIZE * 3 + i];
1819 }
1820
1821 for (i = 0; i < ITER / 2; i++) {
1822 /* Dependency chain: address -> read value ------+
1823 * written value <-+ hard function (AES or MUL) <+
1824 * next address <-+
1825 */
1826 /* Iteration 1 */
1827 j = e2i(a, MEMORY / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
1828 copy_block(c1, &long_state[j]);
1829 aesb_single_round(c1, c1, a);
1830 VARIANT2_PORTABLE_SHUFFLE_ADD(c1, a, long_state, j);
1831 copy_block(&long_state[j], c1);
1832 xor_blocks(&long_state[j], b);
1833 assert(j == e2i(a, MEMORY / AES_BLOCK_SIZE) * AES_BLOCK_SIZE);
1834 VARIANT1_1(&long_state[j]);
1835 /* Iteration 2 */
1836 j = e2i(c1, MEMORY / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
1837 copy_block(c2, &long_state[j]);
1838 copy_block(a1, a);
1839 VARIANT2_PORTABLE_INTEGER_MATH(c2, c1);
1840 VARIANT4_RANDOM_MATH(a1, c2, r, b, b + AES_BLOCK_SIZE);
1841 mul(c1, c2, d);
1842 VARIANT2_2_PORTABLE();
1843 VARIANT2_PORTABLE_SHUFFLE_ADD(c1, a, long_state, j);
1844 sum_half_blocks(a1, d);
1845 swap_blocks(a1, c2);
1846 xor_blocks(a1, c2);
1847 VARIANT1_2(c2 + 8);
1848 copy_block(&long_state[j], c2);
1849 if (variant >= 2) {
1850 copy_block(b + AES_BLOCK_SIZE, b);
1851 }
1852 copy_block(b, c1);
1853 copy_block(a, a1);
1854 }
1855
1856 memcpy(text, state.init, INIT_SIZE_BYTE);
1857 oaes_key_import_data(aes_ctx, &state.hs.b[32], AES_KEY_SIZE);
1858 for (i = 0; i < MEMORY / INIT_SIZE_BYTE; i++) {
1859 for (j = 0; j < INIT_SIZE_BLK; j++) {
1860 xor_blocks(&text[j * AES_BLOCK_SIZE], &long_state[i * INIT_SIZE_BYTE + j * AES_BLOCK_SIZE]);
1861 aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], aes_ctx->key->exp_data);
1862 }
1863 }
1864 memcpy(state.init, text, INIT_SIZE_BYTE);
1865 hash_permutation(&state.hs);
1866 /*memcpy(hash, &state, 32);*/
1867 extra_hashes[state.hs.b[0] & 3](&state, 200, hash);
1868 oaes_free((OAES_CTX **) &aes_ctx);
1869
1870 #ifdef FORCE_USE_HEAP
1871 free(long_state);
1872 #endif
1873 }
1874
1875 #endif
1876
1877 void slow_hash_allocate_state(void)
1878 {
1879 cn_slow_hash_allocate_state();
1880 rx_slow_hash_allocate_state();
1881 }
1882
1883 void slow_hash_free_state(void)
1884 {
1885 cn_slow_hash_free_state();
1886 rx_slow_hash_free_state();
1887 }