e7cfbda6647a010c3d23685c17e304e2f59849d7
[novacoin.git] / src / scrypt.cpp
1 #include <stdlib.h>
2 #include <openssl/evp.h>
3
4 #include "scrypt.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 uint256 scrypt_blockhash_generic(const uint8_t* input)
28 {
29     uint8_t scratchpad[SCRYPT_BUFFER_SIZE];
30     uint32_t X[32];
31     uint256 result = 0;
32
33     uint32_t *V = (uint32_t *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63));
34
35     PKCS5_PBKDF2_HMAC((const char*)input, 80, input, 80, 1, EVP_sha256(), 128, (unsigned char *)X);
36     scrypt_core(X, V);
37     PKCS5_PBKDF2_HMAC((const char*)input, 80, (const unsigned char*)X, 128, 1, EVP_sha256(), 32, (unsigned char*)&result);
38
39     return result;
40 }
41
42 // By default, set to generic scrypt function. This will prevent crash in case when scrypt_detect_sse2() wasn't called
43 uint256 (*scrypt_blockhash_detected)(const uint8_t* input) = &scrypt_blockhash_generic;
44
45 #ifdef USE_SSE2
46 void scrypt_detect_sse2()
47 {
48     // 32bit x86 Linux or Windows, detect cpuid features
49     unsigned int cpuid_edx=0;
50 #if defined(_MSC_VER)
51      // MSVC
52      int x86cpuid[4];
53      __cpuid(x86cpuid, 1);
54      cpuid_edx = (unsigned int)x86cpuid[3];
55 #else // _MSC_VER
56     // Linux or i686-w64-mingw32 (gcc-4.6.3)
57     unsigned int eax, ebx, ecx;
58     __get_cpuid(1, &eax, &ebx, &ecx, &cpuid_edx);
59 #endif // _MSC_VER
60
61     if (cpuid_edx & 1<<26)
62     {
63         scrypt_blockhash_detected = &scrypt_blockhash__sse2;
64         printf("scrypt: using scrypt-sse2 as detected.\n");
65     }
66     else
67     {
68         scrypt_blockhash_detected = &scrypt_blockhash_generic;
69         printf("scrypt: using scrypt-generic, SSE2 unavailable.\n");
70     }
71 }
72 #endif
73
74 uint256 scrypt_blockhash(const uint8_t* input)
75 {
76     return scrypt_blockhash_detected(input);
77 }