forked from yuzi-co/Forager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCore.ps1
1831 lines (1561 loc) · 95.9 KB
/
Core.ps1
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
param(
[Parameter(Mandatory = $false)]
[Array]$Algorithm = $null,
[Parameter(Mandatory = $false)]
[Array]$PoolsName = $null,
[Parameter(Mandatory = $false)]
[array]$CoinsName = $null,
[Parameter(Mandatory = $false)]
[String]$MiningMode = $null,
[Parameter(Mandatory = $false)]
[array]$GroupNames = $null,
[Parameter(Mandatory = $false)]
[string]$PercentToSwitch = $null
)
##Parameters for testing, must be commented on real use
# $MiningMode='Automatic'
# $MiningMode='Manual'
# $PoolsName=('ahashpool','miningpoolhub','hashrefinery')
# $PoolsName='whattomine'
# $PoolsName='zergpool'
# $PoolsName='yiimp'
# $PoolsName='ahashpool'
# $PoolsName=('hashrefinery','zpool')
# $PoolsName='miningpoolhub'
# $PoolsName='zpool'
# $PoolsName='hashrefinery'
# $PoolsName='altminer'
# $PoolsName='blazepool'
# $PoolsName="Nicehash"
# $PoolsName="Nanopool"
# $CoinsName =('bitcore','Signatum','Zcash')
# $CoinsName ='zcash'
# $Algorithm =('phi','x17')
# $GroupNames=('rx580')
$error.clear()
$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
. $ScriptRoot\Include.ps1
#Start log file
$LogPath = "$ScriptRoot\Logs\"
if (!(Test-Path -Path $LogPath)) { New-Item -Path $LogPath -ItemType directory | Out-Null }
$LogName = $LogPath + "$(Get-Date -Format "yyyy-MM-dd_HH-mm-ss").log"
Start-Transcript $LogName #for start log msg
Stop-Transcript
$LogFile = [System.IO.StreamWriter]::new( $LogName, $true )
$LogFile.AutoFlush = $true
Clear-Files
if ([Net.ServicePointManager]::SecurityProtocol -notmatch [Net.SecurityProtocolType]::Tls12) {
[Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
}
# Force Culture to en-US
$culture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-US")
$culture.NumberFormat.NumberDecimalSeparator = "."
$culture.NumberFormat.NumberGroupSeparator = ","
[System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
$ErrorActionPreference = "Continue"
$Config = Get-Config
$Application = "Forager"
$Release = "18.12"
Log-Message "$Application v$Release"
$Host.UI.RawUI.WindowTitle = "$Application v$Release"
$env:CUDA_DEVICE_ORDER = 'PCI_BUS_ID' #This align cuda id with nvidia-smi order
$env:GPU_FORCE_64BIT_PTR = 0 #For AMD
$env:GPU_MAX_HEAP_SIZE = 100 #For AMD
$env:GPU_USE_SYNC_OBJECTS = 1 #For AMD
$env:GPU_MAX_ALLOC_PERCENT = 100 #For AMD
$env:GPU_SINGLE_ALLOC_PERCENT = 100 #For AMD
$progressPreference = 'silentlyContinue' #No progress message on web requests
#$progressPreference = 'Stop'
Set-Location $ScriptRoot
#Set process priority to BelowNormal to avoid hash rate drops on systems with weak CPUs
(Get-Process -Id $PID).PriorityClass = "BelowNormal"
Import-Module NetSecurity -ErrorAction SilentlyContinue
Import-Module Defender -ErrorAction SilentlyContinue
Import-Module "$env:Windir\System32\WindowsPowerShell\v1.0\Modules\NetSecurity\NetSecurity.psd1" -ErrorAction SilentlyContinue
Import-Module "$env:Windir\System32\WindowsPowerShell\v1.0\Modules\Defender\Defender.psd1" -ErrorAction SilentlyContinue
if (Get-Command "Unblock-File" -ErrorAction SilentlyContinue) {Get-ChildItem . -Recurse | Unblock-File}
if ((Get-Command "Get-MpPreference" -ErrorAction SilentlyContinue) -and (Get-MpComputerStatus -ErrorAction SilentlyContinue) -and (Get-MpPreference).ExclusionPath -notcontains (Convert-Path .)) {
Start-Process (@{desktop = "powershell"; core = "pwsh"}.$PSEdition) "-Command Import-Module '$env:Windir\System32\WindowsPowerShell\v1.0\Modules\Defender\Defender.psd1'; Add-MpPreference -ExclusionPath '$(Convert-Path .)'" -Verb runAs
}
$ActiveMiners = @()
$ShowBestMinersOnly = $true
$Interval = @{
Current = $null
Last = $null
Duration = $null
StartTime = $null
LastTime = $null
Benchmark = $null
}
$Screen = $Config.StartScreen
#---Parameters checking
if (@('Manual', 'Automatic', 'Automatic24h') -notcontains $MiningMode) {
Log-Message "Parameter MiningMode not valid, valid options: Manual, Automatic, Automatic24h" -Severity Warn
Exit
}
$Params = @{
Querymode = "info"
PoolsFilterList = $PoolsName
CoinFilterList = $CoinsName
Location = $Location
AlgoFilterList = $Algorithm
}
$PoolsChecking = Get-Pools @Params
$PoolsErrors = switch ($MiningMode) {
"Automatic" {$PoolsChecking | Where-Object ActiveOnAutomaticMode -eq $false}
"Automatic24h" {$PoolsChecking | Where-Object ActiveOnAutomatic24hMode -eq $false}
"Manual" {$PoolsChecking | Where-Object ActiveOnManualMode -eq $false }
}
$PoolsErrors | ForEach-Object {
Log-Message "Selected MiningMode is not valid for pool $($_.Name)" -Severity Warn
Exit
}
if ($MiningMode -eq 'Manual' -and ($CoinsName -split ',').Count -ne 1) {
Log-Message "On manual mode one coin must be selected" -Severity Warn
Exit
}
if ($MiningMode -eq 'Manual' -and ($Algorithm -split ',').Count -ne 1) {
Log-Message "On manual mode one algorithm must be selected" -Severity Warn
Exit
}
#parameters backup
$ParamAlgorithmBCK = $Algorithm
$ParamPoolsNameBCK = $PoolsName
$ParamCoinsNameBCK = $CoinsName
$ParamMiningModeBCK = $MiningMode
try {Set-WindowSize 180 50} catch {}
$Interval.StartTime = Get-Date #first initialization, must be outside loop
Send-ErrorsToLog $LogFile
$Msg = @("Starting Parameters: "
"Algorithm: " + [string]($Algorithm -join ",")
"PoolsName: " + [string]($PoolsName -join ",")
"CoinsName: " + [string]($CoinsName -join ",")
"MiningMode: " + $MiningMode
"GroupNames: " + [string]($GroupNames -join ",")
"PercentToSwitch: " + $PercentToSwitch
) -join ' //'
Log-Message $Msg -Severity Debug
#Enable api
if ($config.ApiPort -gt 0) {
Log-Message "Starting API on port $($config.ApiPort)" -Severity Debug
$ApiSharedFile = "$ScriptRoot\ApiShared" + [string](Get-Random -minimum 0 -maximum 99999999) + ".tmp"
$command = "-WindowStyle minimized -noExit -executionpolicy bypass -file $ScriptRoot\Includes\ApiListener.ps1 -port " + [string]$config.ApiPort + " -SharedFile $ApiSharedFile "
$APIprocess = Start-Process -FilePath "powershell.exe" -ArgumentList $command -Verb RunAs -PassThru -WindowStyle Minimized
#open firewall port
$command = "New-NetFirewallRule -DisplayName '$Application' -Direction Inbound -Action Allow -Protocol TCP -LocalPort $($config.ApiPort)"
Start-Process -FilePath "powershell.exe" -ArgumentList $command -Verb RunAs -WindowStyle Minimized
$command = "New-NetFirewallRule -DisplayName '$Application' -Direction Outbound -Action Allow -Protocol TCP -LocalPort $($config.ApiPort)"
Start-Process -FilePath "powershell.exe" -ArgumentList $command -Verb RunAs -WindowStyle Minimized
}
$Quit = $false
# Initialize MSI Afterburner
if ((Get-ConfigVariable "Afterburner") -eq "Enabled") {
. .\Includes\afterburner.ps1
}
#enable EthlargementPill
if (@('RevA', 'RevB') -contains $config.EthlargementPill) {
Log-Message "Starting EthlargementPill"
$arg = "-" + $config.EthlargementPill
$EthPill = Start-Process -FilePath ".\Includes\OhGodAnETHlargementPill-r2.exe" -passthru -Verb RunAs -ArgumentList $arg
}
#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
#This loop will be running forever
#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------------
while ($Quit -eq $false) {
$Config = Get-Config
Log-Message ($Config | ConvertTo-Json) -Severity Debug
Clear-Host; $RepaintScreen = $true
# Check for updates
try {
$Request = Invoke-APIRequest -Url "https://api.github.com/repos/yuzi-co/$Application/releases/latest" -Age 60
$RemoteVersion = ($Request.tag_name -replace '[^\d.]')
$Uri = $Request.assets | Where-Object Name -eq "$Application-$RemoteVersion.7z" | Select-Object -ExpandProperty browser_download_url
if ([version]$RemoteVersion -gt [version]$Release) {
Log-Message "$Application is out of date. There is an updated version available at $URI" -Severity Warn
}
} catch {
Log-Message "Failed to get $Application updates." -Severity Warn
}
#get mining types
$DeviceGroups = Get-MiningTypes -filter $GroupNames
if ($null -eq $Interval.Last) {
Log-Message (Get-DevicesInformation $DeviceGroups | ConvertTo-Json) -Severity Debug
Log-Message ($DeviceGroups | ConvertTo-Json) -Severity Debug
Test-DeviceGroupsConfig $DeviceGroups
}
$NumberTypesGroups = ($DeviceGroups | Measure-Object).count
if ($NumberTypesGroups -gt 0) {$InitialProfitsScreenLimit = [Math]::Floor(30 / $NumberTypesGroups) - 5} #screen adjust to number of groups
if ($null -eq $Interval.Last) {$ProfitsScreenLimit = $InitialProfitsScreenLimit}
Log-Message "New interval starting..."
Log-Message (Get-ComputerStats | ConvertTo-Json) -Severity Debug
$Location = $Config.Location
if ([string]::IsNullOrWhiteSpace($PercentToSwitch)) {$PercentToSwitch2 = [int]($Config.PercentToSwitch)}
else {$PercentToSwitch2 = [int]$PercentToSwitch}
$DelayCloseMiners = $Config.DelayCloseMiners
$BenchmarkIntervalTime = [int]($Config.BenchmarkTime)
$LocalCurrency = $Config.LocalCurrency
if ([string]::IsNullOrWhiteSpace($LocalCurrency)) {
#for old config.ini compatibility
$LocalCurrency = switch ($Location) {
'Europe' {"EUR"}
'EU' {"EUR"}
'US' {"USD"}
'ASIA' {"USD"}
'GB' {"GBP"}
default {"USD"}
}
}
$Interval.Last = $Interval.Current
$Interval.LastTime = (Get-Date) - $Interval.StartTime
$Interval.StartTime = Get-Date
#Donation
$DonationStat = if (Test-Path -Path 'Donation.ctr') { (Get-Content -Path 'Donation.ctr') -split '_' } else { 0, 0 }
$DonationPastTime = [int]$DonationStat[0]
$DonatedTime = [int]$DonationStat[1]
$ElapsedDonationTime = [int]($DonationPastTime + $Interval.LastTime.TotalMinutes)
$ElapsedDonatedTime = [int]($DonatedTime + $Interval.LastTime.TotalMinutes)
$ConfigDonateTime = [math]::Max([int]($Config.Donate), 10)
#Activate or deactivate donation
if ($ElapsedDonationTime -gt 1440 -and $ConfigDonateTime -gt 0) {
# donation interval
$Interval.Current = "Donate"
$Config.UserName = "ffwd"
$Config.WorkerName = "Donate"
$CoinsWallets = @{
BTC = "3NoVvkGSNjPX8xBMWbP2HioWYK395wSzGL"
}
$DonateInterval = ($ConfigDonateTime - $ElapsedDonatedTime) * 60
$Algorithm = $null
$PoolsName = ("NiceHash")
$CoinsName = $null
$MiningMode = "Automatic"
if ($ElapsedDonatedTime -ge $ConfigDonateTime) {"0_0" | Set-Content -Path 'Donation.ctr'}
else {[string]$DonationPastTime + "_" + [string]$ElapsedDonatedTime | Set-Content -Path 'Donation.ctr'}
Log-Message "Next interval you will be donating for $DonateInterval seconds, thanks for your support"
} else {
#NOT donation interval
$Interval.Current = "Mining"
$Algorithm = $ParamAlgorithmBCK
$PoolsName = $ParamPoolsNameBCK
$CoinsName = $ParamCoinsNameBCK
$MiningMode = $ParamMiningModeBCK
if (!$Config.WorkerName) {$Config.WorkerName = (Get-Culture).TextInfo.ToTitleCase(($env:COMPUTERNAME).ToLower())}
$CoinsWallets = @{}
switch -regex -file config.ini {
"^\s*WALLET_(\w+)\s*=\s*(.*)" {
$name, $value = $matches[1..2]
$CoinsWallets[$name] = $value.Trim()
}
}
[string]$ElapsedDonationTime + "_0" | Set-Content -Path Donation.ctr
}
$Currency = $Config.Currency
$UserName = $Config.UserName
$WorkerName = $Config.WorkerName
$MinerWindowStyle = $Config.MinerWindowStyle
if ([string]::IsNullOrEmpty($MinerWindowStyle)) {$MinerWindowStyle = 'Minimized'}
$MinerStatusUrl = $Config.MinerStatusUrl
$MinerStatusKey = $Config.MinerStatusKey
if (!$MinerStatusKey -and $CoinsWallets.BTC) {$MinerStatusKey = $CoinsWallets.BTC}
Send-ErrorsToLog $LogFile
#get actual hour electricity cost
($Config.ElectricityCost | ConvertFrom-Json) | ForEach-Object {
if ((
$_.HourStart -lt $_.HourEnd -and
@(($_.HourStart)..($_.HourEnd)) -contains (Get-Date).Hour
) -or (
$_.HourStart -gt $_.HourEnd -and (
@(($_.HourStart)..23) -contains (Get-Date).Hour -or
@(0..($_.HourEnd)) -contains (Get-Date).Hour
)
)
) {$ElectricityCostValue = [double]$_.CostKwh}
}
Log-Message "Loading Pools Information..."
#Load information about the Pools, only must read parameter passed files (not all as mph do), level is Pool-Algo-Coin
do {
$Params = @{
Querymode = "core"
PoolsFilterList = $PoolsName
CoinFilterList = $CoinsName
Location = $Location
AlgoFilterList = $Algorithm
}
$AllPools = Get-Pools @Params
if ($AllPools.Count -eq 0) {
Log-Message "NO POOLS! Retry in 30 seconds" -Severity Warn
Log-Message "If you are mining on anonymous pool without exchage, like YIIMP, NANOPOOL or similar, you must set wallet for at least one pool coin in config.ini" -Severity Warn
Start-Sleep 30
}
} while ($AllPools.Count -eq 0)
$AllPools | Select-Object name -unique | ForEach-Object {Log-Message "Pool $($_.Name) was responsive..."}
Log-Message "Detected $($AllPools.Count) pools..."
#Filter by minworkers variable (only if there is any pool greater than minimum)
$Pools = ($AllPools | Where-Object {$_.PoolWorkers -ge $Config.MinWorkers -or $_.PoolWorkers -eq $null})
if ($Pools.Count -ge 1) {
Log-Message "$($Pools.Count) pools left after min workers filter..."
} else {
$Pools = $AllPools
Log-Message "No pools with workers greater than minimum config, filter ignored..."
}
## Select highest paying pool for each algo and check if pool is alive.
Log-Message "Select top paying pool for each algo in config"
if ($config.PingPools -eq 'Enabled') {Log-Message "Checking pool availability"}
$PoolsFiltered = $Pools | Group-Object -Property Algorithm | ForEach-Object {
$NeedPool = $false
foreach ($DeviceGroup in $DeviceGroups) {
## Is pool algorithm defined in config?
$AlgoList = $DeviceGroup.Algorithms | ForEach-Object {$_ -split '_'} | Select-Object -Unique
if (!$AlgoList -or $AlgoList -contains $_.Name) {$NeedPool = $true}
}
if ($NeedPool) {
## Order by price (profitability)
$_.Group | Sort-Object -Property `
@{Expression = $(if ($MiningMode -eq 'Automatic24h') {"Price24h"} else {"Price"}); Descending = $true},
@{Expression = "LocationPriority"; Ascending = $true} | ForEach-Object {
if ($NeedPool) {
## test tcp connection to pool
if ($config.PingPools -ne 'Enabled' -or (Test-TCPPort -Server $_.Host -Port $_.Port -Timeout 100)) {
$NeedPool = $false
$_ ## return result
} else {
Log-Message "$($_.PoolName): $($_.Host):$($_.Port) is not responding!" -Severity Warn
}
}
}
}
}
$Pools = $PoolsFiltered
Log-Message "$($Pools.Count) pools left"
Remove-Variable PoolsFiltered
#Call api to local currency conversion
try {
$CDKResponse = Invoke-APIRequest -Url "https://api.coindesk.com/v1/bpi/currentprice/$LocalCurrency.json" -MaxAge 60 |
Select-Object -ExpandProperty BPI
$LocalBTCvalue = $CDKResponse.$LocalCurrency.rate_float
Log-Message "CoinDesk API was responsive..."
} catch {
Log-Message "Coindesk API not responding, no local coin conversion..." -Severity Warn
}
#Load information about the Miner asociated to each Coin-Algo-Miner
$Miners = @()
$MinersFolderContent = (Get-ChildItem "Miners" -Filter "*.json")
Log-Message "Files in miner folder: $($MinersFolderContent.count)" -Severity Debug
Log-Message "Number of device groups: $($DeviceGroups.count)" -Severity Debug
foreach ($MinerFile in $MinersFolderContent) {
try { $Miner = $MinerFile | Get-Content | ConvertFrom-Json }
catch {
Log-Message "Badly formed JSON: $MinerFile" -Severity Warn
Exit
}
foreach ($DeviceGroup in $DeviceGroups) {
#generate a line for each device group that has algorithm as valid
if ($Miner.Type -ne $DeviceGroup.type) {
Log-Message "$($MinerFile.pschildname) is NOT valid for $($DeviceGroup.GroupName). Skipping" -Severity Debug
Continue
} elseif ($Config.("ExcludeMiners_" + $DeviceGroup.GroupName) -and ($Config.("ExcludeMiners_" + $DeviceGroup.GroupName).split(',') | Where-Object {$MinerFile.BaseName -like $_})) {
Log-Message "$($MinerFile.pschildname) is Excluded for $($DeviceGroup.GroupName). Skipping" -Severity Debug
Continue
} else {
#check group and miner types are the same
Log-Message "$($MinerFile.pschildname) is valid for $($DeviceGroup.GroupName)" -Severity Debug
}
foreach ($Algo in $Miner.Algorithms.PSObject.Properties) {
##AlgoName contains real name for dual and no dual miners
$AlgoTmp = ($Algo.Name -split "\|")[0]
$AlgoLabel = ($Algo.Name -split ("\|"))[1]
$AlgoName = Get-AlgoUnifiedName (($AlgoTmp -split ("_"))[0])
$AlgoNameDual = Get-AlgoUnifiedName (($AlgoTmp -split ("_"))[1])
$Algorithms = $AlgoName + $(if ($AlgoNameDual) {"_$AlgoNameDual"})
# Check memory constraints on miners
if ($DeviceGroup.MemoryGB -gt 0) {
$SkipLabel = $false
if ($AlgoLabel -match '(?<mem>\d+)gb.*') {
if ($DeviceGroup.MemoryGB -lt [int]$Matches.mem) {$SkipLabel = $true}
}
if ($SkipLabel) {
Log-Message "$($MinerFile.BaseName)/$Algorithms/$AlgoLabel skipped due to constraints" -Severity Debug
Continue
}
}
if ($Config.CUDAVersion -and $Miner.CUDA) {
if ([version]$Miner.CUDA -gt [version]$Config.CUDAVersion) {
Log-Message "$($MinerFile.BaseName) skipped due to CUDA version constraints" -Severity Debug
Continue
}
}
if ($DeviceGroup.Algorithms -and $DeviceGroup.Algorithms -notcontains $Algorithms) {Continue} #check config has this algo as minable
foreach ($Pool in ($Pools | Where-Object Algorithm -eq $AlgoName)) {
#Search pools for that algo
# If Miner limited to pools
if ($Miner.Pools -and $ExecutionContext.InvokeCommand.ExpandString($Miner.Pools) -eq $false) {Continue}
if (!$AlgoNameDual -or ($Pools | Where-Object Algorithm -eq $AlgoNameDual)) {
#Set flag if both Miner and Pool support SSL
$enableSSL = [bool]($Miner.SSL -and $Pool.SSL)
#Replace wildcards patterns
if ($Pool.PoolName -eq 'Nicehash') {$Nicehash = $true} else {$Nicehash = $false}
if ($Nicehash) {
$WorkerNameMain = $WorkerName + '-' + $DeviceGroup.GroupName #Nicehash requires alphanumeric WorkerNames
} else {
$WorkerNameMain = $WorkerName + '_' + $DeviceGroup.GroupName
}
$PoolUser = $Pool.User -replace '#WorkerName#', $WorkerNameMain
$PoolPass = $Pool.Pass -replace '#WorkerName#', $WorkerNameMain
$Params = @{
'#Protocol#' = $(if ($enableSSL) {$Pool.ProtocolSSL} else {$Pool.Protocol})
'#Server#' = $(if ($enableSSL) {$Pool.HostSSL} else {$Pool.Host})
'#Port#' = $(if ($enableSSL) {$Pool.PortSSL} else {$Pool.Port})
'#Login#' = $PoolUser
'#Password#' = $PoolPass
'#GPUPlatform#' = $DeviceGroup.Platform
'#Algorithm#' = $AlgoName
'#AlgorithmParameters#' = $Algo.Value
'#WorkerName#' = $WorkerNameMain
'#Devices#' = $DeviceGroup.Devices
'#DevicesClayMode#' = $DeviceGroup.DevicesClayMode
'#DevicesETHMode#' = $DeviceGroup.DevicesETHMode
'#DevicesNsgMode#' = $DeviceGroup.DevicesNsgMode
'#EthStMode#' = $Pool.EthStMode
'#GroupName#' = $DeviceGroup.GroupName
'#EMail#' = $Config.EMail
}
$Arguments = $Miner.Arguments -join " "
$Arguments = $Arguments -replace '#AlgorithmParameters#', $Algo.Value
foreach ($P in $Params.Keys) {$Arguments = $Arguments -replace $P, $Params.$P}
$PatternConfigFile = $Miner.PatternConfigFile -replace '#Algorithm#', $AlgoName -replace '#GroupName#', $DeviceGroup.GroupName
if ($PatternConfigFile -and (Test-Path -Path $PatternConfigFile)) {
$ConfigFileArguments = Replace-ForEachDevice (Get-Content $PatternConfigFile -raw) -Devices $DeviceGroup
foreach ($P in $Params.Keys) {$ConfigFileArguments = $ConfigFileArguments -replace $P, $Params.$P}
}
#select correct price by mode
$Price = $Pool.$(if ($MiningMode -eq 'Automatic24h') {"Price24h"} else {"Price"})
#Search for dualmining pool
if ($AlgoNameDual) {
#search dual pool and select correct price by mode
$PoolDual = $Pools |
Where-Object Algorithm -eq $AlgoNameDual |
Sort-Object @{Expression = $(if ($MiningMode -eq 'Automatic24h') {"Price24h"} else {"Price"}); Descending = $true} |
Select-Object -First 1
$PriceDual = [double]$PoolDual.$(if ($MiningMode -eq 'Automatic24h') {"Price24h"} else {"Price"})
#Set flag if both Miner and Pool support SSL
$enableDualSSL = ($Miner.SSL -and $PoolDual.SSL)
#Replace wildcards patterns
if ($PoolDual.PoolName -eq 'Nicehash') {
$WorkerNameDual = $WorkerName + '-' + $DeviceGroup.GroupName + 'D' #Nicehash requires alphanumeric WorkerNames
} else {
$WorkerNameDual = $WorkerName + '_' + $DeviceGroup.GroupName + 'D'
}
$PoolUserDual = $PoolDual.User -replace '#WorkerName#', $WorkerNameDual
$PoolPassDual = $PoolDual.Pass -replace '#WorkerName#', $WorkerNameDual
$Params = @{
'#PortDual#' = $(if ($enableDualSSL) {$PoolDual.PortSSL} else {$PoolDual.Port})
'#ServerDual#' = $(if ($enableDualSSL) {$PoolDual.HostSSL} else {$PoolDual.Host})
'#ProtocolDual#' = $(if ($enableDualSSL) {$PoolDual.ProtocolSSL} else {$PoolDual.Protocol})
'#LoginDual#' = $PoolUserDual
'#PasswordDual#' = $PoolPassDual
'#AlgorithmDual#' = $AlgoNameDual
'#WorkerName#' = $WorkerNameDual
}
foreach ($P in $Params.Keys) {$Arguments = $Arguments -replace $P, $Params.$P}
if ($PatternConfigFile -and (Test-Path -Path $PatternConfigFile)) {
foreach ($P in $Params.Keys) {$ConfigFileArguments = $ConfigFileArguments -replace $P, $Params.$P}
}
} else {
$PoolDual = $null
$PoolUserDual = $null
$PriceDual = 0
}
## SubMiner are variations of miner that not need to relaunch
## Creates a "SubMiner" object for each PL
$SubMiners = @()
foreach ($PowerLimit in ($DeviceGroup.PowerLimits)) {
## always exists as least a power limit 0
## look in ActiveMiners collection if we found that miner to conserve some properties and not read files
$FoundMiner = $ActiveMiners | Where-Object {
$_.Name -eq $MinerFile.BaseName -and
$_.Coin -eq $Pool.Info -and
$_.Algorithm -eq $AlgoName -and
$_.CoinDual -eq $PoolDual.Info -and
$_.AlgorithmDual -eq $AlgoNameDual -and
$_.PoolAbbName -eq $Pool.AbbName -and
$_.PoolAbbNameDual -eq $PoolDual.AbbName -and
$_.DeviceGroup.Id -eq $DeviceGroup.Id -and
$_.AlgoLabel -eq $AlgoLabel }
$FoundSubMiner = $FoundMiner.SubMiners | Where-Object {$_.PowerLimit -eq $PowerLimit}
if (!$FoundSubMiner) {
$Params = @{
Algorithm = $Algorithms
MinerName = $MinerFile.BaseName
GroupName = $DeviceGroup.GroupName
PowerLimit = $PowerLimit
AlgoLabel = $AlgoLabel
}
[array]$Hrs = Get-HashRates @Params
} else {
[array]$Hrs = $FoundSubMiner.SpeedReads
}
if ($Hrs.Count -gt 10) {
# Remove 10 percent of lowest and highest rate samples which may skew the average
$Hrs = $Hrs | Sort-Object Speed
$p5Index = [math]::Ceiling($Hrs.Count * 0.05)
$p95Index = [math]::Ceiling($Hrs.Count * 0.95)
$Hrs = $Hrs[$p5Index..$p95Index] | Sort-Object SpeedDual, Speed
$p5Index = [math]::Ceiling($Hrs.Count * 0.05)
$p95Index = [math]::Ceiling($Hrs.Count * 0.95)
$Hrs = $Hrs[$p5Index..$p95Index]
$PowerValue = [double]($Hrs | Measure-Object -property Power -average).average
$HashRateValue = [double]($Hrs | Measure-Object -property Speed -average).average
$HashRateValueDual = [double]($Hrs | Measure-Object -property SpeedDual -average).average
} else {
$PowerValue = 0
$HashRateValue = 0
$HashRateValueDual = 0
}
#calculates revenue
$SubMinerRevenue = [double]($HashRateValue * $Price)
$SubMinerRevenueDual = [double]($HashRateValueDual * $PriceDual)
#apply fee to revenues
$MinerFee = [decimal]$ExecutionContext.InvokeCommand.ExpandString($Miner.Fee)
$SubMinerRevenue *= (1 - $MinerFee)
if (!$FoundSubMiner) {
$Params = @{
Algorithm = $Algorithms
MinerName = $MinerFile.BaseName
GroupName = $DeviceGroup.GroupName
PowerLimit = $PowerLimit
AlgoLabel = $AlgoLabel
}
$StatsHistory = Get-Stats @Params
} else {
$StatsHistory = $FoundSubMiner.StatsHistory
}
$Stats = [PSCustomObject]@{
BestTimes = 0
BenchmarkedTimes = 0
LastTimeActive = [DateTime]0
ActivatedTimes = 0
ActiveTime = 0
FailedTimes = 0
StatsTime = [DateTime]0
}
if (!$StatsHistory) {$StatsHistory = $Stats}
if ($SubMiners.Count -eq 0 -or $SubMiners[0].StatsHistory.BestTimes -gt 0) {
#only add a SubMiner (distinct from first if sometime first was best)
$SubMiners += [PSCustomObject]@{
Id = $SubMiners.Count
Best = $false
BestBySwitch = ""
HashRate = $HashRateValue
HashRateDual = $HashRateValueDual
NeedBenchmark = [bool]($HashRateValue -eq 0 -or ($AlgorithmDual -and $HashRateValueDual -eq 0))
PowerAvg = $PowerValue
PowerLimit = [int]$PowerLimit
PowerLive = 0
Profits = (($SubMinerRevenue + $SubMinerRevenueDual) * $localBTCvalue) - ($ElectricityCostValue * ($PowerValue * 24) / 1000) #Profit is revenue less electricity cost
ProfitsLive = 0
Revenue = $SubMinerRevenue
RevenueDual = $SubMinerRevenueDual
RevenueLive = 0
RevenueLiveDual = 0
SpeedLive = 0
SpeedLiveDual = 0
SpeedReads = if ($null -ne $Hrs) {[array]$Hrs} else {@()}
Status = 'Idle'
Stats = $Stats
StatsHistory = $StatsHistory
TimeSinceStartInterval = [TimeSpan]0
}
}
} #end foreach PowerLimit
$Miners += [PSCustomObject] @{
AlgoLabel = $AlgoLabel
Algorithm = $AlgoName
AlgorithmDual = $AlgoNameDual
Algorithms = $Algorithms
API = $ExecutionContext.InvokeCommand.ExpandString($Miner.API)
Arguments = $ExecutionContext.InvokeCommand.ExpandString($Arguments)
BenchmarkArg = $ExecutionContext.InvokeCommand.ExpandString($Miner.BenchmarkArg)
Coin = $Pool.Info
CoinDual = $PoolDual.Info
ConfigFileArguments = $ExecutionContext.InvokeCommand.ExpandString($ConfigFileArguments)
ExtractionPath = $(".\Bin\" + $MinerFile.BaseName + "\")
GenerateConfigFile = $(if ($PatternConfigFile) {".\Bin\" + $MinerFile.BaseName + "\" + $Miner.GenerateConfigFile -replace '#GroupName#', $DeviceGroup.GroupName -replace '#Algorithm#', $AlgoName})
DeviceGroup = $DeviceGroup
Host = $Pool.Host
Location = $Pool.Location
MinerFee = $MinerFee
Name = $MinerFile.BaseName
Path = $(".\Bin\" + $MinerFile.BaseName + "\" + $ExecutionContext.InvokeCommand.ExpandString($Miner.Path))
PoolAbbName = $Pool.AbbName
PoolAbbNameDual = $PoolDual.AbbName
PoolFee = [double]$Pool.Fee
PoolFeeDual = [double]$PoolDual.Fee
PoolName = $Pool.PoolName
PoolNameDual = $PoolDual.PoolName
PoolPrice = $(if ($MiningMode -eq 'Automatic24h') {[double]$Pool.Price24h} else {[double]$Pool.Price})
PoolPriceDual = $(if ($MiningMode -eq 'Automatic24h') {[double]$PoolDual.Price24h} else {[double]$PoolDual.Price})
PoolRewardType = $Pool.RewardType
PoolWorkers = $Pool.PoolWorkers
PoolWorkersDual = $PoolDual.PoolWorkers
Port = $(if (($DeviceGroups | Where-Object type -eq $DeviceGroup.type).Count -le 1 -and $DelayCloseMiners -eq 0 -and $config.ForceDynamicPorts -ne "Enabled") { $Miner.ApiPort })
PrelaunchCommand = $ExecutionContext.InvokeCommand.ExpandString($Miner.PrelaunchCommand)
PrerequisitePath = $Miner.PrerequisitePath
PrerequisiteURI = $Miner.PrerequisiteURI
SubMiners = $SubMiners
SHA256 = $Miner.SHA256
Symbol = $Pool.Symbol
SymbolDual = $PoolDual.Symbol
URI = $Miner.URI
UserName = $PoolUser
UserNameDual = $PoolUserDual
WalletMode = $Pool.WalletMode
WalletModeDual = $PoolDual.WalletMode
WalletSymbol = $Pool.WalletSymbol
WalletSymbolDual = $PoolDual.WalletSymbol
WorkerName = $WorkerNameMain
WorkerNameDual = $WorkerNameDual
}
} #dualmining
} #end foreach pool
} #end foreach algo
} # end if types
} #end foreach miner
Log-Message "Miners/Pools combinations detected: $($Miners.Count)"
#Launch download of miners
$Miners |
Where-Object {
-not [string]::IsNullOrEmpty($_.URI) -and
-not [string]::IsNullOrEmpty($_.ExtractionPath) -and
-not [string]::IsNullOrEmpty($_.Path)} |
Select-Object URI, ExtractionPath, Path, SHA256 -Unique |
ForEach-Object {
if (-not (Test-Path $_.Path)) {Start-Downloader -URI $_.URI -ExtractionPath $_.ExtractionPath -Path $_.Path -SHA256 $_.SHA256}
}
#Launch download of prerequisites
$Miners |
Where-Object PrerequisitePath |
Select-Object PrerequisitePath, PrerequisiteURI -Unique |
ForEach-Object {
$_.PrerequisitePath = $ExecutionContext.InvokeCommand.ExpandString($_.PrerequisitePath)
if (-not (Test-Path $_.PrerequisitePath)) {
Start-Downloader -URI $_.PrerequisiteURI -Path $_.PrerequisitePath -ExtractionPath $_.PrerequisitePath
}
}
Send-ErrorsToLog $LogFile
#Paint no miners message
$Miners = $Miners | Where-Object {Test-Path $_.Path}
if ($Miners.Count -eq 0) {
Log-Message "NO MINERS! Retry in 30 seconds..." -Severity Warn
Start-Sleep -Seconds 30
Continue
}
#Update the active miners list which is alive for all execution time
foreach ($ActiveMiner in ($ActiveMiners | Sort-Object [int]id)) {
#Search existing miners to update data
$Miner = $Miners | Where-Object {
$_.Name -eq $ActiveMiner.Name -and
$_.Coin -eq $ActiveMiner.Coin -and
$_.Algorithm -eq $ActiveMiner.Algorithm -and
$_.CoinDual -eq $ActiveMiner.CoinDual -and
$_.AlgorithmDual -eq $ActiveMiner.AlgorithmDual -and
$_.PoolAbbName -eq $ActiveMiner.PoolAbbName -and
$_.PoolAbbNameDual -eq $ActiveMiner.PoolAbbNameDual -and
$_.DeviceGroup.Id -eq $ActiveMiner.DeviceGroup.Id -and
$_.AlgoLabel -eq $ActiveMiner.AlgoLabel }
if (($Miner | Measure-Object).count -gt 1) {
Clear-Host
Log-Message "DUPLICATE MINER $($Miner.Algorithms) in $($Miner.Name)" -Severity Warn
Exit
}
if ($Miner) {
# we found that miner
$ActiveMiner.Arguments = $Miner.Arguments
$ActiveMiner.PoolPrice = $Miner.PoolPrice
$ActiveMiner.PoolPriceDual = $Miner.PoolPriceDual
$ActiveMiner.PoolFee = $Miner.PoolFee
$ActiveMiner.PoolFeeDual = $Miner.PoolFeeDual
$ActiveMiner.PoolWorkers = $Miner.PoolWorkers
$ActiveMiner.IsValid = $true
foreach ($SubMiner in $Miner.SubMiners) {
if (($ActiveMiner.SubMiners | Where-Object {$_.Id -eq $SubMiner.Id}).Count -eq 0) {
$SubMiner | Add-Member IdF $ActiveMiner.Id
$ActiveMiner.SubMiners += $SubMiner
} else {
$ActiveMiner.SubMiners[$SubMiner.Id].HashRate = $SubMiner.HashRate
$ActiveMiner.SubMiners[$SubMiner.Id].HashRateDual = $SubMiner.HashRateDual
$ActiveMiner.SubMiners[$SubMiner.Id].NeedBenchmark = $SubMiner.NeedBenchmark
$ActiveMiner.SubMiners[$SubMiner.Id].PowerAvg = $SubMiner.PowerAvg
$ActiveMiner.SubMiners[$SubMiner.Id].Profits = $SubMiner.Profits
$ActiveMiner.SubMiners[$SubMiner.Id].Revenue = $SubMiner.Revenue
$ActiveMiner.SubMiners[$SubMiner.Id].RevenueDual = $SubMiner.RevenueDual
}
}
} else {
#An existing miner is not found now
$ActiveMiner.IsValid = $false
}
}
##Add new miners to list
foreach ($Miner in $Miners) {
$ActiveMiner = $ActiveMiners | Where-Object {
$_.Name -eq $Miner.Name -and
$_.Coin -eq $Miner.Coin -and
$_.Algorithm -eq $Miner.Algorithm -and
$_.CoinDual -eq $Miner.CoinDual -and
$_.AlgorithmDual -eq $Miner.AlgorithmDual -and
$_.PoolAbbName -eq $Miner.PoolAbbName -and
$_.PoolAbbNameDual -eq $Miner.PoolAbbNameDual -and
$_.DeviceGroup.Id -eq $Miner.DeviceGroup.Id -and
$_.AlgoLabel -eq $Miner.AlgoLabel}
if (!$ActiveMiner) {
$Miner.SubMiners | Add-Member IdF $ActiveMiners.Count
$ActiveMiners += [PSCustomObject]@{
AlgoLabel = $Miner.AlgoLabel
Algorithm = $Miner.Algorithm
AlgorithmDual = $Miner.AlgorithmDual
Algorithms = $Miner.Algorithms
API = $Miner.API
Arguments = $Miner.Arguments
BenchmarkArg = $Miner.BenchmarkArg
Coin = $Miner.Coin
CoinDual = $Miner.CoinDual
ConfigFileArguments = $Miner.ConfigFileArguments
GenerateConfigFile = $Miner.GenerateConfigFile
DeviceGroup = $Miner.DeviceGroup
Host = $Miner.Host
Id = $ActiveMiners.Count
IsValid = $true
Location = $Miner.Location
MinerFee = $Miner.MinerFee
Name = $Miner.Name
Path = Convert-Path $Miner.Path
PoolAbbName = $Miner.PoolAbbName
PoolAbbNameDual = $Miner.PoolAbbNameDual
PoolFee = $Miner.PoolFee
PoolFeeDual = $Miner.PoolFeeDual
PoolName = $Miner.PoolName
PoolNameDual = $Miner.PoolNameDual
PoolPrice = $Miner.PoolPrice
PoolPriceDual = $Miner.PoolPriceDual
PoolWorkers = $Miner.PoolWorkers
PoolHashRate = $null
PoolHashRateDual = $null
PoolRewardType = $Miner.PoolRewardType
Port = $Miner.Port
PrelaunchCommand = $Miner.PrelaunchCommand
Process = $null
SubMiners = $Miner.SubMiners
Symbol = $Miner.Symbol
SymbolDual = $Miner.SymbolDual
UserName = $Miner.UserName
UserNameDual = $Miner.UserNameDual
WalletMode = $Miner.WalletMode
WalletSymbol = $Miner.WalletSymbol
WorkerName = $Miner.WorkerName
WorkerNameDual = $Miner.WorkerNameDual
}
}
}
## Reset failed miners after 4 hours
$ActiveMiners.SubMiners | Where-Object {$_.Status -eq 'Failed' -and $_.Stats.LastTimeActive -lt (Get-Date).AddHours(-4)} | ForEach-Object {
$_.Status = 'Idle'
$_.Stats.FailedTimes = 0
Log-Message "Reset failed miner status: $($ActiveMiners[$_.IdF].Name)/$($ActiveMiners[$_.IdF].Algorithms)"
}
Log-Message "Active Miners-pools: $($ActiveMiners.Count)"
Send-ErrorsToLog $LogFile
Log-Message "Pending benchmarks: $(($ActiveMiners | Where-Object IsValid | Select-Object -ExpandProperty SubMiners | Where-Object NeedBenchmark | Select-Object -ExpandProperty Id).Count)..."
$Msg = ($ActiveMiners.SubMiners | ForEach-Object {
"$($_.IdF)-$($_.Id), " +
"$($ActiveMiners[$_.IdF].DeviceGroup.GroupName), " +
"$(if ($ActiveMiners[$_.IdF].IsValid) {'Valid'} else {'Invalid'}), " +
"PL $($_.PowerLimit), " +
"$($_.Status), " +
"$($ActiveMiners[$_.IdF].Name), " +
"$($ActiveMiners[$_.IdF].Algorithms), " +
"$($ActiveMiners[$_.IdF].Coin), " +
"$($ActiveMiners[$_.IdF].Process.Id)"
}) | ConvertTo-Json
Log-Message $Msg -Severity Debug
#For each type, select most profitable miner, not benchmarked has priority, new miner is only lauched if new profit is greater than old by percenttoswitch
#This section changes SubMiner
foreach ($DeviceGroup in $DeviceGroups) {
#look for last round best
$Candidates = $ActiveMiners | Where-Object {$_.DeviceGroup.Id -eq $DeviceGroup.Id}
$BestLast = $Candidates.SubMiners | Where-Object {@("Running", "PendingCancellation") -contains $_.Status}
if ($BestLast) {
$ProfitLast = $BestLast.Profits
$BestLastLogMsg = $(
"$($ActiveMiners[$BestLast.IdF].Name)/" +
"$($ActiveMiners[$BestLast.IdF].Algorithms)/" +
"$($ActiveMiners[$BestLast.IdF].Coin)" +
"$(if ($ActiveMiners[$BestLast.IdF].CoinDual) { '_' + $ActiveMiners[$BestLast.IdF].CoinDual}) " +
"with Power Limit $($BestLast.PowerLimit) " +
"(id $($BestLast.IdF)-$($BestLast.Id)) " +
"for group $($DeviceGroup.GroupName)")
# cancel miner if current pool workers below MinWorkers
if (
$ActiveMiners[$BestLast.IdF].PoolWorkers -ne $null -and
$ActiveMiners[$BestLast.IdF].PoolWorkers -le $config.MinWorkers
) {
$BestLast.Status = 'PendingCancellation'
Log-Message "Cancelling miner due to low worker count"
}
} else {
$ProfitLast = 0
}
if ($BestLast -and $config.SessionStatistics -eq 'Enabled') {
$BestLast | Select-Object -Property `
@{Name = "Date"; Expression = {Get-Date -f "yyyy-MM-dd"}},
@{Name = "Time"; Expression = {Get-Date -f "HH:mm:ss"}},
@{Name = "Group"; Expression = {$DeviceGroup.GroupName}},
@{Name = "Name"; Expression = {$ActiveMiners[$_.IdF].Name}},
@{Name = "Algorithm"; Expression = {$ActiveMiners[$_.IdF].Algorithm}},
@{Name = "AlgorithmDual"; Expression = {$ActiveMiners[$_.IdF].AlgorithmDual}},
@{Name = "AlgoLabel"; Expression = {$ActiveMiners[$_.IdF].AlgoLabel}},
@{Name = "Coin"; Expression = {$ActiveMiners[$_.IdF].Coin}},
@{Name = "CoinDual"; Expression = {$ActiveMiners[$_.IdF].CoinDual}},
@{Name = "PoolName"; Expression = {$ActiveMiners[$_.IdF].PoolName}},
@{Name = "PoolNameDual"; Expression = {$ActiveMiners[$_.IdF].PoolNameDual}},
@{Name = "PowerLimit"; Expression = {$_.PowerLimit}},
@{Name = "HashRate"; Expression = {[decimal]$_.HashRate}},
@{Name = "HashRateDual"; Expression = {[decimal]$_.HashRateDual}},
@{Name = "Revenue"; Expression = {[decimal]$_.Revenue}},
@{Name = "RevenueDual"; Expression = {[decimal]$_.RevenueDual}},
@{Name = "Profits"; Expression = {[decimal]$_.Profits}},
@{Name = "IntervalRevenue"; Expression = {[decimal]$_.Revenue * $Interval.LastTime.TotalSeconds / (24 * 60 * 60)}},
@{Name = "IntervalRevenueDual"; Expression = {[decimal]$_.RevenueDual * $Interval.LastTime.TotalSeconds / (24 * 60 * 60)}},
@{Name = "Interval"; Expression = {[int]$Interval.LastTime.TotalSeconds}} |
Export-Csv -Path $(".\Logs\Stats-" + (Get-Process -PID $PID).StartTime.tostring('yyyy-MM-dd_HH-mm-ss') + ".csv") -Append -NoTypeInformation
}
#check if must cancel miner/algo/coin combo
if ($BestLast.Status -eq 'PendingCancellation') {
if (($ActiveMiners[$BestLast.IdF].SubMiners.Stats.FailedTimes | Measure-Object -sum).sum -ge 3) {
$ActiveMiners[$BestLast.IdF].SubMiners | ForEach-Object {$_.Status = 'Failed'}
Log-Message "Detected more than 3 fails, cancelling combination for $BestNowLogMsg" -Severity Warn
}
}
# look for best for next round
$Candidates = $ActiveMiners | Where-Object {$_.DeviceGroup.Id -eq $DeviceGroup.Id -and $_.IsValid -and $_.UserName}
## Select top miner that need Benchmark, or if running in Manual mode, or highest Profit above zero.
$BestNow = $Candidates.SubMiners |
Where-Object Status -ne 'Failed' |
Where-Object {
$_.NeedBenchmark -or
$_.Profits -gt $Config.('MinProfit_' + $DeviceGroup.GroupName) -or
-not $LocalBTCvalue -gt 0 -or
$MiningMode -eq "Manual" -or
$Interval.Current -eq "Donate"
} |
Sort-Object -Descending NeedBenchmark, {$(if ($MiningMode -eq "Manual") {$_.HashRate} else {$_.Profits})}, {$ActiveMiners[$_.IdF].PoolPrice}, {$ActiveMiners[$_.IdF].PoolPriceDual}, PowerLimit |
Select-Object -First 1