api-example2.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "../randomx.h"
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <thread>
  5. int main() {
  6. const char myKey[] = "RandomX example key";
  7. const char myInput[] = "RandomX example input";
  8. char hash[RANDOMX_HASH_SIZE];
  9. randomx_flags flags = randomx_get_flags();
  10. flags |= RANDOMX_FLAG_LARGE_PAGES;
  11. flags |= RANDOMX_FLAG_FULL_MEM;
  12. randomx_cache *myCache = randomx_alloc_cache(flags);
  13. if (myCache == nullptr) {
  14. std::cout << "Cache allocation failed" << std::endl;
  15. return 1;
  16. }
  17. randomx_init_cache(myCache, myKey, sizeof myKey);
  18. randomx_dataset *myDataset = randomx_alloc_dataset(flags);
  19. if (myDataset == nullptr) {
  20. std::cout << "Dataset allocation failed" << std::endl;
  21. return 1;
  22. }
  23. auto datasetItemCount = randomx_dataset_item_count();
  24. std::thread t1(&randomx_init_dataset, myDataset, myCache, 0, datasetItemCount / 2);
  25. std::thread t2(&randomx_init_dataset, myDataset, myCache, datasetItemCount / 2, datasetItemCount - datasetItemCount / 2);
  26. t1.join();
  27. t2.join();
  28. randomx_release_cache(myCache);
  29. randomx_vm *myMachine = randomx_create_vm(flags, nullptr, myDataset);
  30. if (myMachine == nullptr) {
  31. std::cout << "Failed to create a virtual machine" << std::endl;
  32. return 1;
  33. }
  34. randomx_calculate_hash(myMachine, &myInput, sizeof myInput, hash);
  35. randomx_destroy_vm(myMachine);
  36. randomx_release_dataset(myDataset);
  37. for (unsigned i = 0; i < RANDOMX_HASH_SIZE; ++i)
  38. std::cout << std::hex << std::setw(2) << std::setfill('0') << ((int)hash[i] & 0xff);
  39. std::cout << std::endl;
  40. return 0;
  41. }