-
Notifications
You must be signed in to change notification settings - Fork 3
/
hashcashgen.js
70 lines (64 loc) · 1.51 KB
/
hashcashgen.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
var crypto = require('crypto')
, default_strength = 3
module.exports = exports = function generateHashCash (challenge, strength, cb) {
if (typeof strength === 'function') {
cb = strength;
strength = default_strength;
}
else if (!strength) {
strength = default_strength;
}
var search = repeat('0', strength)
, separator = ':'
, counter = 0
, attempt
function doAttempt () {
attempt = challenge + separator + counter++;
return exports.check(challenge, strength, attempt, search) ? attempt : null;
}
if (cb) {
(function findHashcash () {
var ret = doAttempt();
if (ret) return cb(null, ret);
else {
if (global.setImmediate) {
setImmediate(findHashcash);
}
else {
process.nextTick(findHashcash);
}
}
})();
}
else {
var ret;
do {
ret = doAttempt();
}
while (!ret);
return ret;
}
};
exports.check = function checkHashCash (challenge, strength, hashcash, search) {
if (typeof strength === 'string') {
hashcash = strength;
strength = default_strength;
}
else {
strength || (strength = default_strength);
}
if (!search) search = repeat('0', strength);
return (hashcash.indexOf(challenge) === 0 && sha1(hashcash).indexOf(search) === 0);
};
function repeat (input, length) {
var ret = '';
for (var i = 0; i < length; i++) {
ret += input;
}
return ret;
}
function sha1 (input) {
return crypto.createHash('sha1')
.update(input)
.digest('hex');
}