prime.c 25 KB

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