Merge pull request #187 from fsb4000/Qt
[novacoin.git] / src / scrypt.cpp
1 #include <stdlib.h>
2
3 #include "scrypt.h"
4 #include "pbkdf2.h"
5
6 #include "util.h"
7 #include "net.h"
8
9 #ifdef USE_SSE2
10 #ifdef _MSC_VER
11 // MSVC 64bit is unable to use inline asm
12 #include <intrin.h>
13 #else
14 // GCC Linux or i686-w64-mingw32
15 #include <cpuid.h>
16 #endif
17 #endif
18
19 extern "C" void scrypt_core(uint32_t *X, uint32_t *V);
20 #ifdef USE_SSE2
21 extern  uint256 scrypt_blockhash__sse2(const uint8_t* input);
22 #endif
23 /* cpu and memory intensive function to transform a 80 byte buffer into a 32 byte output
24    scratchpad size needs to be at least 63 + (128 * r * p) + (256 * r + 64) + (128 * r * N) bytes
25    r = 1, p = 1, N = 1024
26  */
27
28 uint256 scrypt_blockhash_generic(const uint8_t* input)
29 {
30     uint8_t scratchpad[SCRYPT_BUFFER_SIZE];
31     uint32_t X[32];
32     uint256 result = 0;
33
34     uint32_t *V = (uint32_t *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63));
35
36     PBKDF2_SHA256(input, 80, input, 80, 1, (uint8_t *)X, 128);
37     scrypt_core(X, V);
38     PBKDF2_SHA256(input, 80, (uint8_t *)X, 128, 1, (uint8_t*)&result, 32);
39
40     return result;
41 }
42
43 // By default, set to generic scrypt function. This will prevent crash in case when scrypt_detect_sse2() wasn't called
44 uint256 (*scrypt_blockhash_detected)(const uint8_t* input) = &scrypt_blockhash_generic;
45
46 #ifdef USE_SSE2
47 void scrypt_detect_sse2()
48 {
49     // 32bit x86 Linux or Windows, detect cpuid features
50     unsigned int cpuid_edx=0;
51 #if defined(_MSC_VER)
52      // MSVC
53      int x86cpuid[4];
54      __cpuid(x86cpuid, 1);
55      cpuid_edx = (unsigned int)x86cpuid[3];
56 #else // _MSC_VER
57     // Linux or i686-w64-mingw32 (gcc-4.6.3)
58     unsigned int eax, ebx, ecx;
59     __get_cpuid(1, &eax, &ebx, &ecx, &cpuid_edx);
60 #endif // _MSC_VER
61
62     if (cpuid_edx & 1<<26)
63     {
64         scrypt_blockhash_detected = &scrypt_blockhash__sse2;
65         printf("scrypt: using scrypt-sse2 as detected.\n");
66     }
67     else
68     {
69         scrypt_blockhash_detected = &scrypt_blockhash_generic;
70         printf("scrypt: using scrypt-generic, SSE2 unavailable.\n");
71     }
72 }
73 #endif
74
75 uint256 scrypt_blockhash(const uint8_t* input)
76 {
77     return scrypt_blockhash_detected(input);
78 }