-
Notifications
You must be signed in to change notification settings - Fork 1
/
difficulty.js
58 lines (50 loc) · 1.67 KB
/
difficulty.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
var bignum = require('./node_modules/bitcoinjs/node_modules/bignum');
require('./node_modules/bitcoinjs/node_modules/buffertools');
/**
* Decode difficulty bits.
*
* This function calculates the difficulty target given the difficulty bits.
*/
var decodeDiffBits = function (diffBits) {
diffBits = +diffBits;
var size = diffBits >>> 24;
var negative = (diffBits & 0x800000 != 0);
var target = bignum(diffBits & 0x7fffff);
if (size <= 3) {
target = target.shiftRight(8*(3-size));
} else {
target = target.shiftLeft(8*(size-3));
}
if (negative === true) target = target.neg();
// Convert to buffer
var diffBuf = target.toBuffer();
var targetBuf = new Buffer(32).clear();
diffBuf.copy(targetBuf, 32-diffBuf.length);
return targetBuf;
};
/**
* Calculate "difficulty".
*
* This function calculates the maximum difficulty target divided by the given
* difficulty target.
*/
var calcDifficulty = function (target) {
if (!Buffer.isBuffer(target)) {
target = decodeDiffBits(target);
}
var targetBigint = bignum.fromBuffer(target, {order: 'forward'});
var maxBigint = bignum('00000000FFFF0000000000000000000000000000000000000000000000000000', 16);
return maxBigint.div(targetBigint).toNumber();
};
var input = process.argv[2];
if (input.indexOf('0x') == 0) {
input = input.substring(2);
} else if (/[A-Fa-f]/.test(input) == false) {
input = parseInt(input).toString(16); // Integer bits given
}
var bits = new Buffer(input, 'hex');
var target = decodeDiffBits(bits.readUInt32BE(0));
var diff = calcDifficulty(target);
console.log('Bits: '+bits.toString('hex'));
console.log('Target: '+target.toString('hex'));
console.log('Difficulty: '+diff);