-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
42 lines (36 loc) · 1.45 KB
/
index.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
/**
* Sintaxe:
* node index.js 3 000 rocketseat
*/
const { isMainThread, Worker, workerData, parentPort } = require('worker_threads');
if (isMainThread) {
const { cpus } = require("os");
const threads = Number.isFinite(Number(process.argv[2])) ? Number(process.argv[2]) : cpus().length;
const prefix = process.argv[3];
const input = process.argv.slice(4).join(" ");
console.log(`Threads Count: ${threads}`);
const workers = [];
for (let i = 0; i < threads; i++) {
const worker = new Worker(__filename, { workerData: { prefix, input } });
workers.push(worker);
worker.on('message', message => {
workers
.filter(otherWorker => otherWorker !== worker)
.forEach(otherWorker => otherWorker.terminate());
console.log(`Worker ${i} / ${message}`);
});
}
} else {
const prefix = workerData.prefix;
const input = workerData.input;
const { createHash } = require("crypto");
const { freemem, totalmem } = require("os");
let nonce;
let hash;
do {
nonce = `+${Math.random().toFixed(17).substring(2)}${Math.random().toFixed(17).substring(2)}`;
hash = createHash('sha256').update(`${input}${nonce}`).digest('hex');
memory = ((1 - freemem() / totalmem()) * 100).toFixed(2) + '%';
} while (!hash.startsWith(prefix));
parentPort.postMessage(`Input: ${input} / Nonce: ${nonce} / Hash: ${hash} / Memory: ${memory}`);
}