-
Notifications
You must be signed in to change notification settings - Fork 132
/
miner.js
128 lines (99 loc) · 2.81 KB
/
miner.js
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
var console = { log: function(m) {
postMessage({ golden_ticket: false, print: m});
}};
var TotalHashes = 0;
var useTimeout = false;
try {
importScripts('sha256.js');
importScripts('util.js');
} catch (e) {
useTimeout = true;
}
var reportPeriod = 1000;
var maxNonce = 0xFFFFFFFF;
var maxCnt = 5;
var run = true;
function scanhash(job, progress_report, cb) {
var midstate = job.midstate;
var data = job.data;
var hash1 = job.hash1;
var target = job.target;
var t = job.t === undefined ? 0 : job.t;
var nonce = job.nonce === undefined ? 0 : job.nonce;
var curCnt = 0;
if (!run || nonce > 0xFFFFFFFF) return;
while(run) {
data[3] = nonce;
sha256.reset();
var h1 = sha256.update(midstate, data).state;
var h2 = hash1;
for (var i=0; i<8; i++) h2[i] = h1[i];
sha256.reset();
var hash = sha256.update(h2).state;
// console.log(derMiner.Util.toPoolString(hash));
if (is_golden_hash(hash, target)) {
job.nonce = nonce;
var r = [];
for (var i = 0; i < job.half.length; i++)
r.push(job.half[i]);
for (var i = 0; i < job.data.length; i++)
r.push(job.data[i]);
var ret = derMiner.Util.toPoolString(r);
cb(ret);
job.golden_ticket = null;
}
if (nonce >= maxNonce) {
cb(null);
break;
}
TotalHashes++;
nonce++;
if (t < (new Date()).getTime()) {
t = (new Date()).getTime() + reportPeriod;
progress_report();
}
if (useTimeout && ++curCnt > maxCnt) {
curCnt = 0;
job.nonce = nonce;
job.t = t;
var c = function() {
scanhash(job, progress_report, cb);
}
window.setTimeout(c, 1);
return;
}
}
return;
}
function is_golden_hash(hash, target)
{
if (hash[7] == 0x00000000) {
var u1 = derMiner.Util.ToUInt32(hash[6]);
var u2 = derMiner.Util.ToUInt32(target[6]);
console.log("worker: checking " + u1 + " <= " + u2);
return (u1 <= u2);
}
return false;
}
///// Web Worker /////
onmessage = function(event) {
if (!event.data || !event.data.run) {
run = false;
console.log("worker: forced quit!");
return;
}
var job = event.data;
job.golden_ticket = false;
sendProgressUpdate(job);
var result = function (golden_ticket) {
job.golden_ticket = golden_ticket;
postMessage(job);
};
scanhash(event.data, function() { sendProgressUpdate(job); }, result);
};
function sendProgressUpdate(job)
{
job.total_hashes = TotalHashes;
postMessage(job);
TotalHashes = 0;
}