forked from hg5fm/jhPrimeminer
-
Notifications
You must be signed in to change notification settings - Fork 10
/
prime.cpp
1735 lines (1520 loc) · 59.2 KB
/
prime.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013 Primecoin developers
// Distributed under conditional MIT/X11 software license,
// see the accompanying file COPYING
#include "global.h"
#include <bitset>
#include <time.h>
#include <set>
#include <algorithm>
// Prime Table
//std::vector<unsigned int> vPrimes;
//uint32* vPrimes;
uint32* vPrimesTwoInverse;
uint32 vPrimesSize = 0;
__declspec( thread ) BN_CTX* pctx = NULL;
// changed to return the ticks since reboot
// doesnt need to be the correct time, just a more or less random input value
uint64 GetTimeMicros()
{
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return (uint64)t.QuadPart;
}
std::vector<unsigned int> vPrimes;
unsigned int nSieveExtensions = nDefaultSieveExtensions;
static unsigned int int_invert(unsigned int a, unsigned int nPrime);
void GeneratePrimeTable(unsigned int nSieveSize)
{
const unsigned int nPrimeTableLimit = nSieveSize ;
vPrimes.clear();
// Generate prime table using sieve of Eratosthenes
std::vector<bool> vfComposite (nPrimeTableLimit, false);
for (unsigned int nFactor = 2; nFactor * nFactor < nPrimeTableLimit; nFactor++)
{
if (vfComposite[nFactor])
continue;
for (unsigned int nComposite = nFactor * nFactor; nComposite < nPrimeTableLimit; nComposite += nFactor)
vfComposite[nComposite] = true;
}
for (unsigned int n = 2; n < nPrimeTableLimit; n++)
if (!vfComposite[n])
vPrimes.push_back(n);
printf("GeneratePrimeTable() : prime table [1, %d] generated with %lu primes\n", nPrimeTableLimit, vPrimes.size());
vPrimesSize = vPrimes.size();
}
// Get next prime number of p
bool PrimeTableGetNextPrime(unsigned int& p)
{
for(uint32 i=0; i<vPrimesSize; i++)
{
unsigned int nPrime = vPrimes[i];
if ( nPrime > p)
{
p = nPrime;
return true;
}
}
return false;
}
// Get previous prime number of p
bool PrimeTableGetPreviousPrime(unsigned int& p)
{
uint32 nPrevPrime = 0;
for(uint32 i=0; i<vPrimesSize; i++)
{
if (vPrimes[i] >= p)
break;
nPrevPrime = vPrimes[i];
}
if (nPrevPrime)
{
p = nPrevPrime;
return true;
}
return false;
}
// Compute Primorial number p#
void Primorial(unsigned int p, CBigNum& bnPrimorial)
{
bnPrimorial = 1;
for(uint32 i=0; i<vPrimesSize; i++)
{
unsigned int nPrime = vPrimes[i];
if (nPrime > p) break;
bnPrimorial *= nPrime;
}
}
// Compute Primorial number p#
void Primorial(unsigned int p, mpz_class& mpzPrimorial)
{
mpzPrimorial = 1;
//BOOST_FOREACH(unsigned int nPrime, vPrimes)
//for(uint32 i=0; i<vPrimes.size(); i++)
for(uint32 i=0; i<vPrimesSize; i++)
{
unsigned int nPrime = vPrimes[i];
if (nPrime > p) break;
mpzPrimorial *= nPrime;
}
}
// Compute Primorial number p#
// Fast 32-bit version assuming that p <= 23
unsigned int PrimorialFast(unsigned int p)
{
unsigned int nPrimorial = 1;
for(uint32 i=0; i<vPrimesSize; i++)
{
unsigned int nPrime = vPrimes[i];
if (nPrime > p) break;
nPrimorial *= nPrime;
}
return nPrimorial;
}
// Compute first primorial number greater than or equal to pn
void PrimorialAt(mpz_class& bn, mpz_class& mpzPrimorial)
{
mpzPrimorial = 1;
//BOOST_FOREACH(unsigned int nPrime, vPrimes)
//for(uint32 i=0; i<vPrimes.size(); i++)
for(uint32 i=0; i<vPrimesSize; i++)
{
unsigned int nPrime = vPrimes[i];
mpzPrimorial *= nPrime;
if (mpzPrimorial >= bn)
return;
}
}
// Check Fermat probable primality test (2-PRP): 2 ** (n-1) = 1 (mod n)
// true: n is probable prime
// false: n is composite; set fractional length in the nLength output
static bool FermatProbablePrimalityTest(const CBigNum& n, unsigned int& nLength)
{
//CBigNum a = 2; // base; Fermat witness
CBigNum e = n - 1;
CBigNum r;
BN_mod_exp(&r, &bnTwo, &e, &n, pctx);
if (r == 1)
return true;
// Failed Fermat test, calculate fractional length
unsigned int nFractionalLength = (((n-r) << nFractionalBits) / n).getuint();
if (nFractionalLength >= (1 << nFractionalBits))
return error("FermatProbablePrimalityTest() : fractional assert");
nLength = (nLength & TARGET_LENGTH_MASK) | nFractionalLength;
return false;
}
// Check Fermat probable primality test (2-PRP): 2 ** (n-1) = 1 (mod n)
// true: n is probable prime
// false: n is composite; set fractional length in the nLength output
static bool FermatProbablePrimalityTest(const mpz_class& n, unsigned int& nLength)
{
// Faster GMP version
mpz_t mpzN;
mpz_t mpzE;
mpz_t mpzR;
mpz_init_set(mpzN, n.get_mpz_t());
mpz_init(mpzE);
mpz_sub_ui(mpzE, mpzN, 1);
mpz_init(mpzR);
mpz_powm(mpzR, mpzTwo.get_mpz_t(), mpzE, mpzN);
if (mpz_cmp_ui(mpzR, 1) == 0) {
mpz_clear(mpzN);
mpz_clear(mpzE);
mpz_clear(mpzR);
return true;
}
// Failed Fermat test, calculate fractional length
mpz_sub(mpzE, mpzN, mpzR);
mpz_mul_2exp(mpzR, mpzE, nFractionalBits);
mpz_tdiv_q(mpzE, mpzR, mpzN);
unsigned int nFractionalLength = mpz_get_ui(mpzE);
mpz_clear(mpzN);
mpz_clear(mpzE);
mpz_clear(mpzR);
if (nFractionalLength >= (1 << nFractionalBits))
return error("FermatProbablePrimalityTest() : fractional assert");
nLength = (nLength & TARGET_LENGTH_MASK) | nFractionalLength;
return false;
}
// Test probable primality of n = 2p +/- 1 based on Euler, Lagrange and Lifchitz
// fSophieGermain:
// true: n = 2p+1, p prime, aka Cunningham Chain of first kind
// false: n = 2p-1, p prime, aka Cunningham Chain of second kind
// Return values
// true: n is probable prime
// false: n is composite; set fractional length in the nLength output
static bool EulerLagrangeLifchitzPrimalityTest(const CBigNum& n, bool fSophieGermain, unsigned int& nLength)
{
//CBigNum a = 2;
CBigNum e = (n - 1) >> 1;
CBigNum r;
BN_mod_exp(&r, &bnTwo, &e, &n, pctx);
uint32 nMod8U32 = 0;
if( n.top > 0 )
nMod8U32 = n.d[0]&7;
// validate the optimization above:
//CBigNum nMod8 = n % bnConst8;
//if( CBigNum(nMod8U32) != nMod8 )
// __debugbreak();
bool fPassedTest = false;
if (fSophieGermain && (nMod8U32 == 7)) // Euler & Lagrange
fPassedTest = (r == 1);
else if (fSophieGermain && (nMod8U32 == 3)) // Lifchitz
fPassedTest = ((r+1) == n);
else if ((!fSophieGermain) && (nMod8U32 == 5)) // Lifchitz
fPassedTest = ((r+1) == n);
else if ((!fSophieGermain) && (nMod8U32 == 1)) // LifChitz
fPassedTest = (r == 1);
else
return error("EulerLagrangeLifchitzPrimalityTest() : invalid n %% 8 = %d, %s", nMod8U32, (fSophieGermain? "first kind" : "second kind"));
if (fPassedTest)
return true;
// Failed test, calculate fractional length
r = (r * r) % n; // derive Fermat test remainder
unsigned int nFractionalLength = (((n-r) << nFractionalBits) / n).getuint();
if (nFractionalLength >= (1 << nFractionalBits))
return error("EulerLagrangeLifchitzPrimalityTest() : fractional assert");
nLength = (nLength & TARGET_LENGTH_MASK) | nFractionalLength;
return false;
}
class CPrimalityTestParams
{
public:
// GMP variables
mpz_t mpzE;
mpz_t mpzR;
mpz_t mpzRplusOne;
// GMP C++ variables
mpz_class mpzOriginMinusOne;
mpz_class mpzOriginPlusOne;
mpz_class N;
// Values specific to a round
unsigned int nBits;
unsigned int nPrimorialSeq;
unsigned int nCandidateType;
unsigned int nTargetLength;
unsigned int nHalfTargetLength;
// Results
unsigned int nChainLength;
CPrimalityTestParams(unsigned int nBits, unsigned int nPrimorialSeq)
{
this->nBits = nBits;
this->nTargetLength = TargetGetLength(nBits);
this->nHalfTargetLength = nTargetLength / 2;
this->nPrimorialSeq = nPrimorialSeq;
nChainLength = 0;
mpz_init(mpzE);
mpz_init(mpzR);
mpz_init(mpzRplusOne);
}
~CPrimalityTestParams()
{
mpz_clear(mpzE);
mpz_clear(mpzR);
mpz_clear(mpzRplusOne);
}
};
// Check Fermat probable primality test (2-PRP): 2 ** (n-1) = 1 (mod n)
// true: n is probable prime
// false: n is composite; set fractional length in the nLength output
static bool FermatProbablePrimalityTestFast(const mpz_class& n, unsigned int& nLength, CPrimalityTestParams& testParams, bool fFastFail = false)
{
// Faster GMP version
mpz_t& mpzE = testParams.mpzE;
mpz_t& mpzR = testParams.mpzR;
mpz_sub_ui(mpzE, n.get_mpz_t(), 1);
mpz_powm(mpzR, mpzTwo.get_mpz_t(), mpzE, n.get_mpz_t());
if (mpz_cmp_ui(mpzR, 1) == 0)
return true;
if (fFastFail)
return false;
// Failed Fermat test, calculate fractional length
mpz_sub(mpzE, n.get_mpz_t(), mpzR);
mpz_mul_2exp(mpzR, mpzE, nFractionalBits);
mpz_tdiv_q(mpzE, mpzR, n.get_mpz_t());
unsigned int nFractionalLength = mpz_get_ui(mpzE);
if (nFractionalLength >= (1 << nFractionalBits))
return error("FermatProbablePrimalityTest() : fractional assert");
nLength = (nLength & TARGET_LENGTH_MASK) | nFractionalLength;
return false;
}
// Test probable primality of n = 2p +/- 1 based on Euler, Lagrange and Lifchitz
// fSophieGermain:
// true: n = 2p+1, p prime, aka Cunningham Chain of first kind
// false: n = 2p-1, p prime, aka Cunningham Chain of second kind
// Return values
// true: n is probable prime
// false: n is composite; set fractional length in the nLength output
static bool EulerLagrangeLifchitzPrimalityTestFast(const mpz_class& n, bool fSophieGermain, unsigned int& nLength, CPrimalityTestParams& testParams/*, bool fFastDiv = false*/)
{
// Faster GMP version
mpz_t& mpzE = testParams.mpzE;
mpz_t& mpzR = testParams.mpzR;
mpz_t& mpzRplusOne = testParams.mpzRplusOne;
/*
if (fFastDiv)
{
// Fast divisibility tests
// Divide n by a large divisor
// Use the remainder to test divisibility by small primes
const unsigned int nDivSize = testParams.nFastDivisorsSize;
for (unsigned int i = 0; i < nDivSize; i++)
{
unsigned long lRemainder = mpz_tdiv_ui(n.get_mpz_t(), testParams.vFastDivisors[i]);
unsigned int nPrimeSeq = testParams.vFastDivSeq[i];
const unsigned int nPrimeSeqEnd = testParams.vFastDivSeq[i + 1];
for (; nPrimeSeq < nPrimeSeqEnd; nPrimeSeq++)
{
if (lRemainder % vPrimes[nPrimeSeq] == 0)
return false;
}
}
}
*/
mpz_sub_ui(mpzE, n.get_mpz_t(), 1);
mpz_tdiv_q_2exp(mpzE, mpzE, 1);
mpz_powm(mpzR, mpzTwo.get_mpz_t(), mpzE, n.get_mpz_t());
unsigned int nMod8 = mpz_get_ui(n.get_mpz_t()) % 8;
bool fPassedTest = false;
if (fSophieGermain && (nMod8 == 7)) // Euler & Lagrange
fPassedTest = !mpz_cmp_ui(mpzR, 1);
else if (fSophieGermain && (nMod8 == 3)) // Lifchitz
{
mpz_add_ui(mpzRplusOne, mpzR, 1);
fPassedTest = !mpz_cmp(mpzRplusOne, n.get_mpz_t());
}
else if ((!fSophieGermain) && (nMod8 == 5)) // Lifchitz
{
mpz_add_ui(mpzRplusOne, mpzR, 1);
fPassedTest = !mpz_cmp(mpzRplusOne, n.get_mpz_t());
}
else if ((!fSophieGermain) && (nMod8 == 1)) // LifChitz
fPassedTest = !mpz_cmp_ui(mpzR, 1);
else
return error("EulerLagrangeLifchitzPrimalityTest() : invalid n %% 8 = %d, %s", nMod8, (fSophieGermain? "first kind" : "second kind"));
if (fPassedTest)
{
return true;
}
// Failed test, calculate fractional length
mpz_mul(mpzE, mpzR, mpzR);
mpz_tdiv_r(mpzR, mpzE, n.get_mpz_t()); // derive Fermat test remainder
mpz_sub(mpzE, n.get_mpz_t(), mpzR);
mpz_mul_2exp(mpzR, mpzE, nFractionalBits);
mpz_tdiv_q(mpzE, mpzR, n.get_mpz_t());
unsigned int nFractionalLength = mpz_get_ui(mpzE);
if (nFractionalLength >= (1 << nFractionalBits))
return error("EulerLagrangeLifchitzPrimalityTest() : fractional assert");
nLength = (nLength & TARGET_LENGTH_MASK) | nFractionalLength;
return false;
}
// Test probable primality of n = 2p +/- 1 based on Euler, Lagrange and Lifchitz
// fSophieGermain:
// true: n = 2p+1, p prime, aka Cunningham Chain of first kind
// false: n = 2p-1, p prime, aka Cunningham Chain of second kind
// Return values
// true: n is probable prime
// false: n is composite; set fractional length in the nLength output
static bool EulerLagrangeLifchitzPrimalityTest(const mpz_class& n, bool fSophieGermain, unsigned int& nLength)
{
// Faster GMP version
mpz_t mpzN;
mpz_t mpzE;
mpz_t mpzR;
mpz_init_set(mpzN, n.get_mpz_t());
mpz_init(mpzE);
mpz_sub_ui(mpzE, mpzN, 1);
mpz_tdiv_q_2exp(mpzE, mpzE, 1);
mpz_init(mpzR);
mpz_powm(mpzR, mpzTwo.get_mpz_t(), mpzE, mpzN);
unsigned int nMod8 = mpz_tdiv_ui(mpzN, 8);
bool fPassedTest = false;
if (fSophieGermain && (nMod8 == 7)) // Euler & Lagrange
fPassedTest = !mpz_cmp_ui(mpzR, 1);
else if (fSophieGermain && (nMod8 == 3)) // Lifchitz
{
mpz_t mpzRplusOne;
mpz_init(mpzRplusOne);
mpz_add_ui(mpzRplusOne, mpzR, 1);
fPassedTest = !mpz_cmp(mpzRplusOne, mpzN);
mpz_clear(mpzRplusOne);
}
else if ((!fSophieGermain) && (nMod8 == 5)) // Lifchitz
{
mpz_t mpzRplusOne;
mpz_init(mpzRplusOne);
mpz_add_ui(mpzRplusOne, mpzR, 1);
fPassedTest = !mpz_cmp(mpzRplusOne, mpzN);
mpz_clear(mpzRplusOne);
}
else if ((!fSophieGermain) && (nMod8 == 1)) // LifChitz
{
fPassedTest = !mpz_cmp_ui(mpzR, 1);
}
else
{
mpz_clear(mpzN);
mpz_clear(mpzE);
mpz_clear(mpzR);
return error("EulerLagrangeLifchitzPrimalityTest() : invalid n %% 8 = %d, %s", nMod8, (fSophieGermain? "first kind" : "second kind"));
}
if (fPassedTest) {
mpz_clear(mpzN);
mpz_clear(mpzE);
mpz_clear(mpzR);
return true;
}
// Failed test, calculate fractional length
mpz_mul(mpzE, mpzR, mpzR);
mpz_tdiv_r(mpzR, mpzE, mpzN); // derive Fermat test remainder
mpz_sub(mpzE, mpzN, mpzR);
mpz_mul_2exp(mpzR, mpzE, nFractionalBits);
mpz_tdiv_q(mpzE, mpzR, mpzN);
unsigned int nFractionalLength = mpz_get_ui(mpzE);
mpz_clear(mpzN);
mpz_clear(mpzE);
mpz_clear(mpzR);
if (nFractionalLength >= (1 << nFractionalBits)) {
return error("EulerLagrangeLifchitzPrimalityTest() : fractional assert");
}
nLength = (nLength & TARGET_LENGTH_MASK) | nFractionalLength;
return false;
}
// Proof-of-work Target (prime chain target):
// format - 32 bit, 8 length bits, 24 fractional length bits
unsigned int nTargetInitialLength = 7; // initial chain length target
unsigned int nTargetMinLength = 6; // minimum chain length target
unsigned int TargetGetLimit()
{
return (nTargetMinLength << nFractionalBits);
}
unsigned int TargetGetInitial()
{
return (nTargetInitialLength << nFractionalBits);
}
unsigned int TargetGetLength(unsigned int nBits)
{
return ((nBits & TARGET_LENGTH_MASK) >> nFractionalBits);
}
bool TargetSetLength(unsigned int nLength, unsigned int& nBits)
{
if (nLength >= 0xff)
return error("TargetSetLength() : invalid length=%u", nLength);
nBits &= TARGET_FRACTIONAL_MASK;
nBits |= (nLength << nFractionalBits);
return true;
}
void TargetIncrementLength(unsigned int& nBits)
{
nBits += (1 << nFractionalBits);
}
void TargetDecrementLength(unsigned int& nBits)
{
if (TargetGetLength(nBits) > nTargetMinLength)
nBits -= (1 << nFractionalBits);
}
unsigned int TargetGetFractional(unsigned int nBits)
{
return (nBits & TARGET_FRACTIONAL_MASK);
}
uint64 TargetGetFractionalDifficulty(unsigned int nBits)
{
return (nFractionalDifficultyMax / (uint64) ((1ull<<nFractionalBits) - TargetGetFractional(nBits)));
}
bool TargetSetFractionalDifficulty(uint64 nFractionalDifficulty, unsigned int& nBits)
{
if (nFractionalDifficulty < nFractionalDifficultyMin)
return error("TargetSetFractionalDifficulty() : difficulty below min");
uint64 nFractional = nFractionalDifficultyMax / nFractionalDifficulty;
if (nFractional > (1u<<nFractionalBits))
return error("TargetSetFractionalDifficulty() : fractional overflow: nFractionalDifficulty=%016I64d", nFractionalDifficulty);
nFractional = (1u<<nFractionalBits) - nFractional;
nBits &= TARGET_LENGTH_MASK;
nBits |= (unsigned int)nFractional;
return true;
}
std::string TargetToString(unsigned int nBits)
{
__debugbreak(); // return strprintf("%02x.%06x", TargetGetLength(nBits), TargetGetFractional(nBits));
return NULL; // todo
}
unsigned int TargetFromInt(unsigned int nLength)
{
return (nLength << nFractionalBits);
}
// Get mint value from target
// Primecoin mint rate is determined by target
// mint = 999 / (target length ** 2)
// Inflation is controlled via Moore's Law
bool TargetGetMint(unsigned int nBits, uint64& nMint)
{
nMint = 0;
static uint64 nMintLimit = 999ull * COIN;
CBigNum bnMint = nMintLimit;
if (TargetGetLength(nBits) < nTargetMinLength)
return error("TargetGetMint() : length below minimum required, nBits=%08x", nBits);
bnMint = (bnMint << nFractionalBits) / nBits;
bnMint = (bnMint << nFractionalBits) / nBits;
bnMint = (bnMint / CENT) * CENT; // mint value rounded to cent
nMint = bnMint.getuint256().Get64();
if (nMint > nMintLimit)
{
nMint = 0;
return error("TargetGetMint() : mint value over limit, nBits=%08x", nBits);
}
return true;
}
// Get next target value
bool TargetGetNext(unsigned int nBits, int64 nInterval, int64 nTargetSpacing, int64 nActualSpacing, unsigned int& nBitsNext)
{
nBitsNext = nBits;
// Convert length into fractional difficulty
uint64 nFractionalDifficulty = TargetGetFractionalDifficulty(nBits);
// Compute new difficulty via exponential moving toward target spacing
CBigNum bnFractionalDifficulty = nFractionalDifficulty;
bnFractionalDifficulty *= ((nInterval + 1) * nTargetSpacing);
bnFractionalDifficulty /= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
if (bnFractionalDifficulty > nFractionalDifficultyMax)
bnFractionalDifficulty = nFractionalDifficultyMax;
if (bnFractionalDifficulty < nFractionalDifficultyMin)
bnFractionalDifficulty = nFractionalDifficultyMin;
uint64 nFractionalDifficultyNew = bnFractionalDifficulty.getuint256().Get64();
//if (fDebug && GetBoolArg("-printtarget"))
// printf("TargetGetNext() : nActualSpacing=%d nFractionDiff=%016"PRI64x" nFractionDiffNew=%016"PRI64x"\n", (int)nActualSpacing, nFractionalDifficulty, nFractionalDifficultyNew);
// Step up length if fractional past threshold
if (nFractionalDifficultyNew > nFractionalDifficultyThreshold)
{
nFractionalDifficultyNew = nFractionalDifficultyMin;
TargetIncrementLength(nBitsNext);
}
// Step down length if fractional at minimum
else if (nFractionalDifficultyNew == nFractionalDifficultyMin && TargetGetLength(nBitsNext) > nTargetMinLength)
{
nFractionalDifficultyNew = nFractionalDifficultyThreshold;
TargetDecrementLength(nBitsNext);
}
// Convert fractional difficulty back to length
if (!TargetSetFractionalDifficulty(nFractionalDifficultyNew, nBitsNext))
return error("TargetGetNext() : unable to set fractional difficulty prev=0x%016I64d new=0x%016I64d", nFractionalDifficulty, nFractionalDifficultyNew);
return true;
}
// Test Probable Cunningham Chain for: n
// fSophieGermain:
// true - Test for Cunningham Chain of first kind (n, 2n+1, 4n+3, ...)
// false - Test for Cunningham Chain of second kind (n, 2n-1, 4n-3, ...)
// Return value:
// true - Probable Cunningham Chain found (length at least 2)
// false - Not Cunningham Chain
static bool ProbableCunninghamChainTestFast(const mpz_class& n, const bool fSophieGermain, const bool fFermatTest, unsigned int& nProbableChainLength, CPrimalityTestParams& testParams, bool fBiTwinTest)
{
nProbableChainLength = 0;
// Fermat test for n first
if (!FermatProbablePrimalityTestFast(n, nProbableChainLength, testParams, true))
return false;
const int chainIncremental = (fSophieGermain? 1 : (-1));
mpz_class &N = testParams.N;
N = n;
unsigned int quickTargetCheck = 0;
if (bSoloMining)
{
// Get prime origin.
mpz_class M = n;
// Get target depth to check.
quickTargetCheck = (!fBiTwinTest) ? testParams.nTargetLength : testParams.nHalfTargetLength;
M = (M + chainIncremental) * (1 << (quickTargetCheck - 2)) - chainIncremental;
// If this target fails we don't have a valid candidate, go no further.
if (!FermatProbablePrimalityTestFast(M, nProbableChainLength, testParams, true))
{
return false;
}
else
{
M <<= 1;
M += chainIncremental;
if (!FermatProbablePrimalityTestFast(M, nProbableChainLength, testParams, true))
{
return false;
}
}
}
// Euler-Lagrange-Lifchitz test for the following numbers in chain
unsigned int currentLength = 0;
while (true)
{
TargetIncrementLength(nProbableChainLength);
N <<= 1;
N += chainIncremental;
currentLength++;
if (bSoloMining)
{
if (currentLength == quickTargetCheck - 2) continue; // We already proved this length is valid.
if (currentLength == quickTargetCheck - 1) continue; // We already proved this length is valid.
}
if (fFermatTest)
{
if (!FermatProbablePrimalityTestFast(N, nProbableChainLength, testParams))
break;
}
else
{
if (!EulerLagrangeLifchitzPrimalityTestFast(N, fSophieGermain, nProbableChainLength, testParams))
break;
}
}
return (currentLength >= 2);
}
// Test Probable Cunningham Chain for: n
// fSophieGermain:
// true - Test for Cunningham Chain of first kind (n, 2n+1, 4n+3, ...)
// false - Test for Cunningham Chain of second kind (n, 2n-1, 4n-3, ...)
// Return value:
// true - Probable Cunningham Chain found (length at least 2)
// false - Not Cunningham Chain
static bool ProbableCunninghamChainTest(const mpz_class& n, bool fSophieGermain, bool fFermatTest, unsigned int& nProbableChainLength)
{
nProbableChainLength = 0;
mpz_class N = n;
// Fermat test for n first
if (!FermatProbablePrimalityTest(N, nProbableChainLength))
return false;
// Euler-Lagrange-Lifchitz test for the following numbers in chain
while (true)
{
TargetIncrementLength(nProbableChainLength);
N = N + N + (fSophieGermain? 1 : (-1));
if (fFermatTest)
{
if (!FermatProbablePrimalityTest(N, nProbableChainLength))
break;
}
else
{
if (!EulerLagrangeLifchitzPrimalityTest(N, fSophieGermain, nProbableChainLength))
break;
}
}
return (TargetGetLength(nProbableChainLength) >= 2);
}
static bool ProbableCunninghamChainTestBN(const CBigNum& n, bool fSophieGermain, bool fFermatTest, unsigned int& nProbableChainLength)
{
nProbableChainLength = 0;
CBigNum N = n;
// Fermat test for n first
if (!FermatProbablePrimalityTest(N, nProbableChainLength))
return false;
// Euler-Lagrange-Lifchitz test for the following numbers in chain
while (true)
{
TargetIncrementLength(nProbableChainLength);
N = N + N + (fSophieGermain? 1 : (-1));
if (fFermatTest)
{
if (!FermatProbablePrimalityTest(N, nProbableChainLength))
break;
}
else
{
if (!EulerLagrangeLifchitzPrimalityTest(N, fSophieGermain, nProbableChainLength))
break;
}
}
return (TargetGetLength(nProbableChainLength) >= 2);
}
// Test probable prime chain for: nOrigin
// Return value:
// true - Probable prime chain found (one of nChainLength meeting target)
// false - prime chain too short (none of nChainLength meeting target)
bool ProbablePrimeChainTest(const mpz_class& bnPrimeChainOrigin, unsigned int nBits, bool fFermatTest, unsigned int& nChainLengthCunningham1, unsigned int& nChainLengthCunningham2, unsigned int& nChainLengthBiTwin, bool fullTest)
{
nChainLengthCunningham1 = 0;
nChainLengthCunningham2 = 0;
nChainLengthBiTwin = 0;
// Test for Cunningham Chain of second kind
ProbableCunninghamChainTest(bnPrimeChainOrigin+1, false, fFermatTest, nChainLengthCunningham2);
if (nChainLengthCunningham2 >= nBits && !fullTest)
return true;
// Test for Cunningham Chain of first kind
ProbableCunninghamChainTest(bnPrimeChainOrigin-1, true, fFermatTest, nChainLengthCunningham1);
if (nChainLengthCunningham1 >= nBits && !fullTest)
return true;
// Figure out BiTwin Chain length
// BiTwin Chain allows a single prime at the end for odd length chain
nChainLengthBiTwin =
(TargetGetLength(nChainLengthCunningham1) > TargetGetLength(nChainLengthCunningham2))?
(nChainLengthCunningham2 + TargetFromInt(TargetGetLength(nChainLengthCunningham2)+1)) :
(nChainLengthCunningham1 + TargetFromInt(TargetGetLength(nChainLengthCunningham1)));
if (fullTest)
return (nChainLengthCunningham1 >= nBits || nChainLengthCunningham2 >= nBits || nChainLengthBiTwin >= nBits);
else
return nChainLengthBiTwin >= nBits;
}
// Test probable prime chain for: nOrigin
// Return value:
// true - Probable prime chain found (one of nChainLength meeting target)
// false - prime chain too short (none of nChainLength meeting target)
static bool ProbablePrimeChainTestFast(const mpz_class& mpzPrimeChainOrigin, CPrimalityTestParams& testParams)
{
const unsigned int nBits = testParams.nBits;
const unsigned int nCandidateType = testParams.nCandidateType;
unsigned int& nChainLength = testParams.nChainLength;
mpz_class& mpzOriginMinusOne = testParams.mpzOriginMinusOne;
mpz_class& mpzOriginPlusOne = testParams.mpzOriginPlusOne;
nChainLength = 0;
// Test for Cunningham Chain of first kind
if (nCandidateType == PRIME_CHAIN_CUNNINGHAM1)
{
mpzOriginMinusOne = mpzPrimeChainOrigin - 1;
ProbableCunninghamChainTestFast(mpzOriginMinusOne, true, false, nChainLength, testParams, false);
}
else if (nCandidateType == PRIME_CHAIN_CUNNINGHAM2)
{
// Test for Cunningham Chain of second kind
mpzOriginPlusOne = mpzPrimeChainOrigin + 1;
ProbableCunninghamChainTestFast(mpzOriginPlusOne, false, false, nChainLength, testParams, false);
}
else
{
unsigned int nChainLengthCunningham1 = 0;
unsigned int nChainLengthCunningham2 = 0;
mpzOriginMinusOne = mpzPrimeChainOrigin - 1;
if (ProbableCunninghamChainTestFast(mpzOriginMinusOne, true, false, nChainLengthCunningham1, testParams, true))
{
mpzOriginPlusOne = mpzPrimeChainOrigin + 1;
ProbableCunninghamChainTestFast(mpzOriginPlusOne, false, false, nChainLengthCunningham2, testParams, true);
// Figure out BiTwin Chain length
// BiTwin Chain allows a single prime at the end for odd length chain
nChainLength =
(TargetGetLength(nChainLengthCunningham1) > TargetGetLength(nChainLengthCunningham2))?
(nChainLengthCunningham2 + TargetFromInt(TargetGetLength(nChainLengthCunningham2)+1)) :
(nChainLengthCunningham1 + TargetFromInt(TargetGetLength(nChainLengthCunningham1)));
}
}
primeStats.nTestRound ++;
return (nChainLength >= nBits);
}
//// Sieve for mining
//boost::thread_specific_ptr<CSieveOfEratosthenes> psieve;
// Mine probable prime chain of form: n = h * p# +/- 1
bool MineProbablePrimeChain(CSieveOfEratosthenes*& psieve, primecoinBlock_t* block, mpz_class& mpzFixedMultiplier, bool& fNewBlock, unsigned int& nTriedMultiplier, unsigned int& nProbableChainLength,
unsigned int& nTests, unsigned int& nPrimesHit, sint32 threadIndex, mpz_class& mpzHash, unsigned int nPrimorialMultiplier)
{
nProbableChainLength = 0;
nTests = 0;
nPrimesHit = 0;
//if (fNewBlock && *psieve != NULL)
//{
// // Must rebuild the sieve
//// printf("Must rebuild the sieve\n");
// delete *psieve;
// *psieve = NULL;
//}
fNewBlock = false;
unsigned int lSieveTarget, lSieveBTTarget;
if (nOverrideTargetValue > 0)
lSieveTarget = nOverrideTargetValue;
else
{
lSieveTarget = TargetGetLength(block->nBits);
// If Difficulty gets within 1/36th of next target length, its actually more efficent to
// increase the target length.. While technically worse for share val/hr - this should
// help block rate.
// Discussions with jh00 revealed this is non-linear, and graphs show that 0.1 diff is enough
// to warrant a switch
if (GetChainDifficulty(block->nBits) >= ((lSieveTarget + 1) - 0.1f))
lSieveTarget++;
}
if (nOverrideBTTargetValue > 0)
lSieveBTTarget = nOverrideBTTargetValue;
else
lSieveBTTarget = lSieveTarget; // Set to same as target
//int64 nStart, nCurrent; // microsecond timer
if (psieve == NULL)
{
// Build sieve
psieve = new CSieveOfEratosthenes(nMaxSieveSize, nSievePercentage, nSieveExtensions, lSieveTarget, lSieveBTTarget, mpzHash, mpzFixedMultiplier);
psieve->Weave();
}
else
{
psieve->Init(nMaxSieveSize, nSievePercentage, nSieveExtensions, lSieveTarget, lSieveBTTarget, mpzHash, mpzFixedMultiplier);
psieve->Weave();
}
primeStats.nSieveRounds++;
primeStats.nCandidateCount += psieve->GetCandidateCount();
mpz_class mpzHashMultiplier = mpzHash * mpzFixedMultiplier;
mpz_class mpzChainOrigin;
// Determine the sequence number of the round primorial
unsigned int nPrimorialSeq = 0;
while (vPrimes[nPrimorialSeq + 1] <= nPrimorialMultiplier)
nPrimorialSeq++;
// Allocate GMP variables for primality tests
CPrimalityTestParams testParams(block->serverData.nBitsForShare, nPrimorialSeq);
// References to test parameters
unsigned int& nChainLength = testParams.nChainLength;
unsigned int& nCandidateType = testParams.nCandidateType;
//nStart = GetTickCount();
//nCurrent = nStart;
//uint32 timeStop = GetTickCount() + 25000;
//int nTries = 0;
bool multipleShare = false;
mpz_class mpzPrevPrimeChainMultiplier = 0;
bool rtnValue = false;
uint32 start = GetTickCount();
while (block->serverData.blockHeight == jhMiner_getCurrentWorkBlockHeight(block->threadIndex))
{
if (!psieve->GetNextCandidateMultiplier(nTriedMultiplier, nCandidateType))
{
// power tests completed for the sieve
fNewBlock = true; // notify caller to change nonce
rtnValue = false;
break;
}
nTests++;
mpzChainOrigin = mpzHash * mpzFixedMultiplier * nTriedMultiplier;
nChainLength = 0;
ProbablePrimeChainTestFast(mpzChainOrigin, testParams);
nProbableChainLength = nChainLength;
sint32 shareDifficultyMajor = 0;
primeStats.primeChainsFound++;
if( nProbableChainLength >= 0x06000000 )
{
shareDifficultyMajor = (sint32)(nChainLength>>24);
}
else
{
continue;
}
primeStats.bestPrimeChainDifficultySinceLaunch = max(primeStats.bestPrimeChainDifficultySinceLaunch, nProbableChainLength);
if(nProbableChainLength >= block->serverData.nBitsForShare)
{
// Update Stats
primeStats.chainCounter[0][min(shareDifficultyMajor,12)]++;
primeStats.chainCounter[nCandidateType][min(shareDifficultyMajor,12)]++;
primeStats.nChainHit++;
block->mpzPrimeChainMultiplier = mpzFixedMultiplier * nTriedMultiplier;
time_t now = time(0);
struct tm * timeinfo;
timeinfo = localtime (&now);
char sNow [80];
strftime (sNow, 80, "%x-%X",timeinfo);
float shareDiff = GetChainDifficulty(nProbableChainLength);
if (bSoloMining)
{
printf("%s - BLOCK FOUND !!! --- DIFF: %f\n", sNow, shareDiff);
return SubmitBlock( block);
}
else
{
// attempt to prevent duplicate share submissions.
if (multipleShare && multiplierSet.find(block->mpzPrimeChainMultiplier) != multiplierSet.end())
continue;
// update server data
block->serverData.client_shareBits = nProbableChainLength;
// generate block raw data
uint8 blockRawData[256] = {0};
memcpy(blockRawData, block, 80);
uint32 writeIndex = 80;
sint32 lengthBN = 0;
CBigNum bnPrimeChainMultiplier;
bnPrimeChainMultiplier.SetHex(block->mpzPrimeChainMultiplier.get_str(16));
std::vector<unsigned char> bnSerializeData = bnPrimeChainMultiplier.getvch();
lengthBN = bnSerializeData.size();
*(uint8*)(blockRawData+writeIndex) = (uint8)lengthBN; // varInt (we assume it always has a size low enough for 1 byte)
writeIndex += 1;
memcpy(blockRawData+writeIndex, &bnSerializeData[0], lengthBN);
writeIndex += lengthBN;
// switch endianness
for(uint32 f=0; f<256/4; f++)
{
*(uint32*)(blockRawData+f*4) = _swapEndianessU32(*(uint32*)(blockRawData+f*4));
}
printf("%s - SHARE FOUND! - (Th#:%2u) - DIFF:%8f - TYPE:%u\n", sNow, threadIndex, shareDiff, nCandidateType);
if (nPrintDebugMessages)
{
printf("HashNum : %s\n", mpzHash.get_str(16).c_str());
printf("FixedMultiplier: %s\n", mpzFixedMultiplier.get_str(16).c_str());
printf("HashMultiplier : %u\n", nTriedMultiplier);
}