forked from Kiv/poclbm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
guiminer.py
2130 lines (1811 loc) · 86.6 KB
/
guiminer.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
"""GUIMiner - graphical frontend to Bitcoin miners.
Currently supports:
- m0mchil's "poclbm"
- puddinpop's "rpcminer"
- jedi95's "Phoenix"
- ufasoft's "bitcoin-miner"
Copyright 2011 Chris MacLeod
This program is released under the GNU GPL. See LICENSE.txt for details.
"""
import sys, os, subprocess, errno, re, threading, logging, time, httplib, urllib
import wx
import json
import collections
import webbrowser
from wx.lib.agw import flatnotebook as fnb
from wx.lib.agw import hyperlink
from wx.lib.newevent import NewEvent
__version__ = '2011-06-09'
def get_module_path():
"""Return the folder containing this script (or its .exe)."""
module_name = sys.executable if hasattr(sys, 'frozen') else __file__
abs_path = os.path.abspath(module_name)
return os.path.dirname(abs_path)
USE_MOCK = '--mock' in sys.argv
# Set up localization; requires the app to be created
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
_ = wx.GetTranslation
LANGUAGES = {
"Chinese Simplified": wx.LANGUAGE_CHINESE_SIMPLIFIED,
"English": wx.LANGUAGE_ENGLISH,
"French": wx.LANGUAGE_FRENCH,
"German": wx.LANGUAGE_GERMAN,
"Hungarian": wx.LANGUAGE_HUNGARIAN,
"Spanish": wx.LANGUAGE_SPANISH,
"Russian": wx.LANGUAGE_RUSSIAN,
}
LANGUAGES_REVERSE = dict((v,k) for (k,v) in LANGUAGES.items())
DONATE_SMALL_URL = 'https://www.mybitcoin.com/sci/paypage.php?t=XFxBkKwtjVYHmQmHzVP1jE_euOoSpMZcXJ5XDtQ1EhISH6nuDWExVwvVYXHQjDC-ApO9Zlwww7tqJnCVP4kBSoaaOdLpyFYSKI9LbTjwnKi-tZEMYKmmfhSqGLWNS_BoVHN0RJFwsQlxKleftmfKG7dpRfQ9or2uX1RE1aWesJA9AsU%2C'
locale = None
language = None
def update_language(new_language):
global locale, language
language = new_language
if locale:
del locale
locale = wx.Locale(language)
if locale.IsOk():
locale.AddCatalogLookupPathPrefix(os.path.join(get_module_path(), "locale"))
locale.AddCatalog("guiminer")
else:
locale = None
def load_language():
language_config = os.path.join(get_module_path(), 'default_language.ini')
language_data = dict()
if os.path.exists(language_config):
with open(language_config) as f:
language_data.update(json.load(f))
language_str = language_data.get('language', "English")
update_language(LANGUAGES.get(language_str, wx.LANGUAGE_ENGLISH))
def save_language():
language_config = os.path.join(get_module_path(), 'default_language.ini')
language_str = LANGUAGES_REVERSE.get(language)
with open(language_config, 'w') as f:
json.dump(dict(language=language_str), f)
load_language()
ABOUT_TEXT = _(
"""GUIMiner
Version: %(version)s
GUI by Chris 'Kiv' MacLeod
Original poclbm miner by m0mchil
Original rpcminer by puddinpop
Get the source code or file issues at GitHub:
https://github.com/Kiv/poclbm
If you enjoyed this software, support its development
by donating to:
%(address)s
Even a single Bitcoin is appreciated and helps motivate
further work on this software.
""")
# Translatable strings that are used repeatedly
STR_NOT_STARTED = _("Not started")
STR_STARTING = _("Starting...")
STR_STOPPED = _("Stopped")
STR_PAUSED = _("Paused")
STR_START_MINING = _("Start mining!")
STR_STOP_MINING = _("Stop mining")
STR_REFRESH_BALANCE = _("Refresh balance")
STR_CONNECTION_ERROR = _("Connection error")
STR_USERNAME = _("Username:")
STR_PASSWORD = _("Password:")
STR_QUIT = _("Quit this program")
STR_ABOUT = _("Show about dialog")
# Alternate backends that we know how to call
SUPPORTED_BACKENDS = [
"rpcminer-4way.exe",
"rpcminer-cpu.exe",
"rpcminer-cuda.exe",
"rpcminer-opencl.exe",
"phoenix.py",
"phoenix.exe",
"bitcoin-miner.exe"
]
USER_AGENT = "guiminer/" + __version__
# Time constants
SAMPLE_TIME_SECS = 3600
REFRESH_RATE_MILLIS = 2000
# Layout constants
LBL_STYLE = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL
BTN_STYLE = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL
# Events sent from the worker threads
(UpdateHashRateEvent, EVT_UPDATE_HASHRATE) = NewEvent()
(UpdateAcceptedEvent, EVT_UPDATE_ACCEPTED) = NewEvent()
(UpdateSoloCheckEvent, EVT_UPDATE_SOLOCHECK) = NewEvent()
(UpdateStatusEvent, EVT_UPDATE_STATUS) = NewEvent()
# Utility functions
def merge_whitespace(s):
"""Combine multiple whitespace characters found in s into one."""
s = re.sub(r"( +)|\t+", " ", s)
return s.strip()
def get_opencl_devices():
"""Return a list of available OpenCL devices.
Raises ImportError if OpenCL is not found.
Raises IOError if no OpenCL devices are found.
"""
import pyopencl
device_strings = []
platforms = pyopencl.get_platforms() #@UndefinedVariable
for i, platform in enumerate(platforms):
devices = platform.get_devices()
for j, device in enumerate(devices):
device_strings.append('[%d-%d] %s' %
(i, j, merge_whitespace(device.name)[:25]))
if len(device_strings) == 0:
raise IOError
return device_strings
def get_icon_bundle():
"""Return the Bitcoin program icon bundle."""
return wx.IconBundleFromFile("logo.ico", wx.BITMAP_TYPE_ICO)
def get_taskbar_icon():
"""Return the taskbar icon.
This works around Window's annoying behavior of ignoring the 16x16 image
and using nearest neighbour downsampling on the 32x32 image instead."""
ib = get_icon_bundle()
return ib.GetIcon((16,16))
def mkdir_p(path):
"""If the directory 'path' doesn't exist, create it. Same as mkdir -p."""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
def add_tooltip(widget, text):
"""Add a tooltip to widget with the specified text."""
tooltip = wx.ToolTip(text)
widget.SetToolTip(tooltip)
def format_khash(rate):
"""Format rate for display. A rate of 0 means just connected."""
if rate > 10**6:
return _("%.1f Ghash/s") % (rate / 1000000.)
if rate > 10**3:
return _("%.1f Mhash/s") % (rate / 1000.)
elif rate == 0:
return _("Connecting...")
else:
return _("%d khash/s") % rate
def format_balance(amount):
"""Format a quantity of Bitcoins in BTC."""
return "%.3f BTC" % float(amount)
def init_logger():
"""Set up and return the logging object and custom formatter."""
logger = logging.getLogger("poclbm-gui")
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(
os.path.join(get_module_path(), 'guiminer.log'), 'w')
formatter = logging.Formatter("%(asctime)s: %(message)s",
"%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger, formatter
logger, formatter = init_logger()
def http_request(hostname, *args):
"""Do a HTTP request and return the response data."""
try:
conn = httplib.HTTPConnection(hostname)
logger.debug(_("Requesting balance: %(request)s"), dict(request=args))
conn.request(*args)
response = conn.getresponse()
data = response.read()
logger.debug(_("Server replied: %(status)s, %(data)s"),
dict(status=str(response.status), data=data))
return response, data
finally:
conn.close()
class ConsolePanel(wx.Panel):
"""Panel that displays logging events.
Uses with a StreamHandler to log events to a TextCtrl. Thread-safe.
"""
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
self.parent = parent
vbox = wx.BoxSizer(wx.VERTICAL)
style = wx.TE_MULTILINE | wx.TE_READONLY | wx.HSCROLL
self.text = wx.TextCtrl(self, -1, "", style=style)
vbox.Add(self.text, 1, wx.EXPAND)
self.SetSizer(vbox)
self.handler = logging.StreamHandler(self)
formatter = logging.Formatter("%(asctime)s: %(message)s",
"%Y-%m-%d %H:%M:%S")
self.handler.setFormatter(formatter)
logger.addHandler(self.handler)
def on_focus(self):
"""On focus, clear the status bar."""
self.parent.statusbar.SetStatusText("", 0)
self.parent.statusbar.SetStatusText("", 1)
def on_close(self):
"""On closing, stop handling logging events."""
logger.removeHandler(self.handler)
def write(self, text):
"""Forward logging events to our TextCtrl."""
wx.CallAfter(self.text.AppendText, text)
class SummaryPanel(wx.Panel):
"""Panel that displays a summary of all miners."""
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
self.parent = parent
self.timer = wx.Timer(self)
self.timer.Start(REFRESH_RATE_MILLIS)
self.Bind(wx.EVT_TIMER, self.on_timer)
flags = wx.ALIGN_CENTER_HORIZONTAL | wx.ALL
border = 5
self.column_headers = [
(wx.StaticText(self, -1, _("Miner")), 0, flags, border),
(wx.StaticText(self, -1, _("Speed")), 0, flags, border),
(wx.StaticText(self, -1, _("Accepted")), 0, flags, border),
(wx.StaticText(self, -1, _("Stale")), 0, flags, border),
(wx.StaticText(self, -1, _("Start/Stop")), 0, flags, border),
(wx.StaticText(self, -1, _("Autostart")), 0, flags, border),
]
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
font.SetUnderlined(True)
for st in self.column_headers:
st[0].SetFont(font)
self.grid = wx.FlexGridSizer(0, len(self.column_headers), 2, 2)
self.grid.AddMany(self.column_headers)
self.add_miners_to_grid()
self.grid.AddGrowableCol(0)
self.grid.AddGrowableCol(1)
self.grid.AddGrowableCol(2)
self.grid.AddGrowableCol(3)
self.SetSizer(self.grid)
def add_miners_to_grid(self):
"""Add a summary row for each miner to the summary grid."""
# Remove any existing widgets except the column headers.
for i in reversed(range(len(self.column_headers), len(self.grid.GetChildren()))):
self.grid.Hide(i)
self.grid.Remove(i)
for p in self.parent.profile_panels:
p.clear_summary_widgets()
self.grid.AddMany(p.get_summary_widgets(self))
self.grid.Layout()
def on_close(self):
self.timer.Stop()
def on_timer(self, event=None):
"""Whenever the timer goes off, fefresh the summary data."""
if self.parent.nb.GetSelection() != self.parent.nb.GetPageIndex(self):
return
for p in self.parent.profile_panels:
p.update_summary()
self.parent.statusbar.SetStatusText("", 0) # TODO: show something
total_rate = sum(p.last_rate for p in self.parent.profile_panels
if p.is_mining)
if any(p.is_mining for p in self.parent.profile_panels):
self.parent.statusbar.SetStatusText(format_khash(total_rate), 1)
else:
self.parent.statusbar.SetStatusText("", 1)
def on_focus(self):
"""On focus, show the statusbar text."""
self.on_timer()
class GUIMinerTaskBarIcon(wx.TaskBarIcon):
"""Taskbar icon for the GUI.
Shows status messages on hover and opens on click.
"""
TBMENU_RESTORE = wx.NewId()
TBMENU_PAUSE = wx.NewId()
TBMENU_CLOSE = wx.NewId()
TBMENU_CHANGE = wx.NewId()
TBMENU_REMOVE = wx.NewId()
def __init__(self, frame):
wx.TaskBarIcon.__init__(self)
self.frame = frame
self.icon = get_taskbar_icon()
self.timer = wx.Timer(self)
self.timer.Start(REFRESH_RATE_MILLIS)
self.is_paused = False
self.SetIcon(self.icon, "GUIMiner")
self.imgidx = 1
self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.on_taskbar_activate)
self.Bind(wx.EVT_MENU, self.on_taskbar_activate, id=self.TBMENU_RESTORE)
self.Bind(wx.EVT_MENU, self.on_taskbar_close, id=self.TBMENU_CLOSE)
self.Bind(wx.EVT_MENU, self.on_pause, id=self.TBMENU_PAUSE)
self.Bind(wx.EVT_TIMER, self.on_timer)
def CreatePopupMenu(self):
"""Override from wx.TaskBarIcon. Creates the right-click menu."""
menu = wx.Menu()
menu.AppendCheckItem(self.TBMENU_PAUSE, _("Pause all"))
menu.Check(self.TBMENU_PAUSE, self.is_paused)
menu.Append(self.TBMENU_RESTORE, _("Restore"))
menu.Append(self.TBMENU_CLOSE, _("Close"))
return menu
def on_taskbar_activate(self, evt):
if self.frame.IsIconized():
self.frame.Iconize(False)
if not self.frame.IsShown():
self.frame.Show(True)
self.frame.Raise()
def on_taskbar_close(self, evt):
wx.CallAfter(self.frame.Close, force=True)
def on_timer(self, event):
"""Refresh the taskbar icon's status message."""
objs = self.frame.profile_panels
if objs:
text = '\n'.join(p.get_taskbar_text() for p in objs)
self.SetIcon(self.icon, text)
def on_pause(self, event):
"""Pause or resume the currently running miners."""
self.is_paused = event.Checked()
for miner in self.frame.profile_panels:
if self.is_paused:
miner.pause()
else:
miner.resume()
class MinerListenerThread(threading.Thread):
LINES = [
(r"Target =|average rate|Sending to server|found hash!",
lambda _: None), # Just ignore lines like these
(r"accepted|\"result\":\s*true",
lambda _: UpdateAcceptedEvent(accepted=True)),
(r"invalid|stale", lambda _:
UpdateAcceptedEvent(accepted=False)),
(r"(\d+)\s*khash/s", lambda match:
UpdateHashRateEvent(rate=int(match.group(1)))),
(r"(\d+\.\d+)\s*Mhash/s", lambda match:
UpdateHashRateEvent(rate=float(match.group(1)) * 1000)),
(r"(\d+)\s*Mhash/s", lambda match:
UpdateHashRateEvent(rate=int(match.group(1)) * 1000)),
(r"checking (\d+)", lambda _:
UpdateSoloCheckEvent()),
]
def __init__(self, parent, miner):
threading.Thread.__init__(self)
self.shutdown_event = threading.Event()
self.parent = parent
self.parent_name = parent.name
self.miner = miner
def run(self):
logger.info(_('Listener for "%s" started') % self.parent_name)
while not self.shutdown_event.is_set():
line = self.miner.stdout.readline().strip()
#logger.debug("Line: %s", line)
if not line: continue
for s, event_func in self.LINES: # Use self to allow subclassing
match = re.search(s, line, flags=re.I)
if match is not None:
event = event_func(match)
if event is not None:
wx.PostEvent(self.parent, event)
break
else:
# Possible error or new message, just pipe it through
event = UpdateStatusEvent(text=line)
logger.info(_('Listener for "%(name)s": %(line)s'),
dict(name=self.parent_name, line=line))
wx.PostEvent(self.parent, event)
logger.info(_('Listener for "%s" shutting down'), self.parent_name)
class PhoenixListenerThread(MinerListenerThread):
LINES = [
(r"Result: .* accepted",
lambda _: UpdateAcceptedEvent(accepted=True)),
(r"Result: .* rejected", lambda _:
UpdateAcceptedEvent(accepted=False)),
(r"(\d+)\.?(\d*) Khash/sec", lambda match:
UpdateHashRateEvent(rate=float(match.group(1)+'.'+match.group(2)))),
(r"(\d+)\.?(\d*) Mhash/sec", lambda match:
UpdateHashRateEvent(rate=float(match.group(1)+'.'+match.group(2)) * 1000)),
(r"Currently on block",
lambda _: None), # Just ignore lines like these
]
class MinerTab(wx.Panel):
"""A tab in the GUI representing a miner instance.
Each MinerTab has these responsibilities:
- Persist its data to and from the config file
- Launch a backend subprocess and monitor its progress
by creating a MinerListenerThread.
- Post updates to the GUI's statusbar & summary panel; the format depends
whether the backend is working solo or in a pool.
"""
def __init__(self, parent, id, devices, servers, defaults, statusbar, data):
wx.Panel.__init__(self, parent, id)
self.parent = parent
self.servers = servers
self.defaults = defaults
self.statusbar = statusbar
self.is_mining = False
self.is_paused = False
self.is_possible_error = False
self.miner = None # subprocess.Popen instance when mining
self.miner_listener = None # MinerListenerThread when mining
self.solo_blocks_found = 0
self.accepted_shares = 0 # shares for pool, diff1 hashes for solo
self.accepted_times = collections.deque()
self.invalid_shares = 0
self.invalid_times = collections.deque()
self.last_rate = 0 # units of khash/s
self.autostart = False
self.server_lbl = wx.StaticText(self, -1, _("Server:"))
self.summary_panel = None # SummaryPanel instance if summary open
self.server = wx.ComboBox(self, -1,
choices=[s['name'] for s in servers],
style=wx.CB_READONLY)
self.website_lbl = wx.StaticText(self, -1, _("Website:"))
self.website = hyperlink.HyperLinkCtrl(self, -1, "")
self.external_lbl = wx.StaticText(self, -1, _("Ext. Path:"))
self.txt_external = wx.TextCtrl(self, -1, "")
self.host_lbl = wx.StaticText(self, -1, _("Host:"))
self.txt_host = wx.TextCtrl(self, -1, "")
self.port_lbl = wx.StaticText(self, -1, _("Port:"))
self.txt_port = wx.TextCtrl(self, -1, "")
self.user_lbl = wx.StaticText(self, -1, STR_USERNAME)
self.txt_username = wx.TextCtrl(self, -1, "")
self.pass_lbl = wx.StaticText(self, -1, STR_PASSWORD)
self.txt_pass = wx.TextCtrl(self, -1, "", style=wx.TE_PASSWORD)
self.device_lbl = wx.StaticText(self, -1, _("Device:"))
self.device_listbox = wx.ComboBox(self, -1, choices=devices or [_("No OpenCL devices")], style=wx.CB_READONLY)
self.flags_lbl = wx.StaticText(self, -1, _("Extra flags:"))
self.txt_flags = wx.TextCtrl(self, -1, "")
self.extra_info = wx.StaticText(self, -1, "")
self.balance_lbl = wx.StaticText(self, -1, _("Balance:"))
self.balance_amt = wx.StaticText(self, -1, "0")
self.balance_refresh = wx.Button(self, -1, STR_REFRESH_BALANCE)
self.balance_refresh_timer = wx.Timer()
self.withdraw = wx.Button(self, -1, _("Withdraw"))
self.balance_cooldown_seconds = 0
self.balance_auth_token = ""
self.labels = [self.server_lbl, self.website_lbl,
self.host_lbl, self.port_lbl,
self.user_lbl, self.pass_lbl,
self.device_lbl, self.flags_lbl,
self.balance_lbl]
self.txts = [self.txt_host, self.txt_port,
self.txt_username, self.txt_pass,
self.txt_flags]
self.all_widgets = [self.server, self.website,
self.device_listbox,
self.balance_amt,
self.balance_refresh,
self.withdraw] + self.labels + self.txts
self.hidden_widgets = [self.extra_info,
self.txt_external,
self.external_lbl]
self.start = wx.Button(self, -1, STR_START_MINING)
self.device_listbox.SetSelection(0)
self.server.SetStringSelection(self.defaults.get('default_server'))
self.set_data(data)
for txt in self.txts:
txt.Bind(wx.EVT_KEY_UP, self.check_if_modified)
self.device_listbox.Bind(wx.EVT_COMBOBOX, self.check_if_modified)
self.start.Bind(wx.EVT_BUTTON, self.toggle_mining)
self.server.Bind(wx.EVT_COMBOBOX, self.on_select_server)
self.balance_refresh_timer.Bind(wx.EVT_TIMER, self.on_balance_cooldown_tick)
self.balance_refresh.Bind(wx.EVT_BUTTON, self.on_balance_refresh)
self.withdraw.Bind(wx.EVT_BUTTON, self.on_withdraw)
self.Bind(EVT_UPDATE_HASHRATE, lambda event: self.update_khash(event.rate))
self.Bind(EVT_UPDATE_ACCEPTED, lambda event: self.update_shares(event.accepted))
self.Bind(EVT_UPDATE_STATUS, lambda event: self.update_status(event.text))
self.Bind(EVT_UPDATE_SOLOCHECK, lambda event: self.update_solo())
self.update_statusbar()
self.clear_summary_widgets()
@property
def last_update_time(self):
"""Return the local time of the last accepted share."""
if self.accepted_times:
return time.localtime(self.accepted_times[-1])
return None
@property
def server_config(self):
hostname = self.txt_host.GetValue()
return self.get_server_by_field(hostname, 'host')
@property
def is_solo(self):
"""Return True if this miner is configured for solo mining."""
return self.server.GetStringSelection() == "solo"
@property
def is_modified(self):
"""Return True if this miner has unsaved changes pending."""
return self.last_data != self.get_data()
@property
def external_path(self):
"""Return the path to an external miner, or "" if none is present."""
return self.txt_external.GetValue()
@property
def is_external_miner(self):
"""Return True if this miner has an external path configured."""
return self.txt_external.GetValue() != ""
@property
def host_with_http_prefix(self):
"""Return the host address, with http:// prepended if needed."""
host = self.txt_host.GetValue()
if not host.startswith("http://"):
host = "http://" + host
return host
@property
def host_without_http_prefix(self):
"""Return the host address, with http:// stripped off if needed."""
host = self.txt_host.GetValue()
if host.startswith("http://"):
return host[len('http://'):]
return host
@property
def device_index(self):
"""Return the index of the currently selected OpenCL device."""
s = self.device_listbox.GetStringSelection()
match = re.search(r'\[(\d+)-(\d+)\]', s)
assert match is not None
return int(match.group(2))
@property
def platform_index(self):
"""Return the index of the currently selected OpenCL platform."""
s = self.device_listbox.GetStringSelection()
match = re.search(r'\[(\d+)-(\d+)\]', s)
assert match is not None
return int(match.group(1))
@property
def is_device_visible(self):
"""Return True if we are using a backend with device selection."""
NO_DEVICE_SELECTION = ['rpcminer', 'bitcoin-miner']
return not any(d in self.external_path for d in NO_DEVICE_SELECTION)
def pause(self):
"""Pause the miner if we are mining, otherwise do nothing."""
if self.is_mining:
self.stop_mining()
self.is_paused = True
def resume(self):
"""Resume the miner if we are paused, otherwise do nothing."""
if self.is_paused:
self.start_mining()
self.is_paused = False
def get_data(self):
"""Return a dict of our profile data."""
return dict(name=self.name,
hostname=self.txt_host.GetValue(),
port=self.txt_port.GetValue(),
username=self.txt_username.GetValue(),
password=self.txt_pass.GetValue(),
device=self.device_listbox.GetSelection(),
flags=self.txt_flags.GetValue(),
autostart=self.autostart,
balance_auth_token=self.balance_auth_token,
external_path=self.external_path)
def set_data(self, data):
"""Set our profile data to the information in data. See get_data()."""
self.last_data = data
default_server_config = self.get_server_by_field(
self.defaults['default_server'], 'name')
self.name = (data.get('name') or _('Default'))
# Backwards compatibility: hostname key used to be called server.
# We only save out hostname now but accept server from old INI files.
hostname = (data.get('hostname') or
data.get('server') or
default_server_config['host'])
self.txt_host.SetValue(hostname)
self.server.SetStringSelection(self.server_config.get('name', "Other"))
self.txt_username.SetValue(
data.get('username') or
self.defaults.get('default_username', ''))
self.txt_pass.SetValue(
data.get('password') or
self.defaults.get('default_password', ''))
self.txt_port.SetValue(str(
data.get('port') or
self.server_config.get('port', 8332)))
self.txt_flags.SetValue(data.get('flags', ''))
self.autostart = data.get('autostart', False)
self.txt_external.SetValue(data.get('external_path', ''))
# Handle case where they removed devices since last run.
device_index = data.get('device', None)
if device_index is not None and device_index < self.device_listbox.GetCount():
self.device_listbox.SetSelection(device_index)
self.change_server(self.server_config)
self.balance_auth_token = data.get('balance_auth_token', '')
def clear_summary_widgets(self):
"""Release all our summary widgets."""
self.summary_name = None
self.summary_status = None
self.summary_shares_accepted = None
self.summary_shares_stale = None
self.summary_start = None
self.summary_autostart = None
def get_start_stop_state(self):
"""Return appropriate text for the start/stop button."""
return _("Stop") if self.is_mining else _("Start")
def get_start_label(self):
return STR_STOP_MINING if self.is_mining else STR_START_MINING
def update_summary(self):
"""Update our summary fields if possible."""
if not self.summary_panel:
return
self.summary_name.SetLabel(self.name)
if self.is_paused:
text = STR_PAUSED
elif not self.is_mining:
text = STR_STOPPED
elif self.is_possible_error:
text = _("Connection problems")
else:
text = format_khash(self.last_rate)
self.summary_status.SetLabel(text)
self.summary_shares_accepted.SetLabel("%d (%d)" %
(self.accepted_shares, len(self.accepted_times)))
if self.is_solo:
self.summary_shares_invalid.SetLabel("-")
else:
self.summary_shares_invalid.SetLabel("%d (%d)" %
(self.invalid_shares, len(self.invalid_times)))
self.summary_start.SetLabel(self.get_start_stop_state())
self.summary_autostart.SetValue(self.autostart)
self.summary_panel.grid.Layout()
def get_summary_widgets(self, summary_panel):
"""Return a list of summary widgets suitable for sizer.AddMany."""
self.summary_panel = summary_panel
self.summary_name = wx.StaticText(summary_panel, -1, self.name)
self.summary_name.Bind(wx.EVT_LEFT_UP, self.show_this_panel)
self.summary_status = wx.StaticText(summary_panel, -1, STR_STOPPED)
self.summary_shares_accepted = wx.StaticText(summary_panel, -1, "0")
self.summary_shares_invalid = wx.StaticText(summary_panel, -1, "0")
self.summary_start = wx.Button(summary_panel, -1, self.get_start_stop_state(), style=wx.BU_EXACTFIT)
self.summary_start.Bind(wx.EVT_BUTTON, self.toggle_mining)
self.summary_autostart = wx.CheckBox(summary_panel, -1)
self.summary_autostart.Bind(wx.EVT_CHECKBOX, self.toggle_autostart)
self.summary_autostart.SetValue(self.autostart)
return [
(self.summary_name, 0, wx.ALIGN_CENTER_HORIZONTAL),
(self.summary_status, 0, wx.ALIGN_CENTER_HORIZONTAL, 0),
(self.summary_shares_accepted, 0, wx.ALIGN_CENTER_HORIZONTAL, 0),
(self.summary_shares_invalid, 0, wx.ALIGN_CENTER_HORIZONTAL, 0),
(self.summary_start, 0, wx.ALIGN_CENTER, 0),
(self.summary_autostart, 0, wx.ALIGN_CENTER, 0)
]
def show_this_panel(self, event):
"""Set focus to this panel."""
self.parent.SetSelection(self.parent.GetPageIndex(self))
def toggle_autostart(self, event):
self.autostart = event.IsChecked()
def toggle_mining(self, event):
"""Stop or start the miner."""
if self.is_mining:
self.stop_mining()
else:
self.start_mining()
self.update_summary()
#############################
# Begin backend specific code
def configure_subprocess_poclbm(self):
"""Set up the command line for poclbm."""
folder = get_module_path()
if USE_MOCK:
executable = "python mockBitcoinMiner.py"
else:
if hasattr(sys, 'frozen'):
executable = "poclbm.exe"
else:
executable = "python poclbm.py"
cmd = "%s --user=%s --pass=%s -o %s -p %s --device=%d --platform=%d --verbose %s" % (
executable,
self.txt_username.GetValue(),
self.txt_pass.GetValue(),
self.txt_host.GetValue(),
self.txt_port.GetValue(),
self.device_index,
self.platform_index,
self.txt_flags.GetValue()
)
return cmd, folder
def configure_subprocess_rpcminer(self):
"""Set up the command line for rpcminer.
The hostname must start with http:// for these miners.
"""
cmd = "%s -user=%s -password=%s -url=%s:%s %s" % (
self.external_path,
self.txt_username.GetValue(),
self.txt_pass.GetValue(),
self.host_with_http_prefix,
self.txt_port.GetValue(),
self.txt_flags.GetValue()
)
return cmd, os.path.dirname(self.external_path)
def configure_subprocess_ufasoft(self):
"""Set up the command line for ufasoft's SSE2 miner.
The hostname must start with http:// for these miners.
"""
cmd = "%s -u %s -p %s -o %s:%s %s" % (
self.external_path,
self.txt_username.GetValue(),
self.txt_pass.GetValue(),
self.host_with_http_prefix,
self.txt_port.GetValue(),
self.txt_flags.GetValue())
return cmd, os.path.dirname(self.external_path)
def configure_subprocess_phoenix(self):
"""Set up the command line for phoenix miner."""
path = self.external_path
if path.endswith('.py'):
path = "python " + path
cmd = "%s -u http://%s:%s@%s:%s PLATFORM=%d DEVICE=%d %s" % (
path,
self.txt_username.GetValue(),
self.txt_pass.GetValue(),
self.host_without_http_prefix,
self.txt_port.GetValue(),
self.platform_index,
self.device_index,
self.txt_flags.GetValue())
return cmd, os.path.dirname(self.external_path)
# End backend specific code
###########################
def start_mining(self):
"""Launch a miner subprocess and attach a MinerListenerThread."""
self.is_paused = False
# Avoid showing a console window when frozen
try: import win32process
except ImportError: flags = 0
else: flags = win32process.CREATE_NO_WINDOW
# Determine what command line arguments to use
listener_cls = MinerListenerThread
if not self.is_external_miner:
conf_func = self.configure_subprocess_poclbm
elif "rpcminer" in self.external_path:
conf_func = self.configure_subprocess_rpcminer
elif "bitcoin-miner" in self.external_path:
conf_func = self.configure_subprocess_ufasoft
elif "phoenix" in self.external_path:
conf_func = self.configure_subprocess_phoenix
listener_cls = PhoenixListenerThread
else:
raise ValueError # TODO: handle unrecognized miner
cmd, cwd = conf_func()
# for ufasoft:
# redirect stderr to stdout
# use universal_newlines to catch the \r output on Mhash/s lines
try:
logger.debug(_('Running command: ') + cmd)
self.miner = subprocess.Popen(cmd, cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
creationflags=flags,
shell=(sys.platform != 'win32'))
except OSError:
raise #TODO: the folder or exe could not exist
self.miner_listener = listener_cls(self, self.miner)
self.miner_listener.daemon = True
self.miner_listener.start()
self.is_mining = True
self.set_status(STR_STARTING, 1)
self.start.SetLabel(self.get_start_label())
def on_close(self):
"""Prepare to close gracefully."""
self.stop_mining()
self.balance_refresh_timer.Stop()
def stop_mining(self):
"""Terminate the poclbm process if able and its associated listener."""
if self.miner is not None:
if self.miner.returncode is None:
# It didn't return yet so it's still running.
try:
self.miner.terminate()
except OSError:
pass # TODO: Guess it wasn't still running?
self.miner = None
if self.miner_listener is not None:
self.miner_listener.shutdown_event.set()
self.miner_listener = None
self.is_mining = False
self.is_paused = False
self.set_status(STR_STOPPED, 1)
self.start.SetLabel(self.get_start_label())
def update_khash(self, rate):
"""Update our rate according to a report from the listener thread.
If we are receiving rate messages then it means poclbm is no longer
reporting errors.
"""
self.last_rate = rate
self.set_status(format_khash(rate), 1)
if self.is_possible_error:
self.update_statusbar()
self.is_possible_error = False
def update_statusbar(self):
"""Show the shares or equivalent on the statusbar."""
if self.is_solo:
text = _("Difficulty 1 hashes: %(nhashes)d %(update_time)s") % \
dict(nhashes=self.accepted_shares,
update_time=self.format_last_update_time())
if self.solo_blocks_found > 0:
block_text = _("Blocks: %d, ") % self.solo_blocks_found
text = block_text + text
else:
text = _("Shares: %d accepted") % self.accepted_shares
if self.invalid_shares > 0:
text += _(", %d stale/invalid") % self.invalid_shares
text += " %s" % self.format_last_update_time()
self.set_status(text, 0)
def update_last_time(self, accepted):
"""Set the last update time to now (in local time)."""
now = time.time()
if accepted:
self.accepted_times.append(now)
while now - self.accepted_times[0] > SAMPLE_TIME_SECS:
self.accepted_times.popleft()
else:
self.invalid_times.append(now)
while now - self.invalid_times[0] > SAMPLE_TIME_SECS:
self.invalid_times.popleft()
def format_last_update_time(self):
"""Format last update time for display."""
time_fmt = '%I:%M:%S%p'
if self.last_update_time is None:
return ""
return _("- last at %s") % time.strftime(time_fmt, self.last_update_time)
def update_shares(self, accepted):
"""Update our shares with a report from the listener thread."""
if self.is_solo and accepted:
self.solo_blocks_found += 1
elif accepted:
self.accepted_shares += 1
else:
self.invalid_shares += 1
self.update_last_time(accepted)
self.update_statusbar()
def update_status(self, msg):
"""Update our status with a report from the listener thread.
If we receive a message from poclbm we don't know how to interpret,
it's probably some kind of error state - in this case the best
thing to do is just show it to the user on the status bar.
"""
self.set_status(msg)
self.is_possible_error = True
def set_status(self, msg, index=0):
"""Set the current statusbar text, but only if we have focus."""
if self.parent.GetSelection() == self.parent.GetPageIndex(self):
self.statusbar.SetStatusText(msg, index)