-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathjobManager.js
More file actions
225 lines (189 loc) · 6.55 KB
/
jobManager.js
File metadata and controls
225 lines (189 loc) · 6.55 KB
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
const events = require('events');
const bignum = require('bignum');
const blockTemplate = require('./blockTemplate.js');
const constants = require('./constants.js');
const util = require('./util');
//Unique job per new block template
var JobCounter = function(){
var counter = 0;
this.next = function(){
counter++;
if (counter % 0xffff === 0)
counter = 1;
return this.cur();
};
this.cur = function () {
return counter.toString(16);
};
};
var ErrorCodes = {
JobNotFound: 20,
InvalidJobChainIndex: 21,
InvalidWorker: 22,
InvalidNonce: 23,
DuplicatedShare: 24,
LowDifficulty: 25,
InvalidBlockChainIndex: 26
};
function isStringType(value){
return (typeof value === 'string') || (value instanceof String);
}
function MiningJobs(expiryDuration){
var _this = this;
this.jobsList = [];
this.jobMap = {};
this.removeExpiredJobs = function(now){
while (now - _this.jobsList[0][0].timestamp > expiryDuration){
var expiredJobs = _this.jobsList.shift();
expiredJobs.forEach(job => delete _this.jobMap[job.jobId]);
}
}
this.addJobs = function(jobs, now){
_this.jobsList.push(jobs);
_this.removeExpiredJobs(now);
jobs.forEach(job => _this.jobMap[job.jobId] = job);
}
this.getJob = function(jobId){
return _this.jobMap[jobId];
}
}
/**
* Emits:
* - newJobs(jobs) - Use this event to broadcast new jobs
* - share(shareData) - It will have blockHex if a block was found
**/
function JobManager(jobExpiryPeriod){
//private members
var _this = this;
var jobCounter = new JobCounter();
//public members
this.validJobs = new MiningJobs(jobExpiryPeriod);
this.processJobs = function(jobs){
var now = Date.now();
var miningJobs = jobs.map(job => {
var jobId = jobCounter.next();
job.jobId = jobId;
return new blockTemplate(job, now);
})
_this.validJobs.addJobs(miningJobs, now);
_this.emit('newJobs', miningJobs);
};
function validateNonce(nonceHex){
if (!isStringType(nonceHex)){
return null;
}
var nonce = null;
try {
nonce = Buffer.from(nonceHex, 'hex');
} catch (error) {
return null;
}
if (nonce.length === constants.NonceLength){
return nonce;
}
return null;
}
function addressIsValid(addressStr){
var [_, error] = util.groupOfAddress(addressStr);
return error == null;
}
this.getWorkerAddress = function(worker){
if (!isStringType(worker)){
return null;
}
var index = worker.indexOf('.');
if (index === -1){
return addressIsValid(worker) ? worker : null;
}
// try to decode address from prefix
var address = worker.slice(0, index);
if (addressIsValid(address)){
var workerName = worker.slice(index + 1);
return workerName.length > 32 ? null : address;
}
// try to decode address from postfix
index = worker.lastIndexOf('.');
address = worker.slice(index + 1);
if (addressIsValid(address)){
var workerName = worker.slice(0, index);
return workerName.length > 32 ? null : address;
}
return null;
}
this.processShare = function(params, previousDifficulty, difficulty, remoteAddress, localPort){
var shareError = function(error){
_this.emit('share', {
job: params.jobId,
ip: remoteAddress,
worker: params.worker,
difficulty: difficulty,
error: error[1]
});
return {error: error};
};
var job = _this.validJobs.getJob(params.jobId);
if (typeof job === 'undefined' || job.jobId != params.jobId ) {
return shareError([ErrorCodes.JobNotFound, 'job not found, maybe expired']);
}
if ((params.fromGroup != job.fromGroup) || (params.toGroup != job.toGroup)){
return shareError([ErrorCodes.InvalidJobChainIndex, 'invalid job chain index']);
}
var address = _this.getWorkerAddress(params.worker);
if (!address){
return shareError([ErrorCodes.InvalidWorker, 'invalid worker']);
}
var nonce = validateNonce(params.nonce);
if (!nonce) {
return shareError([ErrorCodes.InvalidNonce, 'invalid nonce']);
}
if (!job.registerSubmit(params.nonce)) {
return shareError([ErrorCodes.DuplicatedShare, 'duplicate share']);
}
var hash = job.hash(nonce);
var [fromGroup, toGroup] = util.blockChainIndex(hash);
if ((fromGroup != job.fromGroup) || (toGroup != job.toGroup)){
return shareError([ErrorCodes.InvalidBlockChainIndex, 'invalid block chain index']);
}
var hashBigNum = bignum.fromBuffer(hash);
var shareDiff = global.diff1Target.mul(1024).div(hashBigNum).toNumber() / 1024.0;
var foundBlock = false;
//Check if share is a block candidate (matched network difficulty)
if (job.target.ge(hashBigNum)){
foundBlock = true;
}
else {
//Check if share didn't reached the miner's difficulty)
if (shareDiff < difficulty){
//Check if share matched a previous difficulty from before a vardiff retarget
if (previousDifficulty && shareDiff >= previousDifficulty){
difficulty = previousDifficulty;
}
else{
return shareError([ErrorCodes.LowDifficulty,
'low difficulty share of ' + shareDiff +
', current difficulty: ' + difficulty +
', previous difficulty: ' + previousDifficulty]
);
}
}
}
_this.emit('share', {
job: job,
nonce: nonce,
ip: remoteAddress,
port: localPort,
worker: params.worker,
workerAddress: address,
difficulty: difficulty,
shareDiff: shareDiff,
blockHash: hash.toString('hex'),
foundBlock: foundBlock
});
return {error: null};
};
};
JobManager.prototype.__proto__ = events.EventEmitter.prototype;
exports.JobManager = JobManager;
exports.ErrorCodes = ErrorCodes;
exports.MiningJobs = MiningJobs;
exports.JobCounter = JobCounter;