make it work

This commit is contained in:
Jonathan Rainville 2018-06-27 14:14:58 -04:00
parent 26b6ff9044
commit 1c801bc10f
3 changed files with 137 additions and 75 deletions

View File

@ -196,8 +196,10 @@ Blockchain.prototype.readyCallback = function() {
this.onReadyCallback(); this.onReadyCallback();
} }
const GethMiner = require('./miner'); if (this.config.mineWhenNeeded) {
this.miner = new GethMiner(); const GethMiner = require('./miner');
this.miner = new GethMiner();
}
}; };
Blockchain.prototype.kill = function() { Blockchain.prototype.kill = function() {

View File

@ -215,13 +215,6 @@ class GethCommands {
} }
callback(null, ""); callback(null, "");
}, },
function mineWhenNeeded(callback) {
if (config.mineWhenNeeded && !self.isDev) {
args.push("js .embark/" + self.env + "/js/mine.js");
return callback(null, "js .embark/" + self.env + "/js/mine.js");
}
callback(null, "");
},
function isDev(callback) { function isDev(callback) {
if (self.isDev) { if (self.isDev) {
args.push('--dev'); args.push('--dev');

View File

@ -1,3 +1,4 @@
const async = require('async');
const NetcatClient = require('netcat/client'); const NetcatClient = require('netcat/client');
//Constants //Constants
@ -7,7 +8,9 @@ const getHashRate = 'miner_getHashrate';
const getCoinbase = 'eth_coinbase'; const getCoinbase = 'eth_coinbase';
const getBalance = 'eth_getBalance'; const getBalance = 'eth_getBalance';
const newBlockFilter = 'eth_newBlockFilter'; const newBlockFilter = 'eth_newBlockFilter';
const pendingBlockFilter = 'eth_newPendingTransactionFilter';
const getChanges = 'eth_getFilterChanges'; const getChanges = 'eth_getFilterChanges';
const getBlockCount = 'eth_getBlockTransactionCountByNumber';
class GethMiner { class GethMiner {
constructor() { constructor() {
@ -15,6 +18,13 @@ class GethMiner {
// TODO: Find a way to load mining config from YML. // TODO: Find a way to load mining config from YML.
// In the meantime, just set an empty config object // In the meantime, just set an empty config object
this.config = {}; this.config = {};
self.interval = null;
self.callback = null;
self.commandQueue = async.queue((task, callback) => {
self.callback = callback;
self.client.send(JSON.stringify({"jsonrpc": "2.0", "method": task.method, "params": task.params || [], "id": 1}));
}, 1);
const defaults = { const defaults = {
interval_ms: 15000, interval_ms: 15000,
@ -44,7 +54,7 @@ class GethMiner {
this.client.unixSocket(ipcPath) this.client.unixSocket(ipcPath)
.enc('utf8') .enc('utf8')
.connect() .connect()
.on('data', function(response){ .on('data', (response) => {
try { try {
response = JSON.parse(response); response = JSON.parse(response);
} catch (e) { } catch (e) {
@ -53,7 +63,6 @@ class GethMiner {
} }
if (self.callback) { if (self.callback) {
self.callback(response.error, response.result); self.callback(response.error, response.result);
self.callback = null;
} }
}); });
@ -67,8 +76,8 @@ class GethMiner {
console.error(err); console.error(err);
return; return;
} }
if (this.config.mine_periodically) self.start_periodic_mining(); if (self.config.mine_periodically) self.start_periodic_mining();
if (this.config.mine_pending_txns) self.start_transaction_mining(); if (self.config.mine_pending_txns) self.start_transaction_mining();
}); });
}); });
@ -79,21 +88,21 @@ class GethMiner {
callback = params; callback = params;
params = []; params = [];
} }
if (callback) { if (!callback) {
this.callback = callback; callback = function() {};
} }
this.client.send(JSON.stringify({"jsonrpc": "2.0", "method": method, "params": params || [], "id": 1})); this.commandQueue.push({method, params: params || []}, callback);
} }
getCoinbase(callback) { getCoinbase(callback) {
if (this.coinbase) { if (this.coinbase) {
return callback(null, this.coinbase); return callback(null, this.coinbase);
} }
this.sendCommand(getCoinbase, (err, response) => { this.sendCommand(getCoinbase, (err, result) => {
if (err) { if (err) {
return callback(err); return callback(err);
} }
this.coinbase = response.result; this.coinbase = result;
if (!this.coinbase) { if (!this.coinbase) {
return callback('Failed getting coinbase account'); return callback('Failed getting coinbase account');
} }
@ -107,7 +116,7 @@ class GethMiner {
if (err) { if (err) {
return callback(err); return callback(err);
} }
self.sendCommand(getBalance, [coinbase], (err, result) => { self.sendCommand(getBalance, [coinbase, 'latest'], (err, result) => {
if (err) { if (err) {
return callback(err); return callback(err);
} }
@ -116,26 +125,43 @@ class GethMiner {
}); });
} }
watchNewBlocks() { watchBlocks(filterCommand, callback) {
const self = this; const self = this;
self.sendCommand(newBlockFilter, (err, filterId) => { self.sendCommand(filterCommand, (err, filterId) => {
if (err) {
callback(err);
return;
}
self.interval = setInterval(() => {
self.sendCommand(getChanges, [filterId], (err, changes) => {
if (err) {
console.error(err);
return;
}
if (!changes || !changes.length) {
return;
}
callback(null, changes);
});
}, 1000);
});
}
mineUntilFunded(callback) {
const self = this;
this.sendCommand(minerStart);
self.watchBlocks(newBlockFilter, (err) => {
if (err) { if (err) {
console.error(err); console.error(err);
return; return;
} }
const interval = setInterval(() => { self.accountFunded((err, funded) => {
self.sendCommand(getChanges, [filterId], (err, changes) => { if (funded) {
if (!changes || !changes.length) { clearTimeout(self.interval);
return; self.sendCommand(minerStop);
} callback();
self.accountFunded((err, funded) => { }
if (funded) { });
clearTimeout(interval);
self.sendCommand(minerStop);
}
});
});
}, 1000);
}); });
} }
@ -151,64 +177,94 @@ class GethMiner {
} }
console.log("== Funding account"); console.log("== Funding account");
this.sendCommand(minerStart); self.mineUntilFunded(callback);
self.watchNewBlocks();
}); });
} }
pendingTransactions() { pendingTransactions(callback) {
if (web3.eth.pendingTransactions === undefined || web3.eth.pendingTransactions === null) { const self = this;
return txpool.status.pending || txpool.status.queued; self.sendCommand(getBlockCount, ['pending'], (err, hexCount) => {
} if (err) {
else if (typeof web3.eth.pendingTransactions === "function") { return callback(err);
return web3.eth.pendingTransactions().length > 0; }
} callback(null, parseInt(hexCount, 16));
else { });
return web3.eth.pendingTransactions.length > 0 || web3.eth.getBlock('pending').transactions.length > 0;
}
} }
start_periodic_mining() { start_periodic_mining() {
const self = this; const self = this;
const WAIT = 'wait';
let last_mined_ms = Date.now(); let last_mined_ms = Date.now();
let timeout_set = false; let timeout_set = false;
let next_block_in_ms;
self.sendCommand(minerStart); self.sendCommand(minerStart);
web3.eth.filter("latest").watch(function () { self.watchBlocks(newBlockFilter, (err) => {
if ((self.config.mine_pending_txns && self.pendingTransactions()) || timeout_set) { if (err) {
console.error(err);
return; return;
} }
if (timeout_set) {
timeout_set = true; return;
const now = Date.now();
const ms_since_block = now - last_mined_ms;
last_mined_ms = now;
let next_block_in_ms;
if (ms_since_block > self.config.interval_ms) {
next_block_in_ms = 0;
} else {
next_block_in_ms = (self.config.interval_ms - ms_since_block);
} }
async.waterfall([
function checkPendingTransactions(next) {
if (!self.config.mine_pending_txns) {
return next();
}
self.pendingTransactions((err, count) => {
if (err) {
return next(err);
}
if (count) {
return next(WAIT);
}
next();
});
},
function stopMiner(next) {
timeout_set = true;
self.sendCommand(minerStop); const now = Date.now();
console.log("== Looking for next block in " + next_block_in_ms + "ms"); const ms_since_block = now - last_mined_ms;
last_mined_ms = now;
setTimeout(function () { if (ms_since_block > self.config.interval_ms) {
console.log("== Looking for next block"); next_block_in_ms = 0;
timeout_set = false; } else {
//miner_obj.start(config.threads); next_block_in_ms = (self.config.interval_ms - ms_since_block);
self.sendCommand(minerStart); }
}, next_block_in_ms); self.sendCommand(minerStop);
console.log("== Looking for next block in " + next_block_in_ms + "ms");
next();
},
function startAfterTimeout(next) {
setTimeout(function () {
console.log("== Looking for next block");
timeout_set = false;
//miner_obj.start(config.threads);
self.sendCommand(minerStart);
next();
}, next_block_in_ms);
}
], (err) => {
if (err === WAIT) {
return;
}
if (err) {
console.error(err);
}
});
}); });
} }
start_transaction_mining() { start_transaction_mining() {
const self = this; const self = this;
web3.eth.filter("pending").watch(function () { self.watchBlocks(pendingBlockFilter, (err) => {
if (err) {
console.error(err);
return;
}
self.sendCommand(getHashRate, (err, result) => { self.sendCommand(getHashRate, (err, result) => {
if (result > 0) return; if (result > 0) return;
@ -217,13 +273,24 @@ class GethMiner {
}); });
}); });
if (self.config.mine_periodically) return; if (self.config.mine_periodically) return;
web3.eth.filter("latest").watch(function () { self.watchBlocks(newBlockFilter, (err) => {
if (!self.pendingTransactions()) { if (err) {
console.log("== No transactions left. Stopping miner..."); console.error(err);
self.sendCommand(minerStop); return;
} }
self.pendingTransactions((err, count) => {
if (err) {
console.error(err);
return;
}
if (!count) {
console.log("== No transactions left. Stopping miner...");
self.sendCommand(minerStop);
}
});
}); });
} }
} }