57 lines
1.5 KiB
JavaScript
57 lines
1.5 KiB
JavaScript
const crypto = require('crypto');
|
|
|
|
function checkDifficulty(hashBuffer, difficultyBits) {
|
|
let bits = difficultyBits;
|
|
let i = 0;
|
|
while (bits > 0) {
|
|
const byte = hashBuffer[i];
|
|
if (bits >= 8) {
|
|
if (byte !== 0) return false;
|
|
bits -= 8;
|
|
} else {
|
|
const mask = 0xFF << (8 - bits);
|
|
if ((byte & mask) !== 0) return false;
|
|
bits = 0;
|
|
}
|
|
i++;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function main() {
|
|
if (process.argv.length !== 4) {
|
|
console.error(`Usage: node ${process.argv[1]} <challenge_string> <difficulty_bits>`);
|
|
process.exit(1);
|
|
}
|
|
|
|
const challenge = process.argv[2];
|
|
const difficultyBits = parseInt(process.argv[3], 10);
|
|
|
|
if (isNaN(difficultyBits) || difficultyBits <= 0 || difficultyBits > 256) {
|
|
console.error('Difficulty bits must be a number between 1 and 256');
|
|
process.exit(1);
|
|
}
|
|
|
|
let counter = 0;
|
|
|
|
while (true) {
|
|
const input = challenge + counter;
|
|
const hash = crypto.createHash('sha256').update(input).digest();
|
|
|
|
if (checkDifficulty(hash, difficultyBits)) {
|
|
console.log('===================');
|
|
console.log(`Found nonce: ${counter}`);
|
|
console.log('===================');
|
|
console.log(`Hash: ${hash.toString('hex')}`);
|
|
break;
|
|
}
|
|
|
|
if ((counter & 0xFFFFF) === 0) {
|
|
console.log(`Attempts: ${counter}`);
|
|
}
|
|
|
|
counter++;
|
|
}
|
|
}
|
|
|
|
main();
|