squareHash.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. Copyright (c) 2019 tevador
  3. This file is part of RandomX.
  4. RandomX is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. RandomX is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with RandomX. If not, see<http://www.gnu.org/licenses/>.
  14. */
  15. /*
  16. Based on the original idea by SChernykh:
  17. https://github.com/SChernykh/xmr-stak-cpu/issues/1#issuecomment-414336613
  18. */
  19. #include <stdint.h>
  20. #if !defined(_M_X64) && !defined(__x86_64__)
  21. typedef struct {
  22. uint64_t lo;
  23. uint64_t hi;
  24. } uint128_t;
  25. #define LO(x) ((x)&0xffffffff)
  26. #define HI(x) ((x)>>32)
  27. static inline uint128_t square128(uint64_t x) {
  28. uint64_t xh = HI(x), xl = LO(x);
  29. uint64_t xll = xl * xl;
  30. uint64_t xlh = xl * xh;
  31. uint64_t xhh = xh * xh;
  32. uint64_t m1 = 2 * LO(xlh) + HI(xll);
  33. uint64_t m2 = 2 * HI(xlh) + LO(xhh) + HI(m1);
  34. uint64_t m3 = HI(xhh) + HI(m2);
  35. uint128_t x2;
  36. x2.lo = (m1 << 32) + LO(xll);
  37. x2.hi = (m3 << 32) + LO(m2);
  38. return x2;
  39. }
  40. #undef LO(x)
  41. #undef HI(x)
  42. inline uint64_t squareHash(uint64_t x) {
  43. x += 1613783669344650115;
  44. for (int i = 0; i < 42; ++i) {
  45. uint128_t x2 = square128(x);
  46. x = x2.lo - x2.hi;
  47. }
  48. return x;
  49. }
  50. #else
  51. #if defined(__cplusplus)
  52. extern "C" {
  53. #endif
  54. uint64_t squareHash(uint64_t);
  55. #if defined(__cplusplus)
  56. }
  57. #endif
  58. #endif