prime.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. #include "config.h"
  2. #include <stdbool.h>
  3. #include <stddef.h>
  4. #include <stdint.h>
  5. #include <stdio.h>
  6. #include <sys/time.h>
  7. #include <gmp.h>
  8. #include "compat.h"
  9. #include "miner.h"
  10. #define nMaxSieveSize 1000000u
  11. #define nPrimeTableLimit nMaxSieveSize
  12. #define nPrimorialTableLimit 100000u
  13. #define PRIME_COUNT 78498
  14. #define PRIMORIAL_COUNT 9592
  15. static
  16. unsigned vPrimes[PRIME_COUNT];
  17. mpz_t vPrimorials[PRIMORIAL_COUNT];
  18. static
  19. int64_t GetTimeMicros()
  20. {
  21. struct timeval tv;
  22. cgtime(&tv);
  23. return ((int64_t)tv.tv_sec * 1000000) + tv.tv_usec;
  24. }
  25. static
  26. int64_t GetTimeMillis()
  27. {
  28. return GetTimeMicros() / 1000;
  29. }
  30. static
  31. int64_t GetTime()
  32. {
  33. return GetTimeMicros() / 1000000;
  34. }
  35. static
  36. bool error(const char *fmt, ...)
  37. {
  38. puts(fmt); // FIXME
  39. return false;
  40. }
  41. void GeneratePrimeTable()
  42. {
  43. mpz_t bnOne;
  44. mpz_init_set_ui(bnOne, 1);
  45. mpz_t *bnLastPrimorial = &bnOne;
  46. unsigned i = 0;
  47. // Generate prime table using sieve of Eratosthenes
  48. bool vfComposite[nPrimeTableLimit] = {false};
  49. for (unsigned int nFactor = 2; nFactor * nFactor < nPrimeTableLimit; nFactor++)
  50. {
  51. if (vfComposite[nFactor])
  52. continue;
  53. for (unsigned int nComposite = nFactor * nFactor; nComposite < nPrimeTableLimit; nComposite += nFactor)
  54. vfComposite[nComposite] = true;
  55. }
  56. for (unsigned int n = 2; n < nPrimeTableLimit; n++)
  57. if (!vfComposite[n])
  58. {
  59. vPrimes[i] = n;
  60. if (n < nPrimorialTableLimit)
  61. {
  62. mpz_init(vPrimorials[i]);
  63. mpz_mul_ui(vPrimorials[i], *bnLastPrimorial, n);
  64. bnLastPrimorial = &vPrimorials[i];
  65. }
  66. ++i;
  67. }
  68. mpz_clear(bnOne);
  69. applog(LOG_DEBUG, "GeneratePrimeTable() : prime table [1, %d] generated with %lu primes", nPrimeTableLimit, (unsigned long)i);
  70. }
  71. #define nFractionalBits 24
  72. #define TARGET_FRACTIONAL_MASK ((1u << nFractionalBits) - 1)
  73. #define TARGET_LENGTH_MASK (~TARGET_FRACTIONAL_MASK)
  74. // Check Fermat probable primality test (2-PRP): 2 ** (n-1) = 1 (mod n)
  75. // true: n is probable prime
  76. // false: n is composite; set fractional length in the nLength output
  77. static
  78. bool FermatProbablePrimalityTest(mpz_t *n, unsigned int *pnLength)
  79. {
  80. mpz_t a, e, r;
  81. mpz_init_set_ui(a, 2); // base; Fermat witness
  82. mpz_init(e);
  83. mpz_sub_ui(e, *n, 1);
  84. mpz_init(r);
  85. mpz_powm(r, a, e, *n);
  86. mpz_clear(a);
  87. mpz_clear(e);
  88. if (!mpz_cmp_ui(r, 1))
  89. {
  90. mpz_clear(r);
  91. return true;
  92. }
  93. // Failed Fermat test, calculate fractional length
  94. // nFractionalLength = ( (n-r) << nFractionalBits ) / n
  95. mpz_sub(r, *n, r);
  96. mpz_mul_2exp(r, r, nFractionalBits);
  97. mpz_fdiv_q(r, r, *n);
  98. unsigned int nFractionalLength = mpz_get_ui(r);
  99. mpz_clear(r);
  100. if (nFractionalLength >= (1 << nFractionalBits))
  101. return error("FermatProbablePrimalityTest() : fractional assert");
  102. *pnLength = (*pnLength & TARGET_LENGTH_MASK) | nFractionalLength;
  103. return false;
  104. }
  105. static
  106. unsigned int TargetGetLength(unsigned int nBits)
  107. {
  108. return ((nBits & TARGET_LENGTH_MASK) >> nFractionalBits);
  109. }
  110. static
  111. void TargetIncrementLength(unsigned int *pnBits)
  112. {
  113. *pnBits += (1 << nFractionalBits);
  114. }
  115. // Test probable primality of n = 2p +/- 1 based on Euler, Lagrange and Lifchitz
  116. // fSophieGermain:
  117. // true: n = 2p+1, p prime, aka Cunningham Chain of first kind
  118. // false: n = 2p-1, p prime, aka Cunningham Chain of second kind
  119. // Return values
  120. // true: n is probable prime
  121. // false: n is composite; set fractional length in the nLength output
  122. static
  123. bool EulerLagrangeLifchitzPrimalityTest(mpz_t *n, bool fSophieGermain, unsigned int *pnLength)
  124. {
  125. mpz_t a, e, r;
  126. mpz_init_set_ui(a, 2);
  127. mpz_init(e);
  128. mpz_sub_ui(e, *n, 1);
  129. mpz_fdiv_q_2exp(e, e, 1);
  130. mpz_init(r);
  131. mpz_powm(r, a, e, *n);
  132. mpz_clear(a);
  133. mpz_clear(e);
  134. unsigned nMod8 = mpz_fdiv_ui(*n, 8);
  135. bool fPassedTest = false;
  136. if (fSophieGermain && (nMod8 == 7)) // Euler & Lagrange
  137. fPassedTest = !mpz_cmp_ui(r, 1);
  138. else if (nMod8 == (fSophieGermain ? 3 : 5)) // Lifchitz
  139. {
  140. mpz_t mp;
  141. mpz_init_set_ui(mp, 1);
  142. mpz_add(mp, r, mp);
  143. fPassedTest = !mpz_cmp(mp, *n);
  144. mpz_clear(mp);
  145. }
  146. else if ((!fSophieGermain) && (nMod8 == 1)) // LifChitz
  147. fPassedTest = !mpz_cmp_ui(r, 1);
  148. else
  149. {
  150. mpz_clear(r);
  151. return error("EulerLagrangeLifchitzPrimalityTest() : invalid n %% 8 = %d, %s", nMod8, (fSophieGermain? "first kind" : "second kind"));
  152. }
  153. if (fPassedTest)
  154. {
  155. mpz_clear(r);
  156. return true;
  157. }
  158. // Failed test, calculate fractional length
  159. // derive Fermat test remainder
  160. mpz_mul(r, r, r);
  161. mpz_fdiv_r(r, r, *n);
  162. // nFractionalLength = ( (n-r) << nFractionalBits ) / n
  163. mpz_sub(r, *n, r);
  164. mpz_mul_2exp(r, r, nFractionalBits);
  165. mpz_fdiv_q(r, r, *n);
  166. unsigned int nFractionalLength = mpz_get_ui(r);
  167. mpz_clear(r);
  168. if (nFractionalLength >= (1 << nFractionalBits))
  169. return error("EulerLagrangeLifchitzPrimalityTest() : fractional assert");
  170. *pnLength = (*pnLength & TARGET_LENGTH_MASK) | nFractionalLength;
  171. return false;
  172. }
  173. // Test Probable Cunningham Chain for: n
  174. // fSophieGermain:
  175. // true - Test for Cunningham Chain of first kind (n, 2n+1, 4n+3, ...)
  176. // false - Test for Cunningham Chain of second kind (n, 2n-1, 4n-3, ...)
  177. // Return value:
  178. // true - Probable Cunningham Chain found (length at least 2)
  179. // false - Not Cunningham Chain
  180. static
  181. bool ProbableCunninghamChainTest(mpz_t *n, bool fSophieGermain, bool fFermatTest, unsigned int *pnProbableChainLength)
  182. {
  183. #ifdef SUPERDEBUG
  184. printf("ProbableCunninghamChainTest(");
  185. mpz_out_str(stdout, 0x10, *n);
  186. printf(", %d, %d, %u)\n", (int)fSophieGermain, (int)fFermatTest, *pnProbableChainLength);
  187. #endif
  188. *pnProbableChainLength = 0;
  189. mpz_t N;
  190. mpz_init_set(N, *n);
  191. // Fermat test for n first
  192. if (!FermatProbablePrimalityTest(&N, pnProbableChainLength))
  193. {
  194. mpz_clear(N);
  195. return false;
  196. }
  197. #ifdef SUPERDEBUG
  198. printf("N=");
  199. mpz_out_str(stdout, 0x10, N);
  200. printf("\n");
  201. #endif
  202. // Euler-Lagrange-Lifchitz test for the following numbers in chain
  203. while (true)
  204. {
  205. TargetIncrementLength(pnProbableChainLength);
  206. mpz_add(N, N, N);
  207. if (fSophieGermain)
  208. mpz_add_ui(N, N, 1);
  209. else
  210. mpz_sub_ui(N, N, 1);
  211. if (fFermatTest)
  212. {
  213. if (!FermatProbablePrimalityTest(&N, pnProbableChainLength))
  214. break;
  215. }
  216. else
  217. {
  218. #ifdef SUPERDEBUG
  219. if (!fSophieGermain)
  220. {
  221. printf("EulerLagrangeLifchitzPrimalityTest(");
  222. mpz_out_str(stdout, 0x10, N);
  223. printf(", 1, %d)\n", *pnProbableChainLength);
  224. }
  225. #endif
  226. if (!EulerLagrangeLifchitzPrimalityTest(&N, fSophieGermain, pnProbableChainLength))
  227. break;
  228. }
  229. }
  230. mpz_clear(N);
  231. #ifdef SUPERDEBUG
  232. printf("PCCT => %u (%u)\n", TargetGetLength(*pnProbableChainLength), *pnProbableChainLength);
  233. #endif
  234. return (TargetGetLength(*pnProbableChainLength) >= 2);
  235. }
  236. static
  237. unsigned int TargetFromInt(unsigned int nLength)
  238. {
  239. return (nLength << nFractionalBits);
  240. }
  241. // Test probable prime chain for: nOrigin
  242. // Return value:
  243. // true - Probable prime chain found (one of nChainLength meeting target)
  244. // false - prime chain too short (none of nChainLength meeting target)
  245. static
  246. bool ProbablePrimeChainTest(mpz_t *bnPrimeChainOrigin, unsigned int nBits, bool fFermatTest, unsigned int *pnChainLengthCunningham1, unsigned int *pnChainLengthCunningham2, unsigned int *pnChainLengthBiTwin)
  247. {
  248. *pnChainLengthCunningham1 = 0;
  249. *pnChainLengthCunningham2 = 0;
  250. *pnChainLengthBiTwin = 0;
  251. mpz_t mp;
  252. mpz_init(mp);
  253. // Test for Cunningham Chain of first kind
  254. mpz_sub_ui(mp, *bnPrimeChainOrigin, 1);
  255. ProbableCunninghamChainTest(&mp, true, fFermatTest, pnChainLengthCunningham1);
  256. // Test for Cunningham Chain of second kind
  257. mpz_add_ui(mp, *bnPrimeChainOrigin, 1);
  258. ProbableCunninghamChainTest(&mp, false, fFermatTest, pnChainLengthCunningham2);
  259. mpz_clear(mp);
  260. // Figure out BiTwin Chain length
  261. // BiTwin Chain allows a single prime at the end for odd length chain
  262. *pnChainLengthBiTwin = (TargetGetLength(*pnChainLengthCunningham1) > TargetGetLength(*pnChainLengthCunningham2)) ? (*pnChainLengthCunningham2 + TargetFromInt(TargetGetLength(*pnChainLengthCunningham2)+1)) : (*pnChainLengthCunningham1 + TargetFromInt(TargetGetLength(*pnChainLengthCunningham1)));
  263. return (*pnChainLengthCunningham1 >= nBits || *pnChainLengthCunningham2 >= nBits || *pnChainLengthBiTwin >= nBits);
  264. }
  265. struct SieveOfEratosthenes {
  266. bool valid;
  267. unsigned int nSieveSize; // size of the sieve
  268. unsigned int nBits; // target of the prime chain to search for
  269. mpz_t hashBlockHeader; // block header hash
  270. mpz_t bnFixedFactor; // fixed factor to derive the chain
  271. // bitmaps of the sieve, index represents the variable part of multiplier
  272. bool vfCompositeCunningham1[1000000];
  273. bool vfCompositeCunningham2[1000000];
  274. bool vfCompositeBiTwin[1000000];
  275. unsigned int nPrimeSeq; // prime sequence number currently being processed
  276. unsigned int nCandidateMultiplier; // current candidate for power test
  277. };
  278. static
  279. void psieve_reset(struct SieveOfEratosthenes *psieve)
  280. {
  281. mpz_clear(psieve->hashBlockHeader);
  282. mpz_clear(psieve->bnFixedFactor);
  283. psieve->valid = false;
  284. }
  285. static
  286. void psieve_init(struct SieveOfEratosthenes *psieve, unsigned nSieveSize, unsigned nBits, mpz_t *hashBlockHeader, mpz_t *bnFixedMultiplier)
  287. {
  288. assert(!psieve->valid);
  289. *psieve = (struct SieveOfEratosthenes){
  290. .valid = true,
  291. .nSieveSize = nSieveSize,
  292. .nBits = nBits,
  293. };
  294. mpz_init_set(psieve->hashBlockHeader, *hashBlockHeader);
  295. mpz_init(psieve->bnFixedFactor);
  296. mpz_mul(psieve->bnFixedFactor, *bnFixedMultiplier, *hashBlockHeader);
  297. }
  298. // Weave sieve for the next prime in table
  299. // Return values:
  300. // True - weaved another prime; nComposite - number of composites removed
  301. // False - sieve already completed
  302. static
  303. bool psieve_Weave(struct SieveOfEratosthenes *psieve)
  304. {
  305. unsigned nPrime = vPrimes[psieve->nPrimeSeq];
  306. if (psieve->nPrimeSeq >= PRIME_COUNT || nPrime >= psieve->nSieveSize)
  307. return false; // sieve has been completed
  308. if (mpz_fdiv_ui(psieve->bnFixedFactor, nPrime) == 0)
  309. {
  310. // Nothing in the sieve is divisible by this prime
  311. ++psieve->nPrimeSeq;
  312. return true;
  313. }
  314. // Find the modulo inverse of fixed factor
  315. mpz_t bnFixedInverse, p;
  316. mpz_init(bnFixedInverse);
  317. mpz_init_set_ui(p, nPrime);
  318. if (!mpz_invert(bnFixedInverse, psieve->bnFixedFactor, p))
  319. {
  320. mpz_clear(p);
  321. mpz_clear(bnFixedInverse);
  322. return error("CSieveOfEratosthenes::Weave(): BN_mod_inverse of fixed factor failed for prime #%u=%u", psieve->nPrimeSeq, nPrime);
  323. }
  324. mpz_t bnTwo, bnTwoInverse;
  325. mpz_init_set_ui(bnTwo, 2);
  326. mpz_init(bnTwoInverse);
  327. if (!mpz_invert(bnTwoInverse, bnTwo, p))
  328. {
  329. mpz_clear(bnTwoInverse);
  330. mpz_clear(bnTwo);
  331. mpz_clear(p);
  332. mpz_clear(bnFixedInverse);
  333. return error("CSieveOfEratosthenes::Weave(): BN_mod_inverse of 2 failed for prime #%u=%u", psieve->nPrimeSeq, nPrime);
  334. }
  335. mpz_clear(bnTwo);
  336. mpz_clear(p);
  337. mpz_t mp;
  338. mpz_init(mp);
  339. // Weave the sieve for the prime
  340. unsigned int nChainLength = TargetGetLength(psieve->nBits);
  341. for (unsigned int nBiTwinSeq = 0; nBiTwinSeq < 2 * nChainLength; nBiTwinSeq++)
  342. {
  343. // Find the first number that's divisible by this prime
  344. int nDelta = ((nBiTwinSeq % 2 == 0) ? (-1) : 1);
  345. mpz_mul_ui(mp, bnFixedInverse, nPrime - nDelta);
  346. unsigned int nSolvedMultiplier = mpz_fdiv_ui(mp, nPrime);
  347. if (nBiTwinSeq % 2 == 1)
  348. mpz_mul(bnFixedInverse, bnFixedInverse, bnTwoInverse); // for next number in chain
  349. if (nBiTwinSeq < nChainLength)
  350. for (unsigned int nVariableMultiplier = nSolvedMultiplier; nVariableMultiplier < psieve->nSieveSize; nVariableMultiplier += nPrime)
  351. psieve->vfCompositeBiTwin[nVariableMultiplier] = true;
  352. if (((nBiTwinSeq & 1u) == 0))
  353. for (unsigned int nVariableMultiplier = nSolvedMultiplier; nVariableMultiplier < psieve->nSieveSize; nVariableMultiplier += nPrime)
  354. psieve->vfCompositeCunningham1[nVariableMultiplier] = true;
  355. if (((nBiTwinSeq & 1u) == 1u))
  356. for (unsigned int nVariableMultiplier = nSolvedMultiplier; nVariableMultiplier < psieve->nSieveSize; nVariableMultiplier += nPrime)
  357. psieve->vfCompositeCunningham2[nVariableMultiplier] = true;
  358. }
  359. mpz_clear(mp);
  360. mpz_clear(bnTwoInverse);
  361. mpz_clear(bnFixedInverse);
  362. ++psieve->nPrimeSeq;
  363. return true;
  364. }
  365. static
  366. bool psieve_GetNextCandidateMultiplier(struct SieveOfEratosthenes *psieve, unsigned int *pnVariableMultiplier)
  367. {
  368. while (true)
  369. {
  370. psieve->nCandidateMultiplier++;
  371. if (psieve->nCandidateMultiplier >= psieve->nSieveSize)
  372. {
  373. psieve->nCandidateMultiplier = 0;
  374. return false;
  375. }
  376. if (!psieve->vfCompositeCunningham1[psieve->nCandidateMultiplier] ||
  377. !psieve->vfCompositeCunningham2[psieve->nCandidateMultiplier] ||
  378. !psieve->vfCompositeBiTwin[psieve->nCandidateMultiplier])
  379. {
  380. *pnVariableMultiplier = psieve->nCandidateMultiplier;
  381. return true;
  382. }
  383. }
  384. }
  385. // Get total number of candidates for power test
  386. static
  387. unsigned int psieve_GetCandidateCount(struct SieveOfEratosthenes *psieve)
  388. {
  389. unsigned int nCandidates = 0;
  390. for (unsigned int nMultiplier = 0; nMultiplier < psieve->nSieveSize; nMultiplier++)
  391. {
  392. if (!psieve->vfCompositeCunningham1[nMultiplier] || !psieve->vfCompositeCunningham2[nMultiplier] || !psieve->vfCompositeBiTwin[nMultiplier])
  393. nCandidates++;
  394. }
  395. return nCandidates;
  396. }
  397. // Mine probable prime chain of form: n = h * p# +/- 1
  398. bool MineProbablePrimeChain(struct SieveOfEratosthenes *psieve, const uint8_t *header, mpz_t *hash, mpz_t *bnFixedMultiplier, bool *pfNewBlock, unsigned *pnTriedMultiplier, unsigned *pnProbableChainLength, unsigned *pnTests, unsigned *pnPrimesHit, struct work *work)
  399. {
  400. const uint32_t *pnbits = (void*)&header[72];
  401. *pnProbableChainLength = 0;
  402. *pnTests = 0;
  403. *pnPrimesHit = 0;
  404. if (*pfNewBlock && psieve->valid)
  405. {
  406. // Must rebuild the sieve
  407. psieve_reset(psieve);
  408. }
  409. *pfNewBlock = false;
  410. int64_t nStart, nCurrent; // microsecond timer
  411. if (!psieve->valid)
  412. {
  413. // Build sieve
  414. nStart = GetTimeMicros();
  415. #ifdef SUPERDEBUG
  416. fprintf(stderr, "psieve_init(?, %u, %08x, ", nMaxSieveSize, *pnbits);
  417. mpz_out_str(stderr, 0x10, *hash);
  418. fprintf(stderr, ", ");
  419. mpz_out_str(stderr, 0x10, *bnFixedMultiplier);
  420. fprintf(stderr, ")\n");
  421. #endif
  422. psieve_init(psieve, nMaxSieveSize, *pnbits, hash, bnFixedMultiplier);
  423. while (psieve_Weave(psieve));
  424. applog(LOG_DEBUG, "MineProbablePrimeChain() : new sieve (%u/%u) ready in %uus", psieve_GetCandidateCount(psieve), nMaxSieveSize, (unsigned int) (GetTimeMicros() - nStart));
  425. }
  426. mpz_t bnChainOrigin;
  427. mpz_init(bnChainOrigin);
  428. nStart = GetTimeMicros();
  429. nCurrent = nStart;
  430. while (nCurrent - nStart < 10000 && nCurrent >= nStart)
  431. {
  432. ++*pnTests;
  433. if (!psieve_GetNextCandidateMultiplier(psieve, pnTriedMultiplier))
  434. {
  435. // power tests completed for the sieve
  436. psieve_reset(psieve);
  437. *pfNewBlock = true; // notify caller to change nonce
  438. mpz_clear(bnChainOrigin);
  439. return false;
  440. }
  441. #ifdef SUPERDEBUG
  442. printf("nTriedMultiplier=%d\n", *pnTriedMultiplier=640150);
  443. #endif
  444. mpz_mul(bnChainOrigin, *hash, *bnFixedMultiplier);
  445. mpz_mul_ui(bnChainOrigin, bnChainOrigin, *pnTriedMultiplier);
  446. unsigned int nChainLengthCunningham1 = 0;
  447. unsigned int nChainLengthCunningham2 = 0;
  448. unsigned int nChainLengthBiTwin = 0;
  449. #ifdef SUPERDEBUG
  450. printf("ProbablePrimeChainTest(bnChainOrigin=");
  451. mpz_out_str(stdout, 0x10, bnChainOrigin);
  452. printf(", nbits=%08lx, false, %d, %d, %d)\n", (unsigned long)*pnbits, nChainLengthCunningham1, nChainLengthCunningham2, nChainLengthBiTwin);
  453. #endif
  454. if (ProbablePrimeChainTest(&bnChainOrigin, *pnbits, false, &nChainLengthCunningham1, &nChainLengthCunningham2, &nChainLengthBiTwin))
  455. {
  456. // bnChainOrigin is not used again, so recycled here for the result
  457. // block.bnPrimeChainMultiplier = *bnFixedMultiplier * *pnTriedMultiplier;
  458. mpz_mul_ui(bnChainOrigin, *bnFixedMultiplier, *pnTriedMultiplier);
  459. size_t exportsz, resultoff;
  460. uint8_t *export = mpz_export(NULL, &exportsz, -1, 1, -1, 0, bnChainOrigin);
  461. assert(exportsz < 250); // FIXME: bitcoin varint
  462. resultoff = 1;
  463. if (export[0] & 0x80)
  464. ++resultoff;
  465. uint8_t *result = malloc(exportsz + resultoff);
  466. result[0] = exportsz + resultoff - 1;
  467. result[1] = '\0';
  468. memcpy(&result[resultoff], export, exportsz);
  469. if (mpz_sgn(bnChainOrigin) < 0)
  470. result[1] |= 0x80;
  471. free(export);
  472. work->sig = result;
  473. work->sigsz = exportsz + resultoff;
  474. char hex[1 + (work->sigsz * 2)];
  475. bin2hex(hex, work->sig, work->sigsz);
  476. applog(LOG_DEBUG, "SIGNATURE: %s\n", hex);
  477. // printf("Probable prime chain found for block=%s!!\n Target: %s\n Length: (%s %s %s)\n", block.GetHash().GetHex().c_str(),
  478. // TargetToString(nbits).c_str(), TargetToString(nChainLengthCunningham1).c_str(), TargetToString(nChainLengthCunningham2).c_str(), TargetToString(nChainLengthBiTwin).c_str());
  479. applog(LOG_DEBUG, "Probable prime chain found for block");
  480. *pnProbableChainLength = nChainLengthCunningham1;
  481. if (*pnProbableChainLength < nChainLengthCunningham2)
  482. *pnProbableChainLength = nChainLengthCunningham2;
  483. if (*pnProbableChainLength < nChainLengthBiTwin)
  484. *pnProbableChainLength = nChainLengthBiTwin;
  485. mpz_clear(bnChainOrigin);
  486. return true;
  487. }
  488. *pnProbableChainLength = nChainLengthCunningham1;
  489. if (*pnProbableChainLength < nChainLengthCunningham2)
  490. *pnProbableChainLength = nChainLengthCunningham2;
  491. if (*pnProbableChainLength < nChainLengthBiTwin)
  492. *pnProbableChainLength = nChainLengthBiTwin;
  493. if(TargetGetLength(*pnProbableChainLength) >= 1)
  494. ++*pnPrimesHit;
  495. nCurrent = GetTimeMicros();
  496. }
  497. mpz_clear(bnChainOrigin);
  498. return false; // stop as timed out
  499. }
  500. // Checks that the high bit is set, and low bit is clear (ie, divisible by 2)
  501. static
  502. bool check_ends(const uint8_t *hash)
  503. {
  504. return (hash[31] & 0x80) && !(hash[0] & 1);
  505. }
  506. static inline
  507. void set_mpz_to_hash(mpz_t *hash, const uint8_t *hashb)
  508. {
  509. mpz_import(*hash, 8, -1, 4, -1, 0, hashb);
  510. }
  511. struct prime_longterms {
  512. unsigned int nPrimorialHashFactor;
  513. int64_t nTimeExpected; // time expected to prime chain (micro-second)
  514. int64_t nTimeExpectedPrev; // time expected to prime chain last time
  515. bool fIncrementPrimorial; // increase or decrease primorial factor
  516. unsigned current_prime;
  517. int64_t nHPSTimerStart;
  518. int64_t nLogTime;
  519. int64_t nPrimeCounter;
  520. int64_t nTestCounter;
  521. };
  522. static
  523. struct prime_longterms *get_prime_longterms()
  524. {
  525. struct bfgtls_data *bfgtls = get_bfgtls();
  526. struct prime_longterms *pl = bfgtls->prime_longterms;
  527. if (unlikely(!pl))
  528. {
  529. pl = bfgtls->prime_longterms = malloc(sizeof(*pl));
  530. *pl = (struct prime_longterms){
  531. .nPrimorialHashFactor = 7,
  532. .fIncrementPrimorial = true,
  533. .current_prime = 3, // index 3 is prime number 7
  534. .nHPSTimerStart = GetTimeMillis(),
  535. };
  536. }
  537. return pl;
  538. }
  539. bool prime(uint8_t *header, struct work *work)
  540. {
  541. struct prime_longterms *pl = get_prime_longterms();
  542. bool rv = false;
  543. uint32_t *nonce = (void*)(&header[76]);
  544. unsigned char hashb[32];
  545. mpz_t hash, bnPrimeMin;
  546. mpz_init(hash);
  547. mpz_init_set_ui(bnPrimeMin, 1);
  548. mpz_mul_2exp(bnPrimeMin, bnPrimeMin, 255);
  549. bool fNewBlock = true;
  550. unsigned int nTriedMultiplier = 0;
  551. struct SieveOfEratosthenes sieve = {
  552. .valid = false,
  553. };
  554. const unsigned nHashFactor = 210;
  555. // a valid header must hash to have the MSB set, and a multiple of nHashFactor
  556. while (true)
  557. {
  558. gen_hash(header, hashb, 80);
  559. if (check_ends(hashb))
  560. {
  561. set_mpz_to_hash(&hash, hashb);
  562. if (!mpz_fdiv_ui(hash, 105))
  563. break;
  564. }
  565. if (unlikely(*nonce == 0xffffffff))
  566. {
  567. mpz_clear(hash);
  568. mpz_clear(bnPrimeMin);
  569. return false;
  570. }
  571. ++*nonce;
  572. }
  573. {
  574. char hex[9];
  575. bin2hex(hex, nonce, 4);
  576. applog(LOG_DEBUG, "Pass 1 found: %s", hex);
  577. }
  578. // primorial fixed multiplier
  579. mpz_t bnPrimorial;
  580. mpz_init(bnPrimorial);
  581. unsigned int nRoundTests = 0;
  582. unsigned int nRoundPrimesHit = 0;
  583. int64_t nPrimeTimerStart = GetTimeMicros();
  584. if (pl->nTimeExpected > pl->nTimeExpectedPrev)
  585. pl->fIncrementPrimorial = !pl->fIncrementPrimorial;
  586. pl->nTimeExpectedPrev = pl->nTimeExpected;
  587. // dynamic adjustment of primorial multiplier
  588. if (pl->fIncrementPrimorial)
  589. {
  590. ++pl->current_prime;
  591. if (pl->current_prime >= PRIMORIAL_COUNT)
  592. quit(1, "primorial increment overflow");
  593. }
  594. else if (vPrimes[pl->current_prime] > pl->nPrimorialHashFactor)
  595. {
  596. if (!pl->current_prime)
  597. quit(1, "primorial decrement overflow");
  598. --pl->current_prime;
  599. }
  600. mpz_set(bnPrimorial, vPrimorials[pl->current_prime]);
  601. while (true)
  602. {
  603. unsigned int nTests = 0;
  604. unsigned int nPrimesHit = 0;
  605. mpz_t bnMultiplierMin;
  606. // bnMultiplierMin = bnPrimeMin * nHashFactor / hash + 1
  607. mpz_init(bnMultiplierMin);
  608. mpz_mul_ui(bnMultiplierMin, bnPrimeMin, nHashFactor);
  609. mpz_fdiv_q(bnMultiplierMin, bnMultiplierMin, hash);
  610. mpz_add_ui(bnMultiplierMin, bnMultiplierMin, 1);
  611. while (mpz_cmp(bnPrimorial, bnMultiplierMin) < 0)
  612. {
  613. ++pl->current_prime;
  614. if (pl->current_prime >= PRIMORIAL_COUNT)
  615. quit(1, "primorial minimum overflow");
  616. mpz_set(bnPrimorial, vPrimorials[pl->current_prime]);
  617. }
  618. mpz_clear(bnMultiplierMin);
  619. mpz_t bnFixedMultiplier;
  620. mpz_init(bnFixedMultiplier);
  621. // bnFixedMultiplier = (bnPrimorial > nHashFactor) ? (bnPrimorial / nHashFactor) : 1
  622. if (mpz_cmp_ui(bnPrimorial, nHashFactor) > 0)
  623. {
  624. mpz_t bnHashFactor;
  625. mpz_init_set_ui(bnHashFactor, nHashFactor);
  626. mpz_fdiv_q(bnFixedMultiplier, bnPrimorial, bnHashFactor);
  627. mpz_clear(bnHashFactor);
  628. }
  629. else
  630. mpz_set_ui(bnFixedMultiplier, 1);
  631. #ifdef SUPERDEBUG
  632. fprintf(stderr,"bnFixedMultiplier=");
  633. mpz_out_str(stderr, 0x10, bnFixedMultiplier);
  634. fprintf(stderr, " nPrimorialMultiplier=%u nTriedMultiplier=%u\n", vPrimes[pl->current_prime], nTriedMultiplier);
  635. #endif
  636. // mine for prime chain
  637. unsigned int nProbableChainLength;
  638. if (MineProbablePrimeChain(&sieve, header, &hash, &bnFixedMultiplier, &fNewBlock, &nTriedMultiplier, &nProbableChainLength, &nTests, &nPrimesHit, work))
  639. {
  640. // TODO CheckWork(pblock, *pwalletMain, reservekey);
  641. mpz_clear(bnFixedMultiplier);
  642. rv = true;
  643. break;
  644. }
  645. mpz_clear(bnFixedMultiplier);
  646. nRoundTests += nTests;
  647. nRoundPrimesHit += nPrimesHit;
  648. // Meter primes/sec
  649. if (pl->nHPSTimerStart == 0)
  650. {
  651. pl->nHPSTimerStart = GetTimeMillis();
  652. pl->nPrimeCounter = 0;
  653. pl->nTestCounter = 0;
  654. }
  655. else
  656. {
  657. pl->nPrimeCounter += nPrimesHit;
  658. pl->nTestCounter += nTests;
  659. }
  660. if (GetTimeMillis() - pl->nHPSTimerStart > 60000)
  661. {
  662. double dPrimesPerMinute = 60000.0 * pl->nPrimeCounter / (GetTimeMillis() - pl->nHPSTimerStart);
  663. double dPrimesPerSec = dPrimesPerMinute / 60.0;
  664. double dTestsPerMinute = 60000.0 * pl->nTestCounter / (GetTimeMillis() - pl->nHPSTimerStart);
  665. pl->nHPSTimerStart = GetTimeMillis();
  666. pl->nPrimeCounter = 0;
  667. pl->nTestCounter = 0;
  668. if (GetTime() - pl->nLogTime > 60)
  669. {
  670. pl->nLogTime = GetTime();
  671. applog(LOG_NOTICE, "primemeter %9.0f prime/h %9.0f test/h %5dpps", dPrimesPerMinute * 60.0, dTestsPerMinute * 60.0, (int)dPrimesPerSec);
  672. }
  673. }
  674. // Check for stop or if block needs to be rebuilt
  675. // TODO
  676. // boost::this_thread::interruption_point();
  677. // if (vNodes.empty())
  678. // break;
  679. if (fNewBlock /*|| pblock->nNonce >= 0xffff0000*/)
  680. break;
  681. // if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
  682. // break;
  683. // if (pindexPrev != pindexBest)
  684. // break;
  685. }
  686. mpz_clear(bnPrimorial);
  687. // Primecoin: estimate time to block
  688. pl->nTimeExpected = (GetTimeMicros() - nPrimeTimerStart) / max(1u, nRoundTests);
  689. pl->nTimeExpected = pl->nTimeExpected * max(1u, nRoundTests) / max(1u, nRoundPrimesHit);
  690. //TODO
  691. // for (unsigned int n = 1; n < TargetGetLength(pblock->nBits); n++)
  692. // nTimeExpected = nTimeExpected * max(1u, nRoundTests) * 3 / max(1u, nRoundPrimesHit);
  693. applog(LOG_DEBUG, "PrimecoinMiner() : Round primorial=%u tests=%u primes=%u expected=%us", vPrimes[pl->current_prime], nRoundTests, nRoundPrimesHit, (unsigned int)(pl->nTimeExpected/1000000));
  694. mpz_clear(hash);
  695. mpz_clear(bnPrimeMin);
  696. return rv;
  697. }
  698. #if 0
  699. void pmain()
  700. {
  701. setbuf(stderr, NULL);
  702. setbuf(stdout, NULL);
  703. GeneratePrimeTable();
  704. unsigned char array[80] = {
  705. 0x02,0x00,0x00,0x00,
  706. 0x59,0xf7,0x56,0x1c,0x21,0x25,0xc1,0xad,0x0d,0xee,0xbd,0x05,0xb8,0x41,0x38,0xab,
  707. 0x2e,0xfb,0x65,0x40,0xc8,0xc7,0xa3,0xef,0x90,0x3d,0x75,0x8c,0x03,0x1c,0x7a,0xcc,
  708. 0x8d,0x27,0x4d,0xeb,0x7b,0x6a,0xf8,0xe0,0x44,0x2d,0x7c,0xf6,0xb9,0x71,0x12,0xd8,
  709. 0x61,0x60,0x5b,0x1f,0xa5,0xa3,0xf7,0x4f,0x61,0xe3,0x59,0x67,0x03,0xc2,0xfb,0x56,
  710. 0xed,0x78,0xdb,0x51,
  711. 0xd5,0xbe,0x38,0x07,
  712. 0xe8,0x02,0x00,0x00,
  713. };
  714. prime(array);
  715. }
  716. #endif
  717. bool scanhash_prime(struct thr_info *thr, const unsigned char *pmidstate, unsigned char *pdata, unsigned char *phash1, unsigned char *phash, const unsigned char *ptarget, uint32_t max_nonce, uint32_t *last_nonce, uint32_t nonce)
  718. {
  719. struct work *work = (struct work *)(&pmidstate[-offsetof(struct work, midstate)]);
  720. unsigned char header[80];
  721. swap32yes(header, pdata, 80 / 4);
  722. #if 0
  723. memcpy(header,(unsigned char[80]){
  724. 0x02,0x00,0x00,0x00,
  725. 0x59,0xf7,0x56,0x1c,0x21,0x25,0xc1,0xad,0x0d,0xee,0xbd,0x05,0xb8,0x41,0x38,0xab,
  726. 0x2e,0xfb,0x65,0x40,0xc8,0xc7,0xa3,0xef,0x90,0x3d,0x75,0x8c,0x03,0x1c,0x7a,0xcc,
  727. 0x8d,0x27,0x4d,0xeb,0x7b,0x6a,0xf8,0xe0,0x44,0x2d,0x7c,0xf6,0xb9,0x71,0x12,0xd8,
  728. 0x61,0x60,0x5b,0x1f,0xa5,0xa3,0xf7,0x4f,0x61,0xe3,0x59,0x67,0x03,0xc2,0xfb,0x56,
  729. 0xed,0x78,0xdb,0x51,
  730. 0xd5,0xbe,0x38,0x07,
  731. 0xe8,0x02,0x00,0x00,
  732. },80);
  733. #endif
  734. bool rv = prime(header, work);
  735. swap32yes(pdata, header, 80 / 4);
  736. return rv;
  737. }