-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
primenet.py
5056 lines (4506 loc) · 220 KB
/
primenet.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Automatic assignment handler for Mlucas, GpuOwl/PRPLL, CUDALucas and CUDAPm1.
[*] Revised by Teal Dulcet and Daniel Connelly for CUDALucas (2020)
Original Authorship(s):
* # EWM: adapted from https://github.com/MarkRose/primetools/blob/master/mfloop.py
by teknohog and Mark Rose, with help rom Gord Palameta.
* # 2020: support for computer registration and assignment-progress via
direct Primenet-v5-API calls by Loïc Le Loarer <loic@le-loarer.org>
[*] List of supported v5 operations:
* Update Computer Info (uc, register_instance) (Credit: Loarer & Dulcet)
* Program Options (po, program_options) (Credit: Connelly & Dulcet)
* Get Assignment (ga, get_assignment) (Credit: Connelly & Dulcet)
* Register Assignment (ra, register_assignment) (Credit: Dulcet)
* Assignment Un-Reserve (au, assignment_unreserve) (Credit: Dulcet)
* Assignment Progress (ap, send_progress) (Credit: Loarer & Dulcet)
* Assignment Result (ar, report_result) (Credit: Loarer & Dulcet)
* Benchmark Data Statistics (bd) N/A
* Ping Server (ps, ping_server) (Credit: Dulcet)
"""
################################################################################
# #
# (C) 2017-2024 by Daniel Connelly and Teal Dulcet. #
# #
# This program is free software; you can redistribute it and/or modify it #
# under the terms of the GNU General Public License as published by the #
# Free Software Foundation; either version 2 of the License, or (at your #
# option) any later version. #
# #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
# more details. #
# #
# You should have received a copy of the GNU General Public License along #
# with this program; see the file GPL.txt. If not, you may view one at #
# http://www.fsf.org/licenses/licenses.html, or obtain one by writing to the #
# Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA #
# 02111-1307, USA. #
# #
################################################################################
from __future__ import division, print_function, unicode_literals
import atexit
import ctypes
import getpass
import glob
import json
import locale
import logging
import logging.handlers
import math
import mimetypes
import optparse
import os
import platform
import random
import re
import shutil
import smtplib
import struct
import sys
import textwrap
import threading
import time
import timeit
import uuid
import zipfile
from collections import deque
from ctypes.util import find_library
from datetime import datetime, timedelta
from decimal import Decimal
from email import charset, encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr, formatdate, parseaddr
from hashlib import md5
from itertools import chain, count, starmap
try:
# Python 3+
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
try:
# Python 3+
from configparser import ConfigParser
from configparser import Error as ConfigParserError
except ImportError:
from ConfigParser import ConfigParser
from ConfigParser import Error as ConfigParserError
if sys.version_info >= (3, 7):
# Python 3.7+
# If is OK to use dict in 3.7+ because insertion order is guaranteed to be preserved
# Since it is also faster, it is better to use raw dict()
OrderedDict = dict
else:
try:
# Python 2.7 and 3.1+
from collections import OrderedDict
except ImportError:
# Tests will not work correctly but it doesn't affect the
# functionality
OrderedDict = dict
try:
# Python 3.4+
from statistics import median_low
except ImportError:
def median_low(data):
sorts = sorted(data)
length = len(sorts)
return sorts[(length - 1) // 2]
try:
# Python 3.8+
from math import isqrt
except ImportError:
def isqrt(x):
return int(math.sqrt(x))
try:
# Python 3.3+
from math import log2
except ImportError:
def log2(x):
return math.log(x, 2)
try:
# Python 3.2+
from math import expm1
except ImportError:
def expm1(x):
return math.exp(x) - 1
try:
# Python 3.3+
from shutil import disk_usage
except ImportError:
# Adapted from: https://code.activestate.com/recipes/577972-disk-usage/
from collections import namedtuple
_ntuple_diskusage = namedtuple("usage", "total used free")
if hasattr(os, "statvfs"): # POSIX
def disk_usage(path):
st = os.statvfs(path)
free = st.f_bavail * st.f_frsize
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return _ntuple_diskusage(total, used, free)
elif os.name == "nt": # Windows
def disk_usage(path):
_, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), ctypes.c_ulonglong()
if sys.version_info >= (3,) or isinstance(path, unicode):
fun = ctypes.windll.kernel32.GetDiskFreeSpaceExW
else:
fun = ctypes.windll.kernel32.GetDiskFreeSpaceExA
if not fun(path, ctypes.byref(_), ctypes.byref(total),
ctypes.byref(free)):
raise ctypes.WinError()
used = total.value - free.value
return _ntuple_diskusage(total.value, used, free.value)
if sys.platform == "win32": # Windows
from ctypes import wintypes
try:
# Python 3+
import winreg
except ImportError:
import _winreg as winreg
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
class ProcessorCore(ctypes.Structure):
_fields_ = (("Flags", wintypes.BYTE),)
class NumaNode(ctypes.Structure):
_fields_ = (("NodeNumber", wintypes.DWORD),)
class CACHE_DESCRIPTOR(ctypes.Structure):
_fields_ = (("Level", wintypes.BYTE),
("Associativity", wintypes.BYTE),
("LineSize", wintypes.WORD),
("Size", wintypes.DWORD),
("Type", wintypes.DWORD))
class Union(ctypes.Union):
_fields_ = (("ProcessorCore", ProcessorCore),
("NumaNode", NumaNode),
("Cache", CACHE_DESCRIPTOR),
("Reserved", ctypes.c_ulonglong * 2))
class SYSTEM_LOGICAL_PROCESSOR_INFORMATION(ctypes.Structure):
_fields_ = (("ProcessorMask", ctypes.POINTER(ctypes.c_ulong)),
("Relationship", wintypes.DWORD),
("Union", Union))
_anonymous_ = ("Union",)
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = (("dwLength", wintypes.DWORD),
("dwMemoryLoad", wintypes.DWORD),
("ullTotalPhys", ctypes.c_ulonglong),
("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong),
("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong),
("ullAvailVirtual", ctypes.c_ulonglong),
("ullAvailExtendedVirtual", ctypes.c_ulonglong))
def __init__(self):
self.dwLength = ctypes.sizeof(self)
super(MEMORYSTATUSEX, self).__init__()
elif sys.platform == "darwin": # macOS
libc = ctypes.CDLL(find_library("c"))
def sysctl_str(name):
size = ctypes.c_size_t()
libc.sysctlbyname(name, None, ctypes.byref(size), None, 0)
buf = ctypes.create_string_buffer(size.value)
libc.sysctlbyname(name, buf, ctypes.byref(size), None, 0)
return buf.value
def sysctl_value(name, ctype):
size = ctypes.c_size_t(ctypes.sizeof(ctype))
value = ctype()
libc.sysctlbyname(name, ctypes.byref(value),
ctypes.byref(size), None, 0)
return value.value
try:
# Windows
import winsound
except ImportError:
def beep():
"""Emits a beep sound."""
print("\a")
else:
def beep():
"""Emits a beep sound."""
winsound.MessageBeep(type=-1)
try:
# Linux and macOS
import readline
except ImportError:
pass
else:
readline.set_completer_delims("")
readline.parse_and_bind("tab: complete")
try:
# import certifi
import requests
from requests.exceptions import (
ConnectionError,
HTTPError,
RequestException,
Timeout,
)
except ImportError:
import subprocess
print("Installing requests dependency")
subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])
print("The Requests library has been installed. Please run the program again")
sys.exit(0)
locale.setlocale(locale.LC_ALL, "")
if hasattr(sys, "set_int_max_str_digits"):
sys.set_int_max_str_digits(0)
charset.add_charset("utf-8", charset.QP, charset.QP, "utf-8")
VERSION = "2.1"
# GIMPS programs to use in the application version string when registering with PrimeNet
PROGRAMS = (
{"name": "Prime95", "version": "30.19", "build": 20},
{"name": "Mlucas", "version": "21.0.1"},
{"name": "GpuOwl", "version": "7.5"},
{"name": "CUDALucas", "version": "2.06"})
# People to e-mail when a new prime is found
# E-mail addresses munged to prevent spam
CCEMAILS = [(name, user + "@" + ".".join(hosts)) for name, (user, hosts) in (
# ("Primenet server", ("primenet", ("mersenne", "org"))),
("George Woltman", ("woltman", ("alum", "mit", "edu"))),
("James Heinrich", ("james", ("mersenne", "ca"))),
("Aaron", ("aaron", ("madpoo", "com"))),
# ("E. Mayer", ("ewmayer", ("aol", "com"))),
("Mihai Preda", ("mpreda", ("gmail", "com"))),
("Daniel Connelly", ("connellyd2050", ("gmail", "com"))),
("Teal Dulcet", ("tdulcet", ("gmail", "com"))))]
primenet_v5_burl = "http://v5.mersenne.org/v5server/"
TRANSACTION_API_VERSION = 0.95
ERROR_RATE = 0.018 # Estimated LL error rate on clean run
# Estimated PRP error rate (assumes Gerbicz error-checking)
PRP_ERROR_RATE = 0.0001
_V5_UNIQUE_TRUSTED_CLIENT_CONSTANT_ = 17737
primenet_v5_bargs = OrderedDict(
(("px", "GIMPS"), ("v", TRANSACTION_API_VERSION)))
primenet_baseurl = "https://www.mersenne.org/"
primenet_login = False
is_64bit = platform.machine().endswith("64")
PORT = None
if sys.platform == "win32":
PORT = 4 if is_64bit else 1
elif sys.platform == "darwin":
PORT = 10 if is_64bit else 9
elif sys.platform.startswith("linux"):
PORT = 8 if is_64bit else 2
session = requests.Session() # session that maintains our cookies
atexit.register(session.close)
# Python 2.7.9 and 3.4+
# context = ssl.create_default_context(cafile=certifi.where())
# Mlucas constants
TEST_TYPE_PRIMALITY = 1
TEST_TYPE_PRP = 2
TEST_TYPE_PM1 = 3
MODULUS_TYPE_MERSENNE = 1
MODULUS_TYPE_FERMAT = 3
class Formatter(logging.Formatter):
def format(self, record):
record.worker = ", Worker #{0:n}".format(
record.cpu_num + 1) if hasattr(record, "cpu_num") else ""
return super(Formatter, self).format(record)
class SEC:
Internals = "Internals"
PrimeNet = "PrimeNet"
Email = "Email"
class PRIMENET:
# Error codes returned to client
ERROR_OK = 0 # no error
ERROR_SERVER_BUSY = 3 # server is too busy now
ERROR_INVALID_VERSION = 4
ERROR_INVALID_TRANSACTION = 5
# Returned for length, type, or character invalidations.
ERROR_INVALID_PARAMETER = 7
ERROR_ACCESS_DENIED = 9
ERROR_DATABASE_CORRUPT = 11
ERROR_DATABASE_FULL_OR_BROKEN = 13
# Account related errors:
ERROR_INVALID_USER = 21
# Computer cpu/software info related errors:
ERROR_UNREGISTERED_CPU = 30
ERROR_OBSOLETE_CLIENT = 31
ERROR_STALE_CPU_INFO = 32
ERROR_CPU_IDENTITY_MISMATCH = 33
ERROR_CPU_CONFIGURATION_MISMATCH = 34
# Work assignment related errors:
ERROR_NO_ASSIGNMENT = 40
ERROR_INVALID_ASSIGNMENT_KEY = 43
ERROR_INVALID_ASSIGNMENT_TYPE = 44
ERROR_INVALID_RESULT_TYPE = 45
ERROR_INVALID_WORK_TYPE = 46
ERROR_WORK_NO_LONGER_NEEDED = 47
# Valid work_preference values
WP_WHATEVER = 0 # Whatever makes most sense
WP_FACTOR_LMH = 1 # Factor big numbers to low limits
WP_FACTOR = 2 # Trial factoring
WP_PMINUS1 = 3 # P-1 of small Mersennes --- not supported
WP_PFACTOR = 4 # P-1 of large Mersennes
WP_ECM_SMALL = 5 # ECM of small Mersennes looking for first factors
WP_ECM_FERMAT = 6 # ECM of Fermat numbers
WP_ECM_CUNNINGHAM = 7 # ECM of Cunningham numbers --- not supported
WP_ECM_COFACTOR = 8 # ECM of Mersenne cofactors
WP_LL_FIRST = 100 # LL first time tests
WP_LL_DBLCHK = 101 # LL double checks
WP_LL_WORLD_RECORD = 102 # LL test of world record Mersenne
WP_LL_100M = 104 # LL 100 million digit
WP_PRP_FIRST = 150 # PRP test of big Mersennes
WP_PRP_DBLCHK = 151 # PRP double checks
WP_PRP_WORLD_RECORD = 152 # PRP test of world record Mersennes
WP_PRP_100M = 153 # PRP test of 100M digit Mersennes
WP_PRP_NO_PMINUS1 = 154 # PRP test that if possible also needs P-1
WP_PRP_DC_PROOF = 155 # PRP double-check where a proof will be produced
WP_PRP_COFACTOR = 160 # PRP test of Mersenne cofactors
WP_PRP_COFACTOR_DBLCHK = 161 # PRP double check of Mersenne cofactors
# Valid work_types returned by ga
WORK_TYPE_FACTOR = 2
WORK_TYPE_PMINUS1 = 3
WORK_TYPE_PFACTOR = 4
WORK_TYPE_ECM = 5
WORK_TYPE_PPLUS1 = 6 # Not yet supported by the server
WORK_TYPE_FIRST_LL = 100
WORK_TYPE_DBLCHK = 101
WORK_TYPE_PRP = 150
WORK_TYPE_CERT = 200
# This structure is passed for the ar - Assignment Result call
AR_NO_RESULT = 0 # No result, just sending done msg
AR_TF_FACTOR = 1 # Trial factoring, factor found
AR_P1_FACTOR = 2 # P-1, factor found
AR_ECM_FACTOR = 3 # ECM, factor found
AR_TF_NOFACTOR = 4 # Trial Factoring no factor found
AR_P1_NOFACTOR = 5 # P-1 factoring no factor found
AR_ECM_NOFACTOR = 6 # ECM factoring no factor found
AR_PP1_FACTOR = 7 # P+1, factor found
AR_PP1_NOFACTOR = 8 # P+1 factoring no factor found
AR_LL_RESULT = 100 # LL result, not prime
AR_LL_PRIME = 101 # LL result, Mersenne prime
AR_PRP_RESULT = 150 # PRP result, not prime
AR_PRP_PRIME = 151 # PRP result, probably prime
AR_CERT = 200 # Certification result
errors = {
PRIMENET.ERROR_SERVER_BUSY: "Server busy",
PRIMENET.ERROR_INVALID_VERSION: "Invalid version",
PRIMENET.ERROR_INVALID_TRANSACTION: "Invalid transaction",
PRIMENET.ERROR_INVALID_PARAMETER: "Invalid parameter",
PRIMENET.ERROR_ACCESS_DENIED: "Access denied",
PRIMENET.ERROR_DATABASE_CORRUPT: "Server database malfunction",
PRIMENET.ERROR_DATABASE_FULL_OR_BROKEN: "Server database full or broken",
PRIMENET.ERROR_INVALID_USER: "Invalid user",
PRIMENET.ERROR_UNREGISTERED_CPU: "CPU not registered",
PRIMENET.ERROR_OBSOLETE_CLIENT: "Obsolete client, please upgrade",
PRIMENET.ERROR_STALE_CPU_INFO: "Stale cpu info",
PRIMENET.ERROR_CPU_IDENTITY_MISMATCH: "CPU identity mismatch",
PRIMENET.ERROR_CPU_CONFIGURATION_MISMATCH: "CPU configuration mismatch",
PRIMENET.ERROR_NO_ASSIGNMENT: "No assignment",
PRIMENET.ERROR_INVALID_ASSIGNMENT_KEY: "Invalid assignment key",
PRIMENET.ERROR_INVALID_ASSIGNMENT_TYPE: "Invalid assignment type",
PRIMENET.ERROR_INVALID_RESULT_TYPE: "Invalid result type"}
class Assignment(object):
"""Assignment(work_type, uid, k, b, n, c, sieve_depth, pminus1ed, B1, B2, B2_start, tests_saved, prp_base, prp_residue_type, prp_dblchk, known_factors, ra_failed, cert_squarings)."""
__slots__ = (
"work_type", "uid", "k", "b", "n", "c", "sieve_depth", "pminus1ed",
"B1", "B2", "B2_start", "tests_saved", "prp_base", "prp_residue_type",
"prp_dblchk", "known_factors", "ra_failed", "cert_squarings")
def __init__(self, work_type=None):
"""Create new instance of Assignment(work_type, uid, k, b, n, c, sieve_depth, pminus1ed, B1, B2, B2_start, tests_saved, prp_base, prp_residue_type, prp_dblchk, known_factors, ra_failed, cert_squarings)."""
self.work_type = work_type
self.uid = None
# k*b^n+c
self.k = 1.0
self.b = 2
self.n = 0
self.c = -1
self.sieve_depth = 99.0
self.pminus1ed = 1
self.B1 = 0
self.B2 = 0
self.B2_start = 0
self.tests_saved = 0.0
self.prp_base = 0
self.prp_residue_type = 0
self.prp_dblchk = False
self.known_factors = None
self.ra_failed = False
self.cert_squarings = 0
suffix_power_char = ("", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q")
suffix_power = {"k": 1, "K": 1, "M": 2, "G": 3, "T": 4,
"P": 5, "E": 6, "Z": 7, "Y": 8, "R": 9, "Q": 10}
# yes_regex = re.compile(locale.nl_langinfo(locale.YESEXPR))
yes_regex = re.compile(r"^[yY]")
# no_regex = re.compile(locale.nl_langinfo(locale.NOEXPR))
no_regex = re.compile(r"^[nN]")
# Python 2
if hasattr(__builtins__, "raw_input"):
input = raw_input
def ask_yn(astr, val):
"""Prompt the user with a yes/no question and return their response as a boolean value."""
while True:
temp = input("{0} ({1}): ".format(astr, "Y" if val else "N")).strip()
if not temp:
return val
yes_res = yes_regex.match(temp)
no_res = no_regex.match(temp)
if yes_res or no_res:
return bool(yes_res)
def ask_int(astr, val, amin=None, amax=None, base=0):
"""Prompt the user for an integer input, ensuring the response is within a specified range."""
while True:
temp = input("{0}{1}: ".format(
astr, " ({0!r})".format(val) if val is not None else ""))
if not temp:
return val
try:
newval = int(temp, base)
except ValueError:
print("Please enter a valid number.")
continue
if (amin is None or newval >= amin) and (
amax is None or newval <= amax):
return newval
if amin is not None and amax is not None:
print(
"Please enter a number between {0:n} and {1:n}.".format(amin, amax))
elif amin is not None:
print(
"Please enter a number greater than or equal to {0:n}.".format(amin))
elif amax is not None:
print(
"Please enter a number less than or equal to {0:n}.".format(amax))
def ask_float(astr, val, amin=None, amax=None):
"""Prompt the user for a floating-point number input, ensuring the response is within a specified range."""
while True:
temp = input("{0}{1}: ".format(
astr, " ({0!r})".format(val) if val is not None else ""))
if not temp:
return val
try:
newval = float(temp)
except ValueError:
print("Please enter a valid number.")
continue
if (amin is None or newval >= amin) and (
amax is None or newval <= amax):
return newval
if amin is not None and amax is not None:
print(
"Please enter a number between {0:n} and {1:n}.".format(amin, amax))
elif amin is not None:
print(
"Please enter a number greater than or equal to {0:n}.".format(amin))
elif amax is not None:
print(
"Please enter a number less than or equal to {0:n}.".format(amax))
def ask_str(astr, val, maxlen=0):
"""Prompts for and returns a string input from the user."""
while True:
temp = input("{0}{1}: ".format(
astr, " ({0!r})".format(val) if val else "")).strip()
if not temp:
return val
if not maxlen or len(temp) <= maxlen:
return temp
print("Maximum string length is {0:n} characters.".format(maxlen))
val = temp[:maxlen]
def ask_pass(astr, val):
"""Prompt for a password input from the user, hiding their input for security."""
return getpass.getpass("{0}{1}: ".format(
astr, " ({0})".format("*" * len(val)) if val else "")) or val
def ask_ok():
"""Displays a message and waits for the user to acknowledge it."""
input("\nHit enter to continue: ")
def ask_ok_cancel():
"""Displays a message and returns the user's choice as a boolean."""
return ask_yn("\nAccept the answers above?", True)
def setup():
"""Sets up the configuration for the application."""
wrapper = textwrap.TextWrapper(width=75)
print(wrapper.fill("Welcome to GIMPS, the hunt for huge prime numbers. The program will ask you a few simple questions and then contact the PrimeNet server to get some work for your computer. Good luck!"))
print("\n" + wrapper.fill("Create a GIMPS/PrimeNet account: https://www.mersenne.org/update/ or you may contribute anonymously but it is not recommended."))
userid = ask_str('Your GIMPS/PrimeNet user ID or "ANONYMOUS"',
options.user_id or "ANONYMOUS", 20)
compid = ask_str("Optional computer name", options.computer_id, 20)
if ask_yn("Use a proxy server", False):
print("Use of a proxy is supported, but not (yet) configurable. Please let us know that you need this feature and we can make it configurable.")
if not ask_ok_cancel():
return
if options.user_id != userid:
options.user_id = userid
config.set(SEC.PrimeNet, "username", userid)
if options.computer_id != compid:
options.computer_id = compid
config.set(SEC.PrimeNet, "ComputerID", compid)
program = ask_int("Which GIMPS program are you getting assignments for (1=Mlucas, 2=GpuOwl/PRPLL, 3=CUDALucas)",
3 if options.cudalucas else 2 if options.gpuowl else 1, 1, 3)
if program == 3:
outputfile = ask_str("CUDALucas output filename",
options.cudalucas or "")
hours = ask_int(
"Hours per day you expect the GIMPS program will run", options.cpu_hours, 1, 24)
if not ask_ok_cancel():
return
if options.cpu_hours != hours:
options.cpu_hours = hours
config.set(SEC.PrimeNet, "CPUHours", str(hours))
config.set(SEC.PrimeNet, "RollingAverage", str(1000))
if program == 2:
options.gpuowl = True
config.set(SEC.PrimeNet, "gpuowl", str(True))
elif program == 3:
options.cudalucas = outputfile
config.set(SEC.PrimeNet, "cudalucas", outputfile)
disk = ask_float(
"Configured disk space limit per worker to store the proof interim residues files for PRP tests in GiB/worker (0 to not send)", options.worker_disk_space, 0)
day_night_memory = ask_float(
"Configured day/night P-1 stage 2 memory in GiB", options.day_night_memory / 1024, 0)
archive_dir = ask_str(
"Optional directory to archive PRP proof files after upload", options.archive_dir or "")
if not ask_ok_cancel():
return
threshold = 1.5 * 1000 ** 3
athreshold = threshold / 1024 ** 3
if (not options.worker_disk_space or options.worker_disk_space >=
athreshold) and disk and disk < athreshold:
print(wrapper.fill("Setting disk space limit below {0}B ({1}B) may preclude getting first time prime tests from the PrimeNet server. Consider setting it to 0 instead to not send.".format(
outputunit(threshold), outputunit(threshold, True))))
ask_ok()
# options.worker_disk_space = disk
config.set(SEC.PrimeNet, "WorkerDiskSpace", str(disk))
# options.archive_dir = archive_dir
config.set(SEC.PrimeNet, "ProofArchiveDir", archive_dir)
options.day_night_memory = int(day_night_memory * 1024)
config.set(SEC.PrimeNet, "Memory", str(options.day_night_memory))
num_thread = ask_int(
"Number of workers (CPU cores or GPUs)", options.num_workers, 1)
print("""Use the following values to select a worktype:
4 - P-1 factoring
100 - First time LL tests
101 - Double-check LL tests
102 - World record LL tests
104 - 100 million digit LL tests
150 - First time PRP tests
151 - Double-check PRP tests
152 - World record PRP tests
153 - 100 million digit PRP tests
154 - Smallest available first time PRP that needs P-1 factoring
155 - Double-check using PRP with proof
160 - First time PRP on Mersenne cofactors
161 - Double-check PRP on Mersenne cofactors
""")
print("""Not all worktypes are supported by all the GIMPS programs:
┌──────────┬────────┬────────┬───────┬───────────┬─────────┐
│ Worktype │ Mlucas │ GpuOwl │ PRPLL │ CUDALucas │ CUDAPm1 │
├──────────┴────────┴────────┴───────┴───────────┴─────────┤
│ 4 ✔ ✔ ✔ │
│ 100 ✔ ✔* ✔ │
│ 101 ✔ ✔* ✔ │
│ 102 ✔ ✔* ✔ │
│ 104 ✔ ✔* ✔ │
│ 150 ✔ ✔ ✔ │
│ 151 ✔ ✔ ✔ │
│ 152 ✔ ✔ ✔ │
│ 153 ✔ ✔ ✔ │
│ 154 ✔ ✔* │
│ 155 ✔ ✔ │
│ 160 ✔ │
│ 161 ✔ │
└──────────────────────────────────────────────────────────┘
* Some previous versions of GpuOwl
""")
work_pref = []
for i in range(num_thread):
if num_thread > 1:
print("\nOptions for worker #{0}\n".format(i + 1))
work_pref.append(ask_str("Type of work to get", options.work_preference[i] if i < len(
options.work_preference) else str(PRIMENET.WP_PRP_FIRST)))
if not ask_ok_cancel():
return
if options.num_workers != num_thread:
options.num_workers = num_thread
config.set(SEC.PrimeNet, "NumWorkers", str(num_thread))
options.work_preference = work_pref
work = ask_float("Days of work to queue up", options.days_of_work, 1, 90)
end_dates = ask_int("Hours to wait between sending assignment progress and expected completion dates",
options.hours_between_checkins, 1, 7 * 24)
noise = not (config.getboolean(SEC.PrimeNet, "SilentVictory")
if config.has_option(SEC.PrimeNet, "SilentVictory") else False)
noise = ask_yn("Make noise if a new Mersenne prime is found", noise)
report_100m = ask_yn(
"Report prime results for exponents greater than or equal to 100 million digits", not options.no_report_100m)
if not ask_ok_cancel():
return
options.days_of_work = work
config.set(SEC.PrimeNet, "DaysOfWork", str(work))
# options.hours_between_checkins = end_dates
config.set(SEC.PrimeNet, "HoursBetweenCheckins", str(end_dates))
config.set(SEC.PrimeNet, "SilentVictory", str(not noise))
if not report_100m:
# options.no_report_100m = not report_100m
config.set(SEC.PrimeNet, "no_report_100m", str(not report_100m))
if ask_yn(
"Do you want to set the optional e-mail/text message notification settings?", False):
smtp_server = ask_str(
"SMTP server (hostname and optional port), e.g., 'mail.example.com:465'", options.smtp or "")
tls = ask_yn("Use a secure connection with SSL/TLS?",
True if options.tls is None else options.tls)
starttls = None
if not tls:
starttls = ask_yn("Upgrade to a secure connection with StartTLS?",
True if options.starttls is None else options.starttls)
fromemail = ask_str(
"From e-mail address, e.g., 'User <user@example.com>'", options.fromemail or "")
username = ask_str(
"Optional username for this account, e.g., 'user@example.com'", options.email_username or "")
password = ask_pass(
"Optional password for this account", options.email_password or "")
toemails = []
for i in count():
toemail = ask_str("To e-mail address #{0:n}, e.g., 'User <user@example.com>'".format(i + 1), options.toemails[i]) if i < len(options.toemails) else ask_str(
"To e-mail address #{0:n}, e.g., 'User <user@example.com>' (leave blank {1})".format(i + 1, "to use the From e-mail address" if not i else "to continue"), "")
if not toemail:
break
toemails.append(toemail)
if not ask_ok_cancel():
return
options.smtp = smtp_server
config.set(SEC.Email, "smtp", smtp_server)
if tls:
options.tls = tls
config.set(SEC.Email, "tls", str(tls))
if starttls:
options.starttls = starttls
config.set(SEC.Email, "starttls", str(starttls))
options.fromemail = fromemail
config.set(SEC.Email, "fromemail", fromemail)
options.email_username = username
config.set(SEC.Email, "username", username)
options.email_password = password
config.set(SEC.Email, "password", password)
options.toemails = toemails
config.set(SEC.Email, "toemails", ",".join(toemails))
def readonly_list_file(filename, mode="r"):
"""Reads a file line by line into a list."""
# Used when there is no intention to write the file back, so don't
# check or write lockfiles. Also returns a single string, no list.
try:
with open(filename, mode) as file:
for line in file:
yield line.rstrip()
except (IOError, OSError):
# logging.debug("Error reading {0!r} file.".format(filename))
pass
def write_list_file(filename, lines, mode="w"):
"""Write a list of strings to a file."""
# A "null append" is meaningful, as we can call this to clear the
# lockfile. In this case the main file need not be touched.
if "a" not in mode or lines:
newline = b"\n" if "b" in mode else "\n"
with open(filename, mode) as file:
file.writelines(line + newline for line in lines)
attr_to_copy = {
SEC.PrimeNet:
{"worktodo_file": "workfile", "results_file": "resultsfile",
"logfile": "logfile", "archive_dir": "ProofArchiveDir",
"user_id": "username", "password": "password",
"min_exp": "GetMinExponent", "max_exp": "GetMaxExponent",
"gpuowl": "gpuowl", "cudalucas": "cudalucas",
"num_workers": "NumWorkers", "num_cache":
"num_cache", "days_of_work": "DaysOfWork",
"tests_saved": "tests_saved",
"pm1_multiplier": "pm1_multiplier",
"pm1_bounds": "pm1_bounds",
"no_report_100m": "no_report_100m",
"convert_ll_to_prp": "convert_ll_to_prp",
"convert_prp_to_ll": "convert_prp_to_ll",
"hours_between_checkins": "HoursBetweenCheckins",
"computer_id": "ComputerID", "cpu_brand": "CpuBrand",
"cpu_features": "cpu_features", "cpu_speed": "CpuSpeed",
"memory": "memory", "day_night_memory": "Memory",
"worker_disk_space": "WorkerDiskSpace",
"cpu_l1_cache_size": "L1", "cpu_l2_cache_size": "L2",
"cpu_l3_cache_size": "L3", "num_cores": "NumCores",
"cpu_hyperthreads": "CpuNumHyperthreads",
"cpu_hours": "CPUHours"},
SEC.Email:
{"toemails": "toemails", "fromemail": "fromemail",
"smtp": "smtp", "tls": "tls", "starttls": "starttls",
"email_username": "username", "email_password": "password"}}
def config_read():
"""Reads and parses the configuration settings from a file."""
config = ConfigParser(dict_type=OrderedDict)
config.optionxform = lambda option: option
localfile = os.path.join(workdir, options.localfile)
try:
config.read([localfile])
except ConfigParserError:
logging.exception("ERROR reading {0!r} file:".format(localfile))
for section in (SEC.PrimeNet, SEC.Email, SEC.Internals):
if not config.has_section(section):
# Create the section to avoid having to test for it later
config.add_section(section)
return config
def config_write(config, guid=None):
"""Writes the configuration settings to a file."""
# generate a new local.ini file
if guid is not None: # update the guid if necessary
config.set(SEC.PrimeNet, "ComputerGUID", guid)
localfile = os.path.join(workdir, options.localfile)
with open(localfile, "w") as configfile:
config.write(configfile)
def get_guid(config):
"""Returns the GUID from the config file, or None if it is not present."""
if config.has_option(SEC.PrimeNet, "ComputerGUID"):
return config.get(SEC.PrimeNet, "ComputerGUID")
return None
def create_new_guid():
"""Returns a new globally unique identifier (GUID)."""
return uuid.uuid4().hex
def merge_config_and_options(config, options):
"""Merges command-line options with configuration file settings."""
# getattr and setattr allow access to the options.xxxx values by name
# which allow to copy all of them programmatically instead of having
# one line per attribute. Only the attr_to_copy list need to be updated
# when adding an option you want to copy from argument options to
# local.ini config.
updated = False
for section, value in attr_to_copy.items():
for attr, option in value.items():
# if "attr" has its default value in options, copy it from config
attr_val = getattr(options, attr)
if not hasattr(opts_no_defaults, attr) and config.has_option(
section, option):
# If no option is given and the option exists in local.ini, take it
# from local.ini
if isinstance(attr_val, (list, tuple)):
val = config.get(section, option)
new_val = val.split(",") if val else []
elif isinstance(attr_val, bool):
new_val = config.getboolean(section, option)
else:
new_val = config.get(section, option)
# config file values are always str()
# they need to be converted to the expected type from options
if attr_val is not None:
new_val = type(attr_val)(new_val)
setattr(options, attr, new_val)
elif attr_val is not None:
# If an option is given (even default value) and it is not already
# identical in local.ini, update local.ini
if isinstance(attr_val, (list, tuple)):
new_val = ",".join(map(str, attr_val))
else:
new_val = str(attr_val)
if not config.has_option(section, option) or config.get(
section, option) != new_val:
logging.debug("update {0!r} with {1}={2}".format(
options.localfile, option, "*" * len(new_val) if "password" in option else new_val))
config.set(section, option, new_val)
updated = True
return updated
def is_known_mersenne_prime(p):
"""Returns if a given number is a known Mersenne prime."""
primes = frozenset(
[2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497,
86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269,
2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951,
30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281,
77232917, 82589933])
return p in primes
def is_prime(n):
"""Returns if a given number is prime."""
if n < 2:
return False
if n in {2, 3, 5}:
return True
for p in (2, 3, 5):
if not n % p:
return False
for p in range(7, isqrt(n) + 1, 30):
for i in (0, 4, 6, 10, 12, 16, 22, 24):
if not n % (p + i):
return False
return True
if sys.version_info >= (3, 3):
import decimal
def digits(assignment):
"""Returns the number of digits in the decimal representation of n."""
# Maximum exponent on 32-bit systems: 1,411,819,440 (425,000,000 digits)
exponent = exponent_to_str(assignment)
adigits = int(Decimal(assignment.k).log10() +
assignment.n * Decimal(assignment.b).log10()) + 1
if adigits <= 300000000:
logging.debug(
"Calculating the number of digits for {0}…".format(exponent))
with decimal.localcontext() as ctx:
ctx.prec = decimal.MAX_PREC
ctx.Emax = decimal.MAX_EMAX
ctx.Emin = decimal.MIN_EMIN
ctx.traps[decimal.Inexact] = True
num = str(int(assignment.k) * Decimal(assignment.b)
** assignment.n + assignment.c)
adigits = len(num)
logging.info("The exponent {0} has {1:n} decimal digits: {2}".format(
exponent, adigits, "{0}…{1}".format(num[:10], num[-10:]) if adigits > 30 else num))
else:
logging.info(
"The exponent {0} has approximately {1:n} decimal digits (using formula log10({2.k}) + {2.n} * log10({2.b}) + 1)".format(exponent, adigits, assignment))
return adigits
else:
def digits(assignment):
"""Returns the number of digits in the decimal representation of n."""
adigits = int(Decimal(assignment.k).log10() +
assignment.n * Decimal(assignment.b).log10()) + 1
logging.info("The exponent {0} has approximately {1:n} decimal digits (using formula log10({2.k}) + {2.n} * log10({2.b}) + 1)".format(
exponent_to_str(assignment), adigits, assignment))
return adigits
WORKPATTERN = re.compile(
r'^(?:(?:B1=([0-9]+)(?:,B2=([0-9]+))?|B2=([0-9]+));)?(Test|DoubleCheck|PRP(?:DC)?|P[Ff]actor|P[Mm]inus1|Cert)\s*=\s*(?:(([0-9A-F]{32})|[Nn]/[Aa]|0),)?(?:([-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)|"[0-9]+(?:,[0-9]+)*")(?:,|$)){1,9}$')
Test_RE = re.compile(
r"^(?:(?:B1=[0-9]+(?:,B2=[0-9]+)?|B2=[0-9]+);)?(Test|DoubleCheck)\s*=\s*(?:([0-9A-F]{32}|[Nn]/[Aa]|0),)?([0-9]+)(?:,([0-9]+),([0-9]+))?$")
PRP_RE = re.compile(
r'^(?:(?:B1=[0-9]+(?:,B2=[0-9]+)?|B2=[0-9]+);)?(PRP(?:DC)?)\s*=\s*(?:([0-9A-F]{32}|[Nn]/[Aa]|0),)?([-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)),([0-9]+),([0-9]+),([-+]?[0-9]+)(?:,([0-9]+),([0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:,([0-9]+),([0-9]+))?)?(?:,"([0-9]+(?:,[0-9]+)*)")?$')
PFactor_RE = re.compile(
r'^(?:(?:B1=[0-9]+(?:,B2=[0-9]+)?|B2=[0-9]+);)?(P[Ff]actor)\s*=\s*(?:([0-9A-F]{32}|[Nn]/[Aa]|0),)?([-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)),([0-9]+),([0-9]+),([-+]?[0-9]+),([0-9]+),([0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:,"([0-9]+(?:,[0-9]+)*)")?$')
PMinus1_RE = re.compile(
r'^(P[Mm]inus1)\s*=\s*(?:([0-9A-F]{32}|[Nn]/[Aa]|0),)?([-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)),([0-9]+),([0-9]+),([-+]?[0-9]+),([0-9]+),([0-9]+)(?:,([0-9]+)(?:,([0-9]+))?)?(?:,"([0-9]+(?:,[0-9]+)*)")?$')
Cert_RE = re.compile(
r"^(Cert)\s*=\s*(?:([0-9A-F]{32}|[Nn]/[Aa]|0),)?([-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)),([0-9]+),([0-9]+),([-+]?[0-9]+),([0-9]+)$")
def parse_assignment(task):
"""Parse a line from the workfile into an Assignment."""
# Ex: Test=197ED240A7A41EC575CB408F32DDA661,57600769,74
found = WORKPATTERN.match(task)
if not found:
return None
# logging.debug(task)
assignment = Assignment()
B1, B21, B22, work_type, value, assignment.uid = found.group(
1, 2, 3, 4, 5, 6)
if B1: