Skip to content

Commit

Permalink
Implement scratchpad generating function
Browse files Browse the repository at this point in the history
  • Loading branch information
shizzard committed Dec 6, 2024
1 parent eef4dc8 commit 9c4edf9
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/randomx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,41 @@ extern "C" {
#endif
}

const unsigned char *randomx_calculate_hash_scratchpad(randomx_vm *machine, const void *input, size_t inputSize, const int randomxProgramCount)
{
assert(machine != nullptr);
assert(inputSize == 0 || input != nullptr);

#ifdef USE_CSR_INTRINSICS
const unsigned int fpstate = _mm_getcsr();
#else
fenv_t fpstate;
fegetenv(&fpstate);
#endif

alignas(16) uint64_t tempHash[8];
int blakeResult = blake2b(tempHash, sizeof(tempHash), input, inputSize, nullptr, 0);
assert(blakeResult == 0);
machine->initScratchpad(&tempHash);
machine->resetRoundingMode();
for (int chain = 0; chain < randomxProgramCount - 1; ++chain) {
machine->run(&tempHash);
blakeResult = blake2b(tempHash, sizeof(tempHash), machine->getRegisterFile(), sizeof(randomx::RegisterFile), nullptr, 0);
assert(blakeResult == 0);
}
machine->run(&tempHash);
unsigned char output[64];
machine->getFinalResult(output, RANDOMX_HASH_SIZE);

#ifdef USE_CSR_INTRINSICS
_mm_setcsr(fpstate);
#else
fesetenv(&fpstate);
#endif

return (const unsigned char*)machine->getScratchpad();
}

void randomx_calculate_hash_first(randomx_vm* machine, const void* input, size_t inputSize) {
blake2b(machine->tempHash, sizeof(machine->tempHash), input, inputSize, nullptr, 0);
machine->initScratchpad(machine->tempHash);
Expand Down
11 changes: 11 additions & 0 deletions src/randomx.h
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,17 @@ RANDOMX_EXPORT void randomx_destroy_vm(randomx_vm *machine);
*/
RANDOMX_EXPORT void randomx_calculate_hash(randomx_vm *machine, const void *input, size_t inputSize, void *output);

/**
* Calculates a RandomX long hash value.
* Long hash is effectively the vm scratchpad taken after finalizing the regular hash.
*
* @param machine is a pointer to a randomx_vm structure. Must not be NULL.
* @param input is a pointer to memory to be hashed. Must not be NULL.
* @param inputSize is the number of bytes to be hashed.
* @param randomxProgramCount a custom number of RandomX iterations.
*/
RANDOMX_EXPORT const unsigned char *randomx_calculate_hash_scratchpad(randomx_vm *machine, const void *input, size_t inputSize, const int randomxProgramCount);

/**
* Set of functions used to calculate multiple RandomX hashes more efficiently.
* randomx_calculate_hash_first will begin a hash calculation.
Expand Down

0 comments on commit 9c4edf9

Please sign in to comment.