-
Notifications
You must be signed in to change notification settings - Fork 2
/
pool.js
859 lines (708 loc) · 33.5 KB
/
pool.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
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
var bignum = require('bignum');
var events = require('events');
var async = require('async');
var varDiff = require('./varDiff.js');
var daemon = require('./daemon.js');
var peer = require('./peer.js');
var stratum = require('./stratum.js');
var jobManager = require('./jobManager.js');
var util = require('./util.js');
/*process.on('uncaughtException', function(err) {
console.log(err.stack);
throw err;
});*/
var pool = module.exports = function pool(options, authorizeFn){
this.options = options;
var _this = this;
var blockPollingIntervalId;
var emitLog = function(text) { _this.emit('log', 'debug' , text); };
var emitInfoLog = function(text) { _this.emit('log', 'info' , text); };
var emitWarningLog = function(text) { _this.emit('log', 'warning', text); };
var emitErrorLog = function(text) { _this.emit('log', 'error' , text); };
var emitSpecialLog = function(text) { _this.emit('log', 'special', text); };
if (!(options.coin.algorithm in algos)){
emitErrorLog('The ' + options.coin.algorithm + ' hashing algorithm is not supported.');
throw new Error();
}
this.start = function(){
SetupVarDiff();
SetupApi();
SetupDaemonInterfaces(function(){
DetectCoinData(function(){
SetupRecipients();
SetupJobManager();
OnBlockchainSynced(function(){
GetFirstJob(function(){
SetupBlockPolling();
SetupPeer();
StartStratumServer(function(){
OutputPoolInfo();
_this.emit('started');
});
});
});
});
});
};
function UpdateAuxes(finishedCallback) {
if(!finishedCallback)
finishedCallback = function() {};
var indexes = [];
if(options.auxes) {
for(var i = 0;i < options.auxes.length;i++) indexes.push(i);
} // or make sure options.auxes always exists, even if empty. This seems cleaner.
_this.updateNeeded = false;
async.each(indexes, GetAuxWork, function(err) {
if(err) emitErrorLog('could not update auxillary chains: ' + err);
if(_this.updateNeeded) {
GetBlockTemplate(function() {
if (indexes.length > 0){
for(var i = 0;i < indexes.length;i++) {
emitLog('added updating work for auxillary chains ' + options.auxes[i].coin.name);
}
} else {
emitLog('added updating work for auxillary chains ' + options.auxes[0].coin.name);
}
}, true);
}
finishedCallback();
});
}
function GetFirstJob(finishedCallback){
// Get work from auxillary chains every 5 seconds, perpetually
UpdateAuxes(function() {
GetBlockTemplate(function(error, result){
if (error) {
emitErrorLog('Error with getblocktemplate on creating first job, server cannot start');
return;
}
var portWarnings = [];
var networkDiffAdjusted = options.initStats.difficulty;
Object.keys(options.ports).forEach(function(port){
var portDiff = options.ports[port].diff;
if (networkDiffAdjusted < portDiff)
portWarnings.push('port ' + port + ' w/ diff ' + portDiff);
});
//Only let the first fork show synced status or the log wil look flooded with it
if (portWarnings.length > 0 && (!process.env.forkId || process.env.forkId === '0')) {
var warnMessage = 'Network diff of ' + networkDiffAdjusted + ' is lower than ' + portWarnings.join(' and ');
emitWarningLog(warnMessage);
}
setInterval(UpdateAuxes, 5000);
finishedCallback();
});
});
}
function OutputPoolInfo(){
var startMessage = 'started for ' + options.coin.name +
' [' + options.coin.symbol.toUpperCase() + '] {' + options.coin.algorithm + '}';
if (process.env.forkId && process.env.forkId !== '0'){
emitLog(startMessage);
return;
}
var infoLines = [startMessage,
'Network Connected:\t' + (options.testnet ? 'Testnet' : 'Mainnet'),
'Detected Reward Type:\t' + options.coin.reward,
'Current Block Height:\t' + _this.jobManager.currentJob.rpcData.height,
'Current Connect Peers:\t' + options.initStats.connections,
'Current Block Diff:\t' + _this.jobManager.currentJob.difficulty * algos[options.coin.algorithm].multiplier,
'Network Difficulty:\t' + options.initStats.difficulty,
'Network Hash Rate:\t' + util.getReadableHashRateString(options.initStats.networkHashRate),
'Stratum Port(s):\t' + _this.options.initStats.stratumPorts.join(', '),
'Pool Fee Percent:\t' + _this.options.feePercent + '%'
];
if (typeof options.blockRefreshInterval === "number" && options.blockRefreshInterval > 0)
infoLines.push('Block polling every:\t' + options.blockRefreshInterval + ' ms');
emitSpecialLog(infoLines.join('\n\t\t\t\t\t\t'));
}
function OnBlockchainSynced(syncedCallback){
var checkSynced = function(displayNotSynced){
gbtParams = [];
if (options.coin.reward == "POW"){
gbtParams = [{"capabilities": [ "coinbasetxn", "workid", "coinbase/append" ], "rules": [ "segwit" ]}];
}
_this.daemon.cmd('getblocktemplate',
gbtParams,
function(results){
var synced = results.every(function(r){
return !r.error || r.error.code !== -10;
});
if (synced){
syncedCallback();
}
else{
if (displayNotSynced) displayNotSynced();
setTimeout(checkSynced, 5000);
//Only let the first fork show synced status or the log wil look flooded with it
if (!process.env.forkId || process.env.forkId === '0')
generateProgress();
}
}
);
};
checkSynced(function(){
//Only let the first fork show synced status or the log wil look flooded with it
if (!process.env.forkId || process.env.forkId === '0')
emitErrorLog('Daemon is still syncing with network (download blockchain) - server will be started once synced');
});
var generateProgress = function(){
_this.daemon.cmd('getinfo', [], function(results) {
var blockCount = results.sort(function (a, b) {
return b.response.blocks - a.response.blocks;
})[0].response.blocks;
//get list of peers and their highest block height to compare to ours
_this.daemon.cmd('getpeerinfo', [], function(results){
var peers = results[0].response;
var totalBlocks = peers.sort(function(a, b){
return b.startingheight - a.startingheight;
})[0].startingheight;
var percent = (blockCount / totalBlocks * 100).toFixed(2);
emitWarningLog('Downloaded ' + percent + '% of blockchain from ' + peers.length + ' peers');
});
});
};
}
function SetupApi() {
if (typeof(options.api) !== 'object' || typeof(options.api.start) !== 'function') {
return;
} else {
options.api.start(_this);
}
}
function SetupPeer(){
if (!options.p2p || !options.p2p.enabled)
return;
if (options.testnet && !options.coin.peerMagicTestnet){
emitErrorLog('p2p cannot be enabled in testnet without peerMagicTestnet set in coin configuration');
return;
}
else if (!options.coin.peerMagic){
emitErrorLog('p2p cannot be enabled without peerMagic set in coin configuration');
return;
}
_this.peer = new peer(options);
_this.peer.on('connected', function() {
emitLog('p2p connection successful');
}).on('connectionRejected', function(){
emitErrorLog('p2p connection failed - likely incorrect p2p magic value');
}).on('disconnected', function(){
emitWarningLog('p2p peer node disconnected - attempting reconnection...');
}).on('connectionFailed', function(e){
emitErrorLog('p2p connection failed - likely incorrect host or port');
}).on('socketError', function(e){
emitErrorLog('p2p had a socket error ' + JSON.stringify(e));
}).on('error', function(msg){
emitWarningLog('p2p had an error ' + msg);
}).on('blockFound', function(hash){
_this.processBlockNotify(hash, 'p2p');
});
}
function SetupVarDiff(){
_this.varDiff = {};
Object.keys(options.ports).forEach(function(port) {
if (options.ports[port].varDiff)
_this.setVarDiff(port, options.ports[port].varDiff);
});
}
/*
Coin daemons either use submitblock or getblocktemplate for submitting new blocks
*/
function SubmitBlock(blockHex, finishedCallback){
var rpcCommand, rpcArgs;
if (options.hasSubmitMethod){
rpcCommand = 'submitblock';
rpcArgs = [blockHex];
}
else{
rpcCommand = 'getblocktemplate';
rpcArgs = [{'mode': 'submit', 'data': blockHex}];
}
_this.daemon.cmd(rpcCommand,
rpcArgs,
function(results){
for (var i = 0; i < results.length; i++){
var result = results[i];
if (result.error) {
emitErrorLog('rpc error with daemon instance ' +
result.instance.index + ' when submitting block with ' + rpcCommand + ' ' +
JSON.stringify(result.error)
);
return;
}
else if (result.response === 'rejected') {
emitErrorLog('Daemon instance ' + result.instance.index + ' rejected a supposedly valid block');
return;
}
}
emitLog('Submitted Block using ' + rpcCommand + ' successfully to daemon instance(s)');
finishedCallback();
}
);
}
function SubmitAuxBlock(aux, headerBuffer, coinbaseBuffer, blockHash, callback) {
var branchProof = _this.jobManager.auxMerkleTree.getHashProof(util.uint256BufferFromHash(_this.auxes[aux].rpcData.hash));
if(!branchProof) branchProof = Buffer.concat([util.varIntBuffer(0), util.packInt32LE(0)]);
var coinbaseProof =
Buffer.concat([
util.varIntBuffer(_this.jobManager.currentJob.merkleTree.steps.length),
Buffer.concat(_this.jobManager.currentJob.merkleTree.steps),
util.packInt32LE(0)]
);
var auxpow = Buffer.concat([
coinbaseBuffer,
blockHash,
coinbaseProof,
branchProof,
headerBuffer]
);
_this.auxes[aux].daemon.cmd('getauxblock',
[_this.auxes[aux].rpcData.hash, auxpow.toString('hex')],
function(results) {
//console.log(results);
//console.log(_this.auxes[aux]);
for (var i = 0; i < results.length; i++){
var result = results[i];
if(result.error && result.error !== null) {
emitErrorLog('Failed to submit potential auxiliary block: ' + JSON.stringify(result.error));
return;
} else {
if(!result.response) {
emitWarningLog('Submitted auxiliary block was rejected by the ' + _this.auxes[aux].name + ' network! Check its log for more information');
return;
}
}
}
emitInfoLog('Submitted auxiliary block successfully to the '+_this.auxes[aux].name+' daemon instance(s) with BlockHash: '+ _this.auxes[aux].rpcData.hash);
callback(_this.auxes[aux].rpcData.hash, aux);
});
}
function SetupRecipients(){
var recipients = [];
options.feePercent = 0;
options.rewardRecipients = options.rewardRecipients || {};
for (var r in options.rewardRecipients){
var percent = options.rewardRecipients[r];
var rObj = {
percent: percent
};
try {
if (r.length === 40)
rObj.script = util.miningKeyToScript(r);
else
rObj.script = util.addressToScript(r);
recipients.push(rObj);
options.feePercent += percent;
}
catch(e){
emitErrorLog('Error generating transaction output script for ' + r + ' in rewardRecipients');
}
}
if (recipients.length === 0){
emitErrorLog('No rewardRecipients have been setup which means no fees will be taken');
}
options.recipients = recipients;
}
function SetupJobManager(){
_this.jobManager = new jobManager(options);
_this.jobManager.on('newBlock', function(blockTemplate){
//Check if stratumServer has been initialized yet
if (_this.stratumServer) {
_this.stratumServer.broadcastMiningJobs(blockTemplate.getJobParams());
}
}).on('updatedBlock', function(blockTemplate){
//Check if stratumServer has been initialized yet
if (_this.stratumServer) {
var job = blockTemplate.getJobParams();
job[8] = false;
_this.stratumServer.broadcastMiningJobs(job);
}
}).on('share', function(shareData, blockHexInvalid, blockHex){
var auxResult = function(hash, aux) {
if(!hash) return;
CheckBlockAccepted(hash, _this.auxes[aux].daemon, function(accepted, tx, height, value) {
if(!accepted) emitErrorLog('Block was not detected to have been accepted by ' + _this.auxes[aux].name + ' network: ' + hash);
// Push a message to alert that an auxillary block was found
// First get transaction ID of our coinbase transaction
_this.auxes[aux].daemon.cmd('gettransaction', [tx], function(res) {
var cmdResponse = res[0].response;
var cmdError = res[0].error;
if(cmdError) {
emitErrorLog('Some error occured: ' + JSON.stringify(cmdError));
}
else {
_this.emit('auxblock', options.auxes[aux].symbol, height, hash, tx, cmdResponse.details[0].amount, shareData.difficulty, shareData.worker);
}
});
UpdateAuxes();
// Cant do anything here yet
// Skip the get block template. Just a secondary test
});
};
if(!shareData.error) {
for(var i = 0;i < _this.auxes.length;i++) {
//var aux = ;
if(_this.auxes[i].rpcData.target.ge(shareData.blockBigNum)) {
SubmitAuxBlock(i, new Buffer(blockHexInvalid, 'hex').slice(0,80), shareData.coinbaseBuffer, shareData.headerHash, auxResult);
}
}
}
// Now for parent chain checking
var isValidShare = !shareData.error;
var isValidBlock = !!blockHex;
var emitShare = function(){
_this.emit('share', isValidShare, isValidBlock, shareData);
};
/*
If we calculated that the block solution was found,
before we emit the share, lets submit the block,
then check if it was accepted using RPC getblock
*/
if (!isValidBlock)
emitShare();
else{
SubmitBlock(blockHex, function(){
CheckBlockAccepted(shareData.blockHash, _this.daemon, function(isAccepted, tx, height, value){
isValidBlock = isAccepted;
shareData.txHash = tx;
emitShare();
// Also emit the new block callback
_this.emit('block', options.coin.symbol, height, shareData.blockHash, tx, shareData.blockReward * 0.00000001, shareData.difficulty, shareData.worker);
GetBlockTemplate(function(error, result, foundNewBlock) {
if (foundNewBlock)
emitLog('Block notification via RPC after block submission');
});
});
});
}
}).on('log', function(severity, message){
_this.emit('log', severity, message);
});
}
function SetupDaemonInterfaces(finishedCallback){
if (!Array.isArray(options.daemons) || options.daemons.length < 1){
emitErrorLog('No daemons have been configured - pool cannot start');
return;
}
var setupDaemon = function(daemons, callback) {
if(!callback) callback = function() {};
var d = new daemon.interface(daemons, function(severity, message){
_this.emit('log', severity , message);
});
d.once('online', function(){
callback();
}).on('connectionFailed', function(error){
emitErrorLog('Failed to connect daemon(s): ' + JSON.stringify(error));
}).on('error', function(message){
emitErrorLog(message);
});
d.init();
return d;
};
// Setup auxillary daemons
_this.auxes = [];
if (options.auxes) {
for(var i = 0;i < options.auxes.length;i++) {
if(!Array.isArray(options.auxes[i].daemons) || options.auxes[i].daemons.length < 1) {
emitErrorLog('No daemons have been configured for the auxillary coin: ' + options.auxes[i].name + '. Please specify before the pool starts.');
_this.daemon = undefined; // Should force program to close naturally
return;
}
var a = {};
a.name = options.auxes[i].name; // I want at least this...
a.daemon = setupDaemon(options.auxes[i].daemons);
_this.auxes.push(a);
}
}
// Setup parent daemon
_this.daemon = setupDaemon(options.daemons, finishedCallback);
}
function DetectCoinData(finishedCallback){
var batchRpcCalls = [
['validateaddress', [options.address]],
['getdifficulty', []],
['getinfo', []],
['getmininginfo', []],
['submitblock', []]
];
_this.daemon.batchCmd(batchRpcCalls, function(error, results){
if (error || !results){
console.log(results)
emitErrorLog('Could not start pool, error with init batch RPC call: ' + JSON.stringify(error));
return;
}
var rpcResults = {};
for (var i = 0; i < results.length; i++){
var rpcCall = batchRpcCalls[i][0];
var r = results[i];
rpcResults[rpcCall] = r.result || r.error;
if (rpcCall !== 'submitblock' && (r.error || !r.result)){
emitErrorLog('Could not start pool, error with init RPC ' + rpcCall + ' - ' + JSON.stringify(r.error));
console.log(rpcResults[rpcCall])
return;
}
}
if (!rpcResults.validateaddress.isvalid){
emitErrorLog('Daemon reports address is not valid');
return;
}
if (!options.coin.reward) {
if (isNaN(rpcResults.getdifficulty) && 'proof-of-stake' in rpcResults.getdifficulty)
options.coin.reward = 'POS';
else
options.coin.reward = 'POW';
}
/* POS coins must use the pubkey in coinbase transaction, and pubkey is
only given if address is owned by wallet.*/
if (options.coin.reward === 'POS' && typeof(rpcResults.validateaddress.pubkey) == 'undefined') {
emitErrorLog('The address provided is not from the daemon wallet - this is required for POS coins.');
return;
}
options.poolAddressScript = (function(){
switch(options.coin.reward){
case 'POS':
return util.pubkeyToScript(rpcResults.validateaddress.pubkey);
case 'POW':
return util.addressToScript(rpcResults.validateaddress.address);
}
})();
options.testnet = rpcResults.getinfo.testnet;
options.protocolVersion = rpcResults.getinfo.protocolversion;
options.initStats = {
connections: rpcResults.getinfo.connections,
difficulty: rpcResults.getinfo.difficulty * algos[options.coin.algorithm].multiplier,
networkHashRate: rpcResults.getmininginfo.networkhashps
};
if (rpcResults.submitblock.message === 'Method not found'){
options.hasSubmitMethod = false;
}
else if (rpcResults.submitblock.code === -1){
options.hasSubmitMethod = true;
}
else {
emitErrorLog('Could not detect block submission RPC method, ' + JSON.stringify(results));
return;
}
finishedCallback();
});
}
function StartStratumServer(finishedCallback){
_this.stratumServer = new stratum.Server(options, authorizeFn);
_this.stratumServer.on('started', function(){
options.initStats.stratumPorts = Object.keys(options.ports);
_this.stratumServer.broadcastMiningJobs(_this.jobManager.currentJob.getJobParams());
finishedCallback();
}).on('broadcastTimeout', function(){
emitLog('No new blocks for ' + options.jobRebroadcastTimeout + ' seconds - updating transactions & rebroadcasting work');
GetBlockTemplate(function(error, rpcData, processedBlock){
if (error || processedBlock) return;
_this.jobManager.updateCurrentJob(rpcData);
});
}).on('client.connected', function(client){
if (typeof(_this.varDiff[client.socket.localPort]) !== 'undefined') {
_this.varDiff[client.socket.localPort].manageClient(client);
}
client.on('difficultyChanged', function(diff){
_this.emit('difficultyUpdate', client.workerName, diff);
}).on('subscription', function(params, resultCallback){
var extraNonce = _this.jobManager.extraNonceCounter.next();
var extraNonce2Size = _this.jobManager.extraNonce2Size;
resultCallback(null,
extraNonce,
extraNonce2Size
);
if (typeof(options.ports[client.socket.localPort]) !== 'undefined' && options.ports[client.socket.localPort].diff) {
this.sendDifficulty(options.ports[client.socket.localPort].diff);
} else {
this.sendDifficulty(8);
}
this.sendMiningJob(_this.jobManager.currentJob.getJobParams());
}).on('submit', function(params, resultCallback){
var result =_this.jobManager.processShare(
params.jobId,
client.previousDifficulty,
client.difficulty,
client.extraNonce1,
params.extraNonce2,
params.nTime,
params.nonce,
client.remoteAddress,
client.socket.localPort,
params.name
);
resultCallback(result.error, result.result ? true : null);
}).on('malformedMessage', function (message) {
emitWarningLog('Malformed message from ' + client.getLabel() + ': ' + message);
}).on('socketError', function(err) {
emitWarningLog('Socket error from ' + client.getLabel() + ': ' + JSON.stringify(err));
}).on('socketTimeout', function(reason){
emitWarningLog('Connected timed out for ' + client.getLabel() + ': ' + reason)
}).on('socketDisconnect', function() {
//emitLog('Socket disconnected from ' + client.getLabel());
}).on('kickedBannedIP', function(remainingBanTime){
emitLog('Rejected incoming connection from ' + client.remoteAddress + ' banned for ' + remainingBanTime + ' more seconds');
}).on('forgaveBannedIP', function(){
emitLog('Forgave banned IP ' + client.remoteAddress);
}).on('unknownStratumMethod', function(fullMessage) {
emitLog('Unknown stratum method from ' + client.getLabel() + ': ' + fullMessage.method);
}).on('socketFlooded', function() {
emitWarningLog('Detected socket flooding from ' + client.getLabel());
}).on('tcpProxyError', function(data) {
emitErrorLog('Client IP detection failed, tcpProxyProtocol is enabled yet did not receive proxy protocol message, instead got data: ' + data);
}).on('bootedBannedWorker', function(){
emitWarningLog('Booted worker ' + client.getLabel() + ' who was connected from an IP address that was just banned');
}).on('triggerBan', function(reason){
emitWarningLog('Banned triggered for ' + client.getLabel() + ': ' + reason);
_this.emit('banIP', client.remoteAddress, client.workerName);
});
});
}
function SetupBlockPolling(){
if (typeof options.blockRefreshInterval !== "number" || options.blockRefreshInterval <= 0){
emitLog('Block template polling has been disabled');
return;
}
var pollingInterval = options.blockRefreshInterval;
blockPollingIntervalId = setInterval(function () {
GetBlockTemplate(function(error, result, foundNewBlock){
if (foundNewBlock)
emitLog('getting block notification via RPC polling');
});
}, pollingInterval);
}
function GetBlockTemplate(callback, force){
gbtParams = [];
if (_this.options.coin.getblocktemplate == "POS") {
gbtParams = [{"mode": "template" }];
} else {
gbtParams = [{"capabilities": [ "coinbasetxn", "workid", "coinbase/append" ], "rules": [ "segwit" ]}];
}
_this.daemon.cmd('getblocktemplate',
gbtParams,
function(result){
if (result.error){
emitErrorLog('getblocktemplate call failed for daemon instance ' +
result.instance.index + ' with error ' + JSON.stringify(result.error));
callback(result.error);
} else {
// Add auxes to the RPC data to process
var data = result.response;
data.auxes = [];
for(var i = 0;i < _this.auxes.length;i++) data.auxes.push(_this.auxes[i].rpcData);
var processedNewBlock = _this.jobManager.isNewWork(data);
if(processedNewBlock || force) _this.jobManager.processTemplate(data);
callback(null, result.response, processedNewBlock);
callback = function(){};
}
}, true
);
}
function GetAuxWork(index, callback){
_this.auxes[index].daemon.cmd('getauxblock', [],
function(result){
if (result.error){
emitErrorLog('getauxblock call failed for daemon instance ' +
result.instance.index + ' with error ' + JSON.stringify(result.error));
callback(result.error);
} else {
// Process response
if(_this.auxes[index].rpcData) {
if(_this.auxes[index].rpcData.hash != result.response.hash) _this.updateNeeded = true;
}
_this.auxes[index].rpcData = result.response;
_this.auxes[index].rpcData.target = bignum.fromBuffer(util.uint256BufferFromHash(_this.auxes[index].rpcData.target, {endian: 'little', size: 32}));
callback(null, result.response, false);
//callback = function(){};
}
}, true);
}
function CheckBlockAccepted(blockHash, daemon, callback){
//setTimeout(function(){
daemon.cmd('getblock',
[blockHash],
function(results){
var validResults = results.filter(function(result){
return result.response && (result.response.hash === blockHash);
});
if (validResults.length >= 1){
callback(true, validResults[0].response.tx[0], validResults[0].response.height);
}
else{
callback(false);
}
}
);
//}, 500);
}
/**
* This method is being called from the blockNotify so that when a new block is discovered by the daemon
* We can inform our miners about the newly found block
**/
this.processBlockNotify = function(blockHash, sourceTrigger) {
emitLog('Block notification via ' + sourceTrigger);
if (typeof(_this.jobManager) !== 'undefined'){
if (typeof(_this.jobManager.currentJob) !== 'undefined' && blockHash !== _this.jobManager.currentJob.rpcData.previousblockhash){
GetBlockTemplate(function(error, result){
if (error)
emitErrorLog('Block notify error getting block template for ' + options.coin.name);
});
}
}
};
this.relinquishMiners = function(filterFn, resultCback) {
var origStratumClients = this.stratumServer.getStratumClients();
var stratumClients = [];
Object.keys(origStratumClients).forEach(function (subId) {
stratumClients.push({subId: subId, client: origStratumClients[subId]});
});
async.filter(
stratumClients,
filterFn,
function (clientsToRelinquish) {
clientsToRelinquish.forEach(function(cObj) {
cObj.client.removeAllListeners();
_this.stratumServer.removeStratumClientBySubId(cObj.subId);
});
process.nextTick(function () {
resultCback(
clientsToRelinquish.map(
function (item) {
return item.client;
}
)
);
});
}
);
};
this.attachMiners = function(miners) {
miners.forEach(function (clientObj) {
_this.stratumServer.manuallyAddStratumClient(clientObj);
});
_this.stratumServer.broadcastMiningJobs(_this.jobManager.currentJob.getJobParams());
};
this.getStratumServer = function() {
return _this.stratumServer;
};
this.setVarDiff = function(port, varDiffConfig) {
if (typeof(_this.varDiff[port]) != 'undefined' ) {
_this.varDiff[port].removeAllListeners();
}
var varDiffInstance = new varDiff(port, varDiffConfig);
_this.varDiff[port] = varDiffInstance;
_this.varDiff[port].on('newDifficulty', function(client, newDiff) {
/* We request to set the newDiff @ the next difficulty retarget
(which should happen when a new job comes in - AKA BLOCK) */
client.enqueueNextDifficulty(newDiff);
/*if (options.varDiff.mode === 'fast'){
//Send new difficulty, then force miner to use new diff by resending the
//current job parameters but with the "clean jobs" flag set to false
//so the miner doesn't restart work and submit duplicate shares
client.sendDifficulty(newDiff);
var job = _this.jobManager.currentJob.getJobParams();
job[8] = false;
client.sendMiningJob(job);
}*/
});
};
};
pool.prototype.__proto__ = events.EventEmitter.prototype;