-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.rs
1919 lines (1832 loc) · 75.9 KB
/
main.rs
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
// Gupax - GUI Uniting P2Pool And XMRig
//
// Copyright (c) 2022-2023 hinto-janai
//
// 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 3 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. If not, see <https://www.gnu.org/licenses/>.
// Hide console in Windows
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
//---------------------------------------------------------------------------------------------------- Imports
// egui/eframe
use egui::{
TextStyle::*,
color::Color32,
FontFamily::Proportional,
TextStyle,Spinner,
Layout,Align,
FontId,Label,RichText,Stroke,Vec2,Button,SelectableLabel,
Key,Modifiers,TextEdit,
CentralPanel,TopBottomPanel,
Hyperlink,
};
use egui_extras::RetainedImage;
use eframe::{egui,NativeOptions};
// Logging
use log::*;
use env_logger::{Builder,WriteStyle};
// Regex
use ::regex::Regex;
// Serde
use serde::{Serialize,Deserialize};
// std
use std::{
env,
io::Write,
process::exit,
sync::{Arc,Mutex},
time::Instant,
path::PathBuf,
};
// Sysinfo
use sysinfo::SystemExt;
use sysinfo::CpuExt;
// Modules
//mod benchmark;
mod ferris;
mod constants;
mod node;
mod disk;
mod status;
mod gupax;
mod p2pool;
mod xmrig;
mod update;
mod helper;
mod human;
mod regex;
mod xmr;
mod macros;
use {macros::*,crate::regex::*,ferris::*,constants::*,node::*,disk::*,update::*,gupax::*,helper::*};
// Sudo (dummy values for Windows)
mod sudo;
use crate::sudo::*;
#[cfg(target_family = "unix")]
extern crate sudo as sudo_check;
//---------------------------------------------------------------------------------------------------- Struct + Impl
// The state of the outer main [App].
// See the [State] struct in [state.rs] for the
// actual inner state of the tab settings.
pub struct App {
// Misc state
tab: Tab, // What tab are we on?
width: f32, // Top-level width
height: f32, // Top-level height
// Alpha (transparency)
// This value is used to incrementally increase/decrease
// the transparency when resizing. Basically, it fades
// in/out of black to hide jitter when resizing with [init_text_styles()]
alpha: u8,
// This is a one time trigger so [init_text_styles()] isn't
// called 60x a second when resizing the window. Instead,
// it only gets called if this bool is true and the user
// is hovering over egui (ctx.is_pointer_over_area()).
must_resize: bool, // Sets the flag so we know to [init_text_styles()]
resizing: bool, // Are we in the process of resizing? (For black fade in/out)
// State
og: Arc<Mutex<State>>, // og = Old state to compare against
state: State, // state = Working state (current settings)
update: Arc<Mutex<Update>>, // State for update data [update.rs]
file_window: Arc<Mutex<FileWindow>>, // State for the path selector in [Gupax]
ping: Arc<Mutex<Ping>>, // Ping data found in [node.rs]
og_node_vec: Vec<(String, Node)>, // Manual Node database
node_vec: Vec<(String, Node)>, // Manual Node database
og_pool_vec: Vec<(String, Pool)>, // Manual Pool database
pool_vec: Vec<(String, Pool)>, // Manual Pool database
diff: bool, // This bool indicates state changes
// Restart state:
// If Gupax updated itself, this represents that the
// user should (but isn't required to) restart Gupax.
restart: Arc<Mutex<Restart>>,
// Error State:
// These values are essentially global variables that
// indicate if an error message needs to be displayed
// (it takes up the whole screen with [error_msg] and buttons for ok/quit/etc)
error_state: ErrorState,
// Helper/API State:
// This holds everything related to the data processed by the "helper thread".
// This includes the "helper" threads public P2Pool/XMRig's API.
helper: Arc<Mutex<Helper>>, // [Helper] state, mostly for Gupax uptime
pub_sys: Arc<Mutex<Sys>>, // [Sys] state, read by [Status], mutated by [Helper]
p2pool: Arc<Mutex<Process>>, // [P2Pool] process state
xmrig: Arc<Mutex<Process>>, // [XMRig] process state
p2pool_api: Arc<Mutex<PubP2poolApi>>, // Public ready-to-print P2Pool API made by the "helper" thread
xmrig_api: Arc<Mutex<PubXmrigApi>>, // Public ready-to-print XMRig API made by the "helper" thread
p2pool_img: Arc<Mutex<ImgP2pool>>, // A one-time snapshot of what data P2Pool started with
xmrig_img: Arc<Mutex<ImgXmrig>>, // A one-time snapshot of what data XMRig started with
// STDIN Buffer
p2pool_stdin: String, // The buffer between the p2pool console and the [Helper]
xmrig_stdin: String, // The buffer between the xmrig console and the [Helper]
// Sudo State
sudo: Arc<Mutex<SudoState>>, // This is just a dummy struct on [Windows].
// State from [--flags]
no_startup: bool,
// Gupax-P2Pool API
// Gupax's P2Pool API (e.g: ~/.local/share/gupax/p2pool/)
// This is a file-based API that contains data for permanent stats.
// The below struct holds everything needed for it, the paths, the
// actual stats, and all the functions needed to mutate them.
gupax_p2pool_api: Arc<Mutex<GupaxP2poolApi>>,
// Static stuff
benchmarks: Vec<Benchmark>, // XMRig CPU benchmarks
pid: sysinfo::Pid, // Gupax's PID
max_threads: usize, // Max amount of detected system threads
now: Instant, // Internal timer
exe: String, // Path for [Gupax] binary
dir: String, // Directory [Gupax] binary is in
resolution: Vec2, // Frame resolution
os: &'static str, // OS
admin: bool, // Are we admin? (for Windows)
os_data_path: PathBuf, // OS data path (e.g: ~/.local/share/gupax/)
gupax_p2pool_api_path: PathBuf, // Gupax-P2Pool API path (e.g: ~/.local/share/gupax/p2pool/)
state_path: PathBuf, // State file path
node_path: PathBuf, // Node file path
pool_path: PathBuf, // Pool file path
version: &'static str, // Gupax version
name_version: String, // [Gupax vX.X.X]
img: Images, // Custom Struct holding pre-compiled bytes of [Images]
regex: Regexes, // Custom Struct holding pre-made [Regex]'s
}
impl App {
fn cc(cc: &eframe::CreationContext<'_>, app: Self) -> Self {
let resolution = cc.integration_info.window_info.size;
init_text_styles(&cc.egui_ctx, resolution[0]);
Self {
resolution,
..app
}
}
fn save_before_quit(&mut self) {
if let Err(e) = State::save(&mut self.state, &self.state_path) { error!("State file: {}", e); }
if let Err(e) = Node::save(&self.node_vec, &self.node_path) { error!("Node list: {}", e); }
if let Err(e) = Pool::save(&self.pool_vec, &self.pool_path) { error!("Pool list: {}", e); }
}
fn new(now: Instant) -> Self {
info!("Initializing App Struct...");
info!("App Init | P2Pool & XMRig processes...");
let p2pool = arc_mut!(Process::new(ProcessName::P2pool, String::new(), PathBuf::new()));
let xmrig = arc_mut!(Process::new(ProcessName::Xmrig, String::new(), PathBuf::new()));
let p2pool_api = arc_mut!(PubP2poolApi::new());
let xmrig_api = arc_mut!(PubXmrigApi::new());
let p2pool_img = arc_mut!(ImgP2pool::new());
let xmrig_img = arc_mut!(ImgXmrig::new());
info!("App Init | Sysinfo...");
// We give this to the [Helper] thread.
let mut sysinfo = sysinfo::System::new_with_specifics(
sysinfo::RefreshKind::new()
.with_cpu(sysinfo::CpuRefreshKind::everything())
.with_processes(sysinfo::ProcessRefreshKind::new().with_cpu())
.with_memory());
sysinfo.refresh_all();
let pid = match sysinfo::get_current_pid() {
Ok(pid) => pid,
Err(e) => { error!("App Init | Failed to get sysinfo PID: {}", e); exit(1) }
};
let pub_sys = arc_mut!(Sys::new());
// CPU Benchmark data initialization.
info!("App Init | Initializing CPU benchmarks...");
let benchmarks: Vec<Benchmark> = {
let cpu = sysinfo.cpus()[0].brand();
let mut json: Vec<Benchmark> = serde_json::from_slice(include_bytes!("cpu.json")).unwrap();
json.sort_by(|a, b| {
cmp_f64(strsim::jaro(&b.cpu, &cpu), strsim::jaro(&a.cpu, &cpu))
});
json
};
info!("App Init | Assuming user's CPU is: {}", benchmarks[0].cpu);
info!("App Init | The rest of the [App]...");
let mut app = Self {
tab: Tab::default(),
ping: arc_mut!(Ping::new()),
width: APP_DEFAULT_WIDTH,
height: APP_DEFAULT_HEIGHT,
must_resize: false,
og: arc_mut!(State::new()),
state: State::new(),
update: arc_mut!(Update::new(String::new(), PathBuf::new(), PathBuf::new(), true)),
file_window: FileWindow::new(),
og_node_vec: Node::new_vec(),
node_vec: Node::new_vec(),
og_pool_vec: Pool::new_vec(),
pool_vec: Pool::new_vec(),
restart: arc_mut!(Restart::No),
diff: false,
error_state: ErrorState::new(),
helper: arc_mut!(Helper::new(now, pub_sys.clone(), p2pool.clone(), xmrig.clone(), p2pool_api.clone(), xmrig_api.clone(), p2pool_img.clone(), xmrig_img.clone(), arc_mut!(GupaxP2poolApi::new()))),
p2pool,
xmrig,
p2pool_api,
xmrig_api,
p2pool_img,
xmrig_img,
p2pool_stdin: String::with_capacity(10),
xmrig_stdin: String::with_capacity(10),
sudo: arc_mut!(SudoState::new()),
resizing: false,
alpha: 0,
no_startup: false,
gupax_p2pool_api: arc_mut!(GupaxP2poolApi::new()),
pub_sys,
benchmarks,
pid,
max_threads: num_cpus::get(),
now,
admin: false,
exe: String::new(),
dir: String::new(),
resolution: Vec2::new(APP_DEFAULT_HEIGHT, APP_DEFAULT_WIDTH),
os: OS,
os_data_path: PathBuf::new(),
gupax_p2pool_api_path: PathBuf::new(),
state_path: PathBuf::new(),
node_path: PathBuf::new(),
pool_path: PathBuf::new(),
version: GUPAX_VERSION,
name_version: format!("Gupax {}", GUPAX_VERSION),
img: Images::new(),
regex: Regexes::new(),
};
//---------------------------------------------------------------------------------------------------- App init data that *could* panic
info!("App Init | Getting EXE path...");
let mut panic = String::new();
// Get exe path
app.exe = match get_exe() {
Ok(exe) => exe,
Err(e) => { panic = format!("get_exe(): {}", e); app.error_state.set(panic.clone(), ErrorFerris::Panic, ErrorButtons::Quit); String::new() },
};
// Get exe directory path
app.dir = match get_exe_dir() {
Ok(dir) => dir,
Err(e) => { panic = format!("get_exe_dir(): {}", e); app.error_state.set(panic.clone(), ErrorFerris::Panic, ErrorButtons::Quit); String::new() },
};
// Get OS data path
app.os_data_path = match get_gupax_data_path() {
Ok(dir) => dir,
Err(e) => { panic = format!("get_os_data_path(): {}", e); app.error_state.set(panic.clone(), ErrorFerris::Panic, ErrorButtons::Quit); PathBuf::new() },
};
info!("App Init | Setting TOML path...");
// Set [*.toml] path
app.state_path = app.os_data_path.clone();
app.state_path.push(STATE_TOML);
app.node_path = app.os_data_path.clone();
app.node_path.push(NODE_TOML);
app.pool_path = app.os_data_path.clone();
app.pool_path.push(POOL_TOML);
// Set GupaxP2poolApi path
app.gupax_p2pool_api_path = crate::disk::get_gupax_p2pool_path(&app.os_data_path);
lock!(app.gupax_p2pool_api).fill_paths(&app.gupax_p2pool_api_path);
// Apply arg state
// It's not safe to [--reset] if any of the previous variables
// are unset (null path), so make sure we just abort if the [panic] String contains something.
info!("App Init | Applying argument state...");
let mut app = parse_args(app, panic);
// Read disk state
info!("App Init | Reading disk state...");
use TomlError::*;
app.state = match State::get(&app.state_path) {
Ok(toml) => toml,
Err(err) => {
error!("State ... {}", err);
match err {
Io(e) => app.error_state.set(format!("State file: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Path(e) => app.error_state.set(format!("State file: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Serialize(e) => app.error_state.set(format!("State file: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Deserialize(e) => app.error_state.set(format!("State file: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Format(e) => app.error_state.set(format!("State file: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Merge(e) => app.error_state.set(format!("State file: {}", e), ErrorFerris::Error, ErrorButtons::ResetState),
_ => (),
};
State::new()
},
};
app.og = arc_mut!(app.state.clone());
// Read node list
info!("App Init | Reading node list...");
app.node_vec = match Node::get(&app.node_path) {
Ok(toml) => toml,
Err(err) => {
error!("Node ... {}", err);
match err {
Io(e) => app.error_state.set(format!("Node list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Path(e) => app.error_state.set(format!("Node list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Serialize(e) => app.error_state.set(format!("Node list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Deserialize(e) => app.error_state.set(format!("Node list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Format(e) => app.error_state.set(format!("Node list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Merge(e) => app.error_state.set(format!("Node list: {}", e), ErrorFerris::Error, ErrorButtons::ResetState),
Parse(e) => app.error_state.set(format!("Node list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
};
Node::new_vec()
},
};
app.og_node_vec = app.node_vec.clone();
debug!("Node Vec:");
debug!("{:#?}", app.node_vec);
// Read pool list
info!("App Init | Reading pool list...");
app.pool_vec = match Pool::get(&app.pool_path) {
Ok(toml) => toml,
Err(err) => {
error!("Pool ... {}", err);
match err {
Io(e) => app.error_state.set(format!("Pool list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Path(e) => app.error_state.set(format!("Pool list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Serialize(e) => app.error_state.set(format!("Pool list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Deserialize(e) => app.error_state.set(format!("Pool list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Format(e) => app.error_state.set(format!("Pool list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Merge(e) => app.error_state.set(format!("Pool list: {}", e), ErrorFerris::Error, ErrorButtons::ResetState),
Parse(e) => app.error_state.set(format!("Pool list: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
};
Pool::new_vec()
},
};
app.og_pool_vec = app.pool_vec.clone();
debug!("Pool Vec:");
debug!("{:#?}", app.pool_vec);
//----------------------------------------------------------------------------------------------------
// Read [GupaxP2poolApi] disk files
let mut gupax_p2pool_api = lock!(app.gupax_p2pool_api);
match GupaxP2poolApi::create_all_files(&app.gupax_p2pool_api_path) {
Ok(_) => info!("App Init | Creating Gupax-P2Pool API files ... OK"),
Err(err) => {
error!("GupaxP2poolApi ... {}", err);
match err {
Io(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Path(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Serialize(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Deserialize(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Format(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Merge(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Error, ErrorButtons::ResetState),
Parse(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
};
},
}
info!("App Init | Reading Gupax-P2Pool API files...");
match gupax_p2pool_api.read_all_files_and_update() {
Ok(_) => {
info!(
"GupaxP2poolApi ... Payouts: {} | XMR (atomic-units): {}",
gupax_p2pool_api.payout,
gupax_p2pool_api.xmr,
);
},
Err(err) => {
error!("GupaxP2poolApi ... {}", err);
match err {
Io(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Path(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Serialize(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Deserialize(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Format(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
Merge(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Error, ErrorButtons::ResetState),
Parse(e) => app.error_state.set(format!("GupaxP2poolApi: {}", e), ErrorFerris::Panic, ErrorButtons::Quit),
};
},
};
drop(gupax_p2pool_api);
lock!(app.helper).gupax_p2pool_api = Arc::clone(&app.gupax_p2pool_api);
//----------------------------------------------------------------------------------------------------
let mut og = lock!(app.og); // Lock [og]
// Handle max threads
info!("App Init | Handling max thread overflow...");
og.xmrig.max_threads = app.max_threads;
let current = og.xmrig.current_threads;
let max = og.xmrig.max_threads;
if current > max {
og.xmrig.current_threads = max;
}
// Handle [node_vec] overflow
info!("App Init | Handling [node_vec] overflow");
if og.p2pool.selected_index > app.og_node_vec.len() {
warn!("App | Overflowing manual node index [{} > {}], resetting to 1", og.p2pool.selected_index, app.og_node_vec.len());
let (name, node) = app.og_node_vec[0].clone();
og.p2pool.selected_index = 0;
og.p2pool.selected_name = name.clone();
og.p2pool.selected_ip = node.ip.clone();
og.p2pool.selected_rpc = node.rpc.clone();
og.p2pool.selected_zmq = node.zmq.clone();
app.state.p2pool.selected_index = 0;
app.state.p2pool.selected_name = name;
app.state.p2pool.selected_ip = node.ip;
app.state.p2pool.selected_rpc = node.rpc;
app.state.p2pool.selected_zmq = node.zmq;
}
// Handle [pool_vec] overflow
info!("App Init | Handling [pool_vec] overflow...");
if og.xmrig.selected_index > app.og_pool_vec.len() {
warn!("App | Overflowing manual pool index [{} > {}], resetting to 1", og.xmrig.selected_index, app.og_pool_vec.len());
let (name, pool) = app.og_pool_vec[0].clone();
og.xmrig.selected_index = 0;
og.xmrig.selected_name = name.clone();
og.xmrig.selected_ip = pool.ip.clone();
og.xmrig.selected_port = pool.port.clone();
app.state.xmrig.selected_index = 0;
app.state.xmrig.selected_name = name;
app.state.xmrig.selected_ip = pool.ip;
app.state.xmrig.selected_port = pool.port;
}
// Apply TOML values to [Update]
info!("App Init | Applying TOML values to [Update]...");
let p2pool_path = og.gupax.absolute_p2pool_path.clone();
let xmrig_path = og.gupax.absolute_xmrig_path.clone();
let tor = og.gupax.update_via_tor;
app.update = arc_mut!(Update::new(app.exe.clone(), p2pool_path, xmrig_path, tor));
// Set state version as compiled in version
info!("App Init | Setting state Gupax version...");
lock!(og.version).gupax = GUPAX_VERSION.to_string();
lock!(app.state.version).gupax = GUPAX_VERSION.to_string();
// Set saved [Tab]
info!("App Init | Setting saved [Tab]...");
app.tab = app.state.gupax.tab;
// Check if [P2pool.node] exists
info!("App Init | Checking if saved remote node still exists...");
app.state.p2pool.node = RemoteNode::check_exists(&app.state.p2pool.node);
drop(og); // Unlock [og]
// Spawn the "Helper" thread.
info!("Helper | Spawning helper thread...");
Helper::spawn_helper(&app.helper, sysinfo, app.pid, app.max_threads);
info!("Helper ... OK");
// Check for privilege. Should be Admin on [Windows] and NOT root on Unix.
info!("App Init | Checking for privilege level...");
#[cfg(target_os = "windows")]
if is_elevated::is_elevated() {
app.admin = true;
} else {
error!("Windows | Admin user not detected!");
app.error_state.set(format!("Gupax was not launched as Administrator!\nBe warned, XMRig might have less hashrate!"), ErrorFerris::Sudo, ErrorButtons::WindowsAdmin);
}
#[cfg(target_family = "unix")]
if sudo_check::check() != sudo_check::RunningAs::User {
let id = sudo_check::check();
error!("Unix | Regular user not detected: [{:?}]", id);
app.error_state.set(format!("Gupax was launched as: [{:?}]\nPlease launch Gupax with regular user permissions.", id), ErrorFerris::Panic, ErrorButtons::Quit);
}
// macOS re-locates "dangerous" applications into some read-only "/private" directory.
// It _seems_ to be fixed by moving [Gupax.app] into "/Applications".
// So, detect if we are in in "/private" and warn the user.
#[cfg(target_os = "macos")]
if app.exe.starts_with("/private") {
app.error_state.set(format!("macOS thinks Gupax is a virus!\n(macOS has relocated Gupax for security reasons)\n\nThe directory: [{}]\nSince this is a private read-only directory, it causes issues with updates and correctly locating P2Pool/XMRig. Please move Gupax into the [Applications] directory, this lets macOS relax a little.\n", app.exe), ErrorFerris::Panic, ErrorButtons::Quit);
}
info!("App ... OK");
app
}
}
//---------------------------------------------------------------------------------------------------- [Tab] Enum + Impl
// The tabs inside [App].
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum Tab {
About,
Status,
Gupax,
P2pool,
Xmrig,
}
impl Default for Tab {
fn default() -> Self {
Self::About
}
}
//---------------------------------------------------------------------------------------------------- CPU Benchmarks.
#[derive(Debug,Serialize,Deserialize)]
pub struct Benchmark {
pub cpu: String,
pub rank: u16,
pub percent: f32,
pub benchmarks: u16,
pub average: f32,
pub high: f32,
pub low: f32,
}
//---------------------------------------------------------------------------------------------------- [Restart] Enum
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Restart {
No, // We don't need to restart
Yes, // We updated, user should probably (but isn't required to) restart
}
//---------------------------------------------------------------------------------------------------- [ErrorState] struct
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorButtons {
YesNo,
StayQuit,
ResetState,
ResetNode,
Okay,
Quit,
Sudo,
WindowsAdmin,
Debug,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorFerris {
Happy,
Cute,
Oops,
Error,
Panic,
Sudo,
}
pub struct ErrorState {
error: bool, // Is there an error?
msg: String, // What message to display?
ferris: ErrorFerris, // Which ferris to display?
buttons: ErrorButtons, // Which buttons to display?
quit_twice: bool, // This indicates the user tried to quit on the [ask_before_quit] screen
}
impl Default for ErrorState {
fn default() -> Self {
Self::new()
}
}
impl ErrorState {
pub fn new() -> Self {
Self {
error: false,
msg: "Unknown Error".to_string(),
ferris: ErrorFerris::Oops,
buttons: ErrorButtons::Okay,
quit_twice: false,
}
}
// Convenience function to enable the [App] error state
pub fn set(&mut self, msg: impl Into<String>, ferris: ErrorFerris, buttons: ErrorButtons) {
if self.error {
// If a panic error is already set and there isn't an [Okay] confirm or another [Panic], return
if self.ferris == ErrorFerris::Panic && (buttons != ErrorButtons::Okay || ferris != ErrorFerris::Panic) { return }
}
*self = Self {
error: true,
msg: msg.into(),
ferris,
buttons,
quit_twice: false,
};
}
// Just sets the current state to new, resetting it.
pub fn reset(&mut self) {
*self = Self::new();
}
// Instead of creating a whole new screen and system, this (ab)uses ErrorState
// to ask for the [sudo] when starting XMRig. Yes, yes I know, it's called "ErrorState"
// but rewriting the UI code and button stuff might be worse.
// It also resets the current [SudoState]
pub fn ask_sudo(&mut self, state: &Arc<Mutex<SudoState>>) {
*self = Self {
error: true,
msg: String::new(),
ferris: ErrorFerris::Sudo,
buttons: ErrorButtons::Sudo,
quit_twice: false,
};
SudoState::reset(state)
}
}
//---------------------------------------------------------------------------------------------------- [Images] struct
struct Images {
banner: RetainedImage,
happy: RetainedImage,
cute: RetainedImage,
oops: RetainedImage,
error: RetainedImage,
panic: RetainedImage,
sudo: RetainedImage,
}
impl Images {
fn new() -> Self {
Self {
banner: RetainedImage::from_image_bytes("banner.png", BYTES_BANNER).unwrap(),
happy: RetainedImage::from_image_bytes("happy.png", FERRIS_HAPPY).unwrap(),
cute: RetainedImage::from_image_bytes("cute.png", FERRIS_CUTE).unwrap(),
oops: RetainedImage::from_image_bytes("oops.png", FERRIS_OOPS).unwrap(),
error: RetainedImage::from_image_bytes("error.png", FERRIS_ERROR).unwrap(),
panic: RetainedImage::from_image_bytes("panic.png", FERRIS_PANIC).unwrap(),
sudo: RetainedImage::from_image_bytes("panic.png", FERRIS_SUDO).unwrap(),
}
}
}
//---------------------------------------------------------------------------------------------------- [Pressed] enum
// These represent the keys pressed during the frame.
// I could use egui's [Key] but there is no option for
// a [None] and wrapping [key_pressed] like [Option<egui::Key>]
// meant that I had to destructure like this:
// if let Some(egui::Key)) = key_pressed { /* do thing */ }
//
// That's ugly, so these are used instead so a simple compare can be used.
#[derive(Debug,Clone,Eq,PartialEq)]
enum KeyPressed {
F11,
Up,
Down,
Esc,
Z,
X,
C,
V,
S,
R,
D,
None,
}
impl KeyPressed {
fn is_f11(&self) -> bool {
*self == Self::F11
}
fn is_z(&self) -> bool {
*self == Self::Z
}
fn is_x(&self) -> bool {
*self == Self::X
}
fn is_up(&self) -> bool {
*self == Self::Up
}
fn is_down(&self) -> bool {
*self == Self::Down
}
fn is_esc(&self) -> bool {
*self == Self::Esc
}
fn is_s(&self) -> bool {
*self == Self::S
}
fn is_r(&self) -> bool {
*self == Self::R
}
fn is_d(&self) -> bool {
*self == Self::D
}
fn is_c(&self) -> bool {
*self == Self::C
}
fn is_v(&self) -> bool {
*self == Self::V
}
fn is_none(&self) -> bool {
*self == Self::None
}
}
//---------------------------------------------------------------------------------------------------- Init functions
#[inline(always)]
fn init_text_styles(ctx: &egui::Context, width: f32) {
let scale = width / 30.0;
let mut style = (*ctx.style()).clone();
style.text_styles = [
(Small, FontId::new(scale/3.0, Proportional)),
(Body, FontId::new(scale/2.0, Proportional)),
(Button, FontId::new(scale/2.0, Proportional)),
(Monospace, FontId::new(scale/2.0, egui::FontFamily::Monospace)),
(Heading, FontId::new(scale/1.5, Proportional)),
(Name("Tab".into()), FontId::new(scale*1.2, Proportional)),
(Name("Bottom".into()), FontId::new(scale/2.0, Proportional)),
(Name("MonospaceSmall".into()), FontId::new(scale/2.5, egui::FontFamily::Monospace)),
(Name("MonospaceLarge".into()), FontId::new(scale/1.5, egui::FontFamily::Monospace)),
].into();
style.spacing.icon_width_inner = width / 35.0;
style.spacing.icon_width = width / 25.0;
style.spacing.icon_spacing = 20.0;
style.spacing.scroll_bar_width = width / 150.0;
ctx.set_style(style);
ctx.set_pixels_per_point(1.0);
ctx.request_repaint();
}
#[inline(always)]
fn init_logger(now: Instant) {
use env_logger::fmt::Color;
let filter_env = std::env::var("RUST_LOG").unwrap_or_else(|_| "INFO".to_string());
let filter = match filter_env.as_str() {
"error"|"Error"|"ERROR" => LevelFilter::Error,
"warn"|"Warn"|"WARN" => LevelFilter::Warn,
"debug"|"Debug"|"DEBUG" => LevelFilter::Debug,
"trace"|"Trace"|"TRACE" => LevelFilter::Trace,
_ => LevelFilter::Info,
};
std::env::set_var("RUST_LOG", format!("off,gupax={}", filter_env));
Builder::new().format(move |buf, record| {
let mut style = buf.style();
let level = match record.level() {
Level::Error => { style.set_color(Color::Red); "ERROR" },
Level::Warn => { style.set_color(Color::Yellow); "WARN" },
Level::Info => { style.set_color(Color::White); "INFO" },
Level::Debug => { style.set_color(Color::Blue); "DEBUG" },
Level::Trace => { style.set_color(Color::Magenta); "TRACE" },
};
writeln!(
buf,
"[{}] [{}] [{}:{}] {}",
style.set_bold(true).value(level),
buf.style().set_dimmed(true).value(format!("{:.3}", now.elapsed().as_secs_f32())),
buf.style().set_dimmed(true).value(record.file().unwrap_or("???")),
buf.style().set_dimmed(true).value(record.line().unwrap_or(0)),
record.args(),
)
}).filter_level(filter).write_style(WriteStyle::Always).parse_default_env().format_timestamp_millis().init();
info!("init_logger() ... OK");
info!("Log level ... {}", filter);
}
#[inline(always)]
fn init_options(initial_window_size: Option<Vec2>) -> NativeOptions {
let mut options = eframe::NativeOptions::default();
options.min_window_size = Some(Vec2::new(APP_MIN_WIDTH, APP_MIN_HEIGHT));
options.max_window_size = Some(Vec2::new(APP_MAX_WIDTH, APP_MAX_HEIGHT));
options.initial_window_size = initial_window_size;
options.follow_system_theme = false;
options.default_theme = eframe::Theme::Dark;
let icon = image::load_from_memory(BYTES_ICON).expect("Failed to read icon bytes").to_rgba8();
let (icon_width, icon_height) = icon.dimensions();
options.icon_data = Some(eframe::IconData {
rgba: icon.into_raw(),
width: icon_width,
height: icon_height,
});
info!("init_options() ... OK");
options
}
#[inline(always)]
fn init_auto(app: &mut App) {
// Return early if [--no-startup] was not passed
if app.no_startup {
info!("[--no-startup] flag passed, skipping init_auto()...");
return
} else if app.error_state.error {
info!("App error detected, skipping init_auto()...");
return
} else {
info!("Starting init_auto()...");
}
// [Auto-Update]
#[cfg(not(feature = "distro"))]
if app.state.gupax.auto_update {
Update::spawn_thread(&app.og, &app.state.gupax, &app.state_path, &app.update, &mut app.error_state, &app.restart);
} else {
info!("Skipping auto-update...");
}
// [Auto-Ping]
if app.state.p2pool.auto_ping && app.state.p2pool.simple {
Ping::spawn_thread(&app.ping)
} else {
info!("Skipping auto-ping...");
}
// [Auto-P2Pool]
if app.state.gupax.auto_p2pool {
if !Regexes::addr_ok(&app.regex, &app.state.p2pool.address) {
warn!("Gupax | P2Pool address is not valid! Skipping auto-p2pool...");
} else if !Gupax::path_is_file(&app.state.gupax.p2pool_path) {
warn!("Gupax | P2Pool path is not a file! Skipping auto-p2pool...");
} else if !crate::update::check_p2pool_path(&app.state.gupax.p2pool_path) {
warn!("Gupax | P2Pool path is not valid! Skipping auto-p2pool...");
} else {
Helper::start_p2pool(&app.helper, &app.state.p2pool, &app.state.gupax.absolute_p2pool_path);
}
} else {
info!("Skipping auto-p2pool...");
}
// [Auto-XMRig]
if app.state.gupax.auto_xmrig {
if !Gupax::path_is_file(&app.state.gupax.xmrig_path) {
warn!("Gupax | XMRig path is not an executable! Skipping auto-xmrig...");
} else if !crate::update::check_xmrig_path(&app.state.gupax.xmrig_path) {
warn!("Gupax | XMRig path is not valid! Skipping auto-xmrig...");
} else if cfg!(windows) {
Helper::start_xmrig(&app.helper, &app.state.xmrig, &app.state.gupax.absolute_xmrig_path, Arc::clone(&app.sudo));
} else {
lock!(app.sudo).signal = ProcessSignal::Start;
app.error_state.ask_sudo(&app.sudo);
}
} else {
info!("Skipping auto-xmrig...");
}
}
//---------------------------------------------------------------------------------------------------- Reset functions
fn reset_state(path: &PathBuf) -> Result<(), TomlError> {
match State::create_new(path) {
Ok(_) => { info!("Resetting [state.toml] ... OK"); Ok(()) },
Err(e) => { error!("Resetting [state.toml] ... FAIL ... {}", e); Err(e) },
}
}
#[inline(always)]
fn reset_nodes(path: &PathBuf) -> Result<(), TomlError> {
match Node::create_new(path) {
Ok(_) => { info!("Resetting [node.toml] ... OK"); Ok(()) },
Err(e) => { error!("Resetting [node.toml] ... FAIL ... {}", e); Err(e) },
}
}
#[inline(always)]
fn reset_pools(path: &PathBuf) -> Result<(), TomlError> {
match Pool::create_new(path) {
Ok(_) => { info!("Resetting [pool.toml] ... OK"); Ok(()) },
Err(e) => { error!("Resetting [pool.toml] ... FAIL ... {}", e); Err(e) },
}
}
#[inline(always)]
fn reset_gupax_p2pool_api(path: &PathBuf) -> Result<(), TomlError> {
match GupaxP2poolApi::create_new(path) {
Ok(_) => { info!("Resetting GupaxP2poolApi ... OK"); Ok(()) },
Err(e) => { error!("Resetting GupaxP2poolApi folder ... FAIL ... {}", e); Err(e) },
}
}
#[inline(always)]
fn reset(path: &PathBuf, state: &PathBuf, node: &PathBuf, pool: &PathBuf, gupax_p2pool_api: &PathBuf) {
let mut code = 0;
// Attempt to remove directory first
match std::fs::remove_dir_all(path) {
Ok(_) => info!("Removing OS data path ... OK"),
Err(e) => { error!("Removing OS data path ... FAIL ... {}", e); code = 1; },
}
// Recreate
match create_gupax_dir(path) {
Ok(_) => (),
Err(_) => code = 1,
}
match reset_state(state) {
Ok(_) => (),
Err(_) => code = 1,
}
match reset_nodes(node) {
Ok(_) => (),
Err(_) => code = 1,
}
match reset_pools(pool) {
Ok(_) => (),
Err(_) => code = 1,
}
match reset_gupax_p2pool_api(gupax_p2pool_api) {
Ok(_) => (),
Err(_) => code = 1,
}
match code {
0 => println!("\nGupax reset ... OK"),
_ => eprintln!("\nGupax reset ... FAIL"),
}
exit(code);
}
//---------------------------------------------------------------------------------------------------- Misc functions
#[inline(always)]
fn parse_args<S: Into<String>>(mut app: App, panic: S) -> App {
info!("Parsing CLI arguments...");
let mut args: Vec<String> = env::args().collect();
if args.len() == 1 { info!("No args ... OK"); return app } else { args.remove(0); info!("Args ... {:?}", args); }
// [help/version], exit early
for arg in &args {
match arg.as_str() {
"--help" => { println!("{}", ARG_HELP); exit(0); },
"--version" => {
println!("Gupax {} [OS: {}, Commit: {}]\nThis Gupax was originally bundled with:\n - P2Pool {}\n - XMRig {}\n\n{}", GUPAX_VERSION, OS_NAME, &COMMIT[..40], P2POOL_VERSION, XMRIG_VERSION, ARG_COPYRIGHT);
exit(0);
},
"--ferris" => { println!("{}", FERRIS_ANSI); exit(0); },
_ => (),
}
}
// Abort on panic
let panic = panic.into();
if ! panic.is_empty() {
info!("[Gupax error] {}", panic);
exit(1);
}
// Everything else
for arg in args {
match arg.as_str() {
"--state" => { info!("Printing state..."); print_disk_file(&app.state_path); },
"--nodes" => { info!("Printing node list..."); print_disk_file(&app.node_path); },
"--payouts" => { info!("Printing payouts...\n"); print_gupax_p2pool_api(&app.gupax_p2pool_api); },
"--reset-state" => if let Ok(()) = reset_state(&app.state_path) { println!("\nState reset ... OK"); exit(0); } else { eprintln!("\nState reset ... FAIL"); exit(1) },
"--reset-nodes" => if let Ok(()) = reset_nodes(&app.node_path) { println!("\nNode reset ... OK"); exit(0) } else { eprintln!("\nNode reset ... FAIL"); exit(1) },
"--reset-pools" => if let Ok(()) = reset_pools(&app.pool_path) { println!("\nPool reset ... OK"); exit(0) } else { eprintln!("\nPool reset ... FAIL"); exit(1) },
"--reset-payouts" => if let Ok(()) = reset_gupax_p2pool_api(&app.gupax_p2pool_api_path) { println!("\nGupaxP2poolApi reset ... OK"); exit(0) } else { eprintln!("\nGupaxP2poolApi reset ... FAIL"); exit(1) },
"--reset-all" => reset(&app.os_data_path, &app.state_path, &app.node_path, &app.pool_path, &app.gupax_p2pool_api_path),
"--no-startup" => app.no_startup = true,
_ => { eprintln!("\n[Gupax error] Invalid option: [{}]\nFor help, use: [--help]", arg); exit(1); },
}
}
app
}
// Get absolute [Gupax] binary path
#[inline(always)]
pub fn get_exe() -> Result<String, std::io::Error> {
match std::env::current_exe() {
Ok(path) => { Ok(path.display().to_string()) },
Err(err) => { error!("Couldn't get absolute Gupax PATH"); Err(err) },
}
}
// Get absolute [Gupax] directory path
#[inline(always)]
pub fn get_exe_dir() -> Result<String, std::io::Error> {
match std::env::current_exe() {
Ok(mut path) => { path.pop(); Ok(path.display().to_string()) },
Err(err) => { error!("Couldn't get exe basepath PATH"); Err(err) },
}
}
// Clean any [gupax_update_.*] directories
// The trailing random bits must be exactly 10 alphanumeric characters
#[inline(always)]
pub fn clean_dir() -> Result<(), anyhow::Error> {
let regex = Regex::new("^gupax_update_[A-Za-z0-9]{10}$").unwrap();
for entry in std::fs::read_dir(get_exe_dir()?)? {
let entry = entry?;
if ! entry.path().is_dir() { continue }
if Regex::is_match(®ex, entry.file_name().to_str().ok_or_else(|| anyhow::Error::msg("Basename failed"))?) {
let path = entry.path();
match std::fs::remove_dir_all(&path) {
Ok(_) => info!("Remove [{}] ... OK", path.display()),
Err(e) => warn!("Remove [{}] ... FAIL ... {}", path.display(), e),
}
}