Am i able to mine bitcoin in node.js from ViaBTC pool? I want theres a means, if you already know please inform me.
I attempted to look within the web and that i didnt discovered nothing, i requested chatgpt however offers me flawed code, it doesnt confirm, for the devs who need the code, its this
Index.js
const web = require('web');
const crypto = require('crypto');
const { Employee } = require('worker_threads');
const pool = {
host: 'btc.viabtc.io',
port: 3333,
person: 'person',
go: 'go'
};
let extranonce1 = '';
let extranonce2Size = 0;
let employees = [];
let totalHashrate = 0;
// Crear conexión con la pool
const consumer = new web.Socket();
consumer.join(pool.port, pool.host, () => {
console.log('Conectado a la pool');
consumer.write(JSON.stringify({
id: 1,
methodology: 'mining.subscribe',
params: []
}) + 'n');
});
// Manejo de mensajes desde la pool
consumer.on('knowledge', (knowledge) => {
const messages = knowledge.toString().cut up('n');
messages.forEach((message) => {
if (message.trim()) {
strive {
const parsedMessage = JSON.parse(message);
if (parsedMessage.id === 1 && parsedMessage.consequence) {
[extranonce1, extranonce2Size] = parsedMessage.consequence.slice(1, 3);
console.log('Suscrito. Extranonce1:', extranonce1, 'Extranonce2 Dimension:', extranonce2Size);
consumer.write(JSON.stringify({
id: 2,
methodology: 'mining.authorize',
params: [pool.user, pool.pass]
}) + 'n');
} else if (parsedMessage.id === 2 && parsedMessage.consequence) {
console.log('Autorizado exitosamente');
} else if (parsedMessage.methodology === 'mining.notify') {
const [jobId, prevHash, coinbase1, coinbase2, merkleBranch, version, nBits, nTime, cleanJobs] = parsedMessage.params;
console.log('Nuevo trabajo recibido:', jobId);
if (cleanJobs) {
terminateWorkers();
}
startMining(jobId, prevHash, coinbase1, coinbase2, merkleBranch, model, nBits, nTime);
}
} catch (error) {
console.error('Error al analizar el mensaje:', error);
}
}
});
});
consumer.on('error', (err) => {
console.error('Error en la conexión:', err);
});
consumer.on('shut', () => {
console.log('Conexión cerrada con la pool');
});
// Preserve-alive para evitar desconexiones
setInterval(() => {
consumer.write(JSON.stringify({
id: Math.ground(Math.random() * 1000),
methodology: 'mining.extranonce.subscribe',
params: []
}) + 'n');
}, 30000);
// Función para iniciar minería
perform startMining(jobId, prevHash, coinbase1, coinbase2, merkleBranch, model, nBits, nTime) {
const goal = calculateTarget(nBits);
for (let i = 0; i < require('os').cpus().size; i++) {
const employee = new Employee('./miner-worker.js', {
workerData: {
id: i,
jobId, prevHash, coinbase1, coinbase2, merkleBranch, model, nBits, nTime, extranonce1, extranonce2Size, goal
}
});
employee.on('message', (consequence) => {
if (consequence.sort === 'hashrate') 0), 0);
else if (consequence.discovered) {
console.log('Bloque encontrado por employee:', consequence.hash);
consumer.write(JSON.stringify({
id: 3,
methodology: 'mining.submit',
params: [pool.user, jobId, result.extranonce2, nTime, result.nonce]
}) + 'n');
terminateWorkers();
}
});
employee.on('error', (err) => {
console.error('Error en el employee:', err);
});
employee.on('exit', (code) => {
if (code !== 0) {
console.error('Employee terminó con código:', code);
}
});
employees.push({ employee, hashrate: 0 });
}
}
// Mostrar el hashrate whole periódicamente
setInterval(() => {
console.log(`Hashrate whole: ${(totalHashrate / 1000).toFixed(2)} KH/s`);
}, 5000); // Cada 5 segundos
// Finalizar todos los trabajadores
perform terminateWorkers() {
employees.forEach(({ employee }) => employee.terminate());
employees = [];
totalHashrate = 0;
}
// Calcular objetivo a partir de nBits
perform calculateTarget(nBits) {
const exponent = parseInt(nBits.substring(0, 2), 16);
const coefficient = parseInt(nBits.substring(2), 16);
return BigInt(coefficient) * BigInt(2) ** BigInt((8 * (exponent - 3)));
}
miner-worker.js
const { parentPort, workerData } = require('worker_threads');
const crypto = require('crypto');
const { id, jobId, prevHash, coinbase1, coinbase2, merkleBranch, model, nBits, nTime, extranonce1, extranonce2Size, goal } = workerData;
// Preasignar buffers reutilizables
let extranonce2 = crypto.randomBytes(extranonce2Size).toString('hex').padStart(extranonce2Size * 2, '0');
const coinbase = coinbase1 + extranonce1 + extranonce2 + coinbase2;
const coinbaseHash = crypto.createHash('sha256')
.replace(crypto.createHash('sha256').replace(Buffer.from(coinbase, 'hex')).digest())
.digest('hex');
let merkleRoot = coinbaseHash;
merkleBranch.forEach((department) => {
merkleRoot = crypto.createHash('sha256')
.replace(crypto.createHash('sha256').replace(Buffer.from(merkleRoot + department, 'hex')).digest())
.digest('hex');
});
const blockHeader = model + prevHash + merkleRoot + nTime + nBits + extranonce2;
let nonce = 0;
let makes an attempt = 0;
let lastReport = Date.now();
whereas (true) {
const header = blockHeader + nonce.toString(16).padStart(8, '0');
const hash = crypto.createHash('sha256')
.replace(crypto.createHash('sha256').replace(Buffer.from(header, 'hex')).digest())
.digest('hex');
if (BigInt(`0x${hash}`) < goal) {
parentPort.postMessage({ sort: 'discovered', discovered: true, hash, extranonce2, nonce: nonce.toString(16).padStart(8, '0') });
break;
}
nonce++;
makes an attempt++;
// Reportar hashrate cada segundo
if (Date.now() - lastReport >= 1000) {
parentPort.postMessage({ sort: 'hashrate', id, hashrate: makes an attempt });
makes an attempt = 0;
lastReport = Date.now();
}
}
Thanks soo a lot for making an attempt to assist me
Javi17mod