This repository has been archived by the owner on May 12, 2018. It is now read-only.
forked from billaue2/cryptonote-sumokoin-pool
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinit.js
357 lines (301 loc) · 10.1 KB
/
init.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
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
var fs = require('fs');
var http = require('http');
var bignum = require('bignum');
var multiHashing = require('multi-hashing');
var config = JSON.parse(fs.readFileSync('config.json'));
var cryptoNight = multiHashing['cryptonight'];
var reserveSize = 4;
var diff1 = bignum('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', 16);
var connectedMiners = {};
var rpc = function(host, port, method, params, callback){
var data = JSON.stringify({
id: "0",
jsonrpc: "2.0",
method: method,
params: params
});
var options = {
hostname: config.daemon.host,
port: config.daemon.port,
path: '/json_rpc',
method: 'POST',
headers: {
'Content-Length': data.length,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
var req = http.request(options, function(res){
var replyData = '';
res.setEncoding('utf8');
res.on('data', function(chunk){
replyData += chunk;
});
res.on('end', function(){
var replyJson;
try{
replyJson = JSON.parse(replyData);
}
catch(e){
callback(e);
return;
}
callback(replyJson.error, replyJson.result);
});
});
req.on('error', function(e){
callback(e);
});
req.end(data);
};
var rpcDaemon = function(method, params, callback){
rpc(config.daemon.host, config.daemon.port, method, params, callback);
};
var rpcWallet = function(method, params, callback){
rpc(config.wallet.host, config.wallet.port, method, params, callback);
};
//simplewallet --wallet-file=wallet.bin --pass=test --rpc-bind-port=8082
var getBlockTemplate = function(reserveSize, callback){
rpcDaemon('getblocktemplate', {reserve_size: reserveSize, wallet_address: config.wallet.address}, callback);
};
function Miner(id, login, pass){
this.id = id;
this.login = login;
this.pass = pass;
this.heartbeat();
this.difficulty = config.difficulty;
}
Miner.prototype = {
heartbeat: function(){
this.lastBeat = Date.now();
},
getTargetHex: function(){
var buff = diff1.div(config.difficulty).toBuffer().slice(0, 4);
this.target = buff.readUInt32LE(0);
var hex = buff.toString('hex');
return hex;
}
};
setInterval(function(){
var now = Date.now();
var timeout = config.minerTimeout * 1000;
for (var minerId in connectedMiners){
if (now - connectedMiners[minerId].lastBeat > timeout){
delete connectedMiners[minerId];
}
}
}, 10000);
var uid = function(){
var min = 100000000000000;
var max = 999999999999999;
var id = Math.floor(Math.random() * (max - min + 1)) + min;
return id.toString();
};
var CurrentJob = {
height: 0,
nextBlob: function(){
this.buffer.writeUInt32BE(++this.extraNonce, this.reserveOffset);
return this.buffer.toString('hex');
}
};
function processBlockTemplate(template){
CurrentJob.id = uid();
CurrentJob.blob = template.blocktemplate_blob;
CurrentJob.difficulty = template.difficulty;
CurrentJob.height = template.height;
CurrentJob.extraNonce = 0;
CurrentJob.reserveOffset = template.reserved_offset;
CurrentJob.buffer = new Buffer(CurrentJob.blob, 'hex');
for (var minerId in connectedMiners){
var miner = connectedMiners[minerId];
if (miner.longPoll){
console.log('sending new job to longpolled miner');
clearInterval(miner.longPoll.timeout);
miner.longPoll.reply(null, {
blob: CurrentJob.nextBlob(),
job_id: CurrentJob.id,
target: miner.getTargetHex()
});
miner.lastJobId = CurrentJob.id;
miner.extraNonce = CurrentJob.extraNonce;
delete miner.longPoll;
}
}
}
function jobRefresh(){
getBlockTemplate(reserveSize, function(error, result){
if (error){
console.log('error polling getblocktemplate ' + JSON.stringify(error));
return;
}
if (result.height > CurrentJob.height){
console.log('found new block at height ' + result.height + ' w/ difficulty of ' + result.difficulty);
processBlockTemplate(result);
}
setTimeout(jobRefresh, config.blockRefreshInterval);
})
}
jobRefresh();
function processShare(miner, nonce, resultHash){
var shareBuffer = new Buffer(CurrentJob.buffer.length);
CurrentJob.buffer.copy(shareBuffer);
shareBuffer.writeUInt32BE(miner.extraNonce, CurrentJob.reserveOffset);
new Buffer(nonce, 'hex').copy(shareBuffer, 39);
var hash = cryptoNight(shareBuffer);
var hashHex = hash.toString('hex');
if (hashHex !== resultHash) {
console.log('bad hash ' + hashHex + ' vs ' + resultHash);
return false;
}
var hashArray = hash.toJSON();
hashArray.reverse();
var hashNum = bignum.fromBuffer(new Buffer(hashArray));
var hashDiff = diff1.div(hashNum);
if (hashDiff.ge(CurrentJob.difficulty)){
console.log('Block found!');
rpcDaemon('submitblock', [hashHex], function(error, result){
if (error){
console.log('error submitting block ' + JSON.stringify(error));
return;
}
console.log('Block submitted successfully ' + JSON.stringify(result));
});
}
if (hashDiff.lt(miner.difficulty)){
console.log('Rejected low difficulty share of ' + hashDiff.toString());
return false;
}
var hashTarget = hash.readUInt32LE(hash.length - 4);
var percent = (miner.target / hashTarget * 100).toFixed(2);
if (hashTarget > miner.target){
console.log('high target share ' + percent);
return false;
}
console.log('Accepted share at difficulty ' + hashDiff.toString() + ' - ' + percent + '% of target (' + miner.target + '/' + hashTarget + ')');
return true;
}
function handleMinerMethod(id, method, params, res){
var sendReply = function(error, result){
var sendData = JSON.stringify({
id: id,
jsonrpc: "2.0",
error: error ? {code: -1, message: error} : null,
result: result
});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Length', sendData.length);
res.end(sendData);
};
res.on('close', function(){
sendReply = function(){
console.log('tried writing to dead socket');
};
});
switch(method){
case 'login':
if (!params.login){
sendReply("missing login");
return;
}
if (!params.pass){
sendReply("missing pass");
return;
}
var minerId = uid();
var miner = new Miner(minerId, params.login, params.pass);
connectedMiners[minerId] = miner;
sendReply(null, {
id: minerId,
job: {
blob: CurrentJob.nextBlob(),
job_id: CurrentJob.id,
target: miner.getTargetHex()
},
status: 'OK'
});
miner.lastJobId = CurrentJob.id;
miner.extraNonce = CurrentJob.extraNonce;
console.log('miner connected ' + params.login + ':' + params.pass);
break;
case 'getjob':
var miner = connectedMiners[params.id];
if (!miner){
sendReply('Unauthenticated');
return;
}
if (miner.lastJobId === CurrentJob.id) {
if (!config.useLongPolling){
sendReply(null, {
blob: '',
job_id: '',
target: ''
});
return;
}
miner.longPoll = {
timeout: setTimeout(function(){
delete miner.longPoll;
sendReply(null, {
blob: '',
job_id: '',
target: ''
});
}, 5000),
reply: sendReply
};
return;
}
sendReply(null, {
blob: CurrentJob.nextBlob(),
job_id: CurrentJob.id,
target: miner.getTargetHex()
});
miner.lastJobId = CurrentJob.id;
miner.extraNonce = CurrentJob.extraNonce;
break;
case 'submit':
if (!(params.id in connectedMiners)){
sendReply('Unauthenticated');
return;
}
if (params.job_id !== CurrentJob.id){
sendReply('Invalid job id');
return;
}
var shareAccepted = processShare(connectedMiners[params.id], params.nonce, params.result);
if (!shareAccepted){
sendReply('Low difficulty share');
return;
}
sendReply(null, {status: 'OK'});
break;
default:
sendReply("invalid method");
console.log('invalid ' + method + ' ' + JSON.stringify(params));
break;
}
}
var getworkServer = http.createServer(function(req, res){
var data = '';
req.setEncoding('utf8');
req.on('data', function(chunk){
data += chunk;
});
req.on('end', function(){
var jsonData;
try{
jsonData = JSON.parse(data);
}
catch(e){
console.log('error parsing json ' + data);
return;
}
if (!jsonData.id || !jsonData.method){
console.log('miner rpc request missing id or method');
return;
}
handleMinerMethod(jsonData.id, jsonData.method, jsonData.params, res);
});
});
getworkServer.listen(config.poolPort);