prime.c 30 KB

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