Browse Source

Merge pull request #133 from SuperNETorg/cli

Cli
all-modes
pbca26 8 years ago
committed by GitHub
parent
commit
f8d4fd0e40
  1. 2
      gui/EasyDEX-GUI
  2. 62
      main.js
  3. 9
      private/mainmenu.js
  4. 41
      private/setconf.js
  5. 118
      routes/cache.js
  6. 4
      routes/mock.js
  7. 2
      routes/ports.js
  8. 246
      routes/shepherd.js

2
gui/EasyDEX-GUI

@ -1 +1 @@
Subproject commit 72c3a472674774be19dbd4a512b44e2fbc41d34d
Subproject commit ba50df3108aa7c3dc27583f15e4f85d80ac08cda

62
main.js

@ -22,7 +22,6 @@ var express = require('express'),
pm2 = require('pm2'),
cluster = require('cluster'),
numCPUs = require('os').cpus().length,
//coincli = require('./private/coincli.js'),
ipc = require('electron').ipcMain;
Promise = require('bluebird');
@ -37,7 +36,7 @@ app.setVersion(appBasicInfo.version);
if (os.platform() === 'linux') {
process.env.ELECTRON_RUN_AS_NODE = true;
console.log(process.env);
// console.log(process.env);
}
// GUI APP settings and starting gui on address http://120.0.0.1:17777
@ -48,25 +47,25 @@ shepherd.createIguanaDirs();
const appSessionHash = md5(Date.now());
shepherd.writeLog('app init ' + appSessionHash);
shepherd.writeLog('app info: ' + appBasicInfo.name + ' ' + appBasicInfo.version);
shepherd.writeLog(`app init ${appSessionHash}`);
shepherd.writeLog(`app info: ${appBasicInfo.name} ${appBasicInfo.version}`);
shepherd.writeLog('sys info:');
shepherd.writeLog('totalmem_readable: ' + formatBytes(os.totalmem()));
shepherd.writeLog('arch: ' + os.arch());
shepherd.writeLog('cpu: ' + os.cpus()[0].model);
shepherd.writeLog('cpu_cores: ' + os.cpus().length);
shepherd.writeLog('platform: ' + os.platform());
shepherd.writeLog('os_release: ' + os.release());
shepherd.writeLog('os_type: ' + os.type());
shepherd.writeLog(`totalmem_readable: ${formatBytes(os.totalmem())}`);
shepherd.writeLog(`arch: ${os.arch()}`);
shepherd.writeLog(`cpu: ${os.cpus()[0].model}`);
shepherd.writeLog(`cpu_cores: ${os.cpus().length}`);
shepherd.writeLog(`platform: ${os.platform()}`);
shepherd.writeLog(`os_release: ${os.release()}`);
shepherd.writeLog(`os_type: ${os.type()}`);
var appConfig = shepherd.loadLocalConfig(); // load app config
shepherd.writeLog('app started in ' + (appConfig.dev ? 'dev mode' : ' user mode'));
shepherd.writeLog(`app started in ${(appConfig.dev ? 'dev mode' : ' user mode')}`);
shepherd.setConfKMD();
if (appConfig.killIguanaOnStart) {
var iguanaGrep;
let iguanaGrep;
if (os.platform() === 'darwin') {
iguanaGrep = "ps -p $(ps -A | grep -m1 iguana | awk '{print $1}') | grep -i iguana";
@ -79,23 +78,25 @@ if (appConfig.killIguanaOnStart) {
}
exec(iguanaGrep, function(error, stdout, stderr) {
if (stdout.indexOf('iguana') > -1) {
const pkillCmd = os.platform() === 'win32' ? 'taskkill /f /im iguana.exe' : 'pkill -15 iguana';
console.log('found another iguana process(es)');
shepherd.writeLog('found another iguana process(es)');
const pkillCmd = os.platform() === 'win32' ? 'taskkill /f /im iguana.exe' : 'pkill -15 iguana';
exec(pkillCmd, function(error, stdout, stderr) {
console.log(pkillCmd + ' is issued');
shepherd.writeLog(pkillCmd + ' is issued');
console.log(`${pkillCmd} is issued`);
shepherd.writeLog(`${pkillCmd} is issued`);
if (error !== null) {
console.log(pkillCmd + ' exec error: ' + error);
shepherd.writeLog(pkillCmd + ' exec error: ' + error);
console.log(`${pkillCmd} exec error: ${error}`);
shepherd.writeLog(`${pkillCmd} exec error: ${error}`);
};
});
}
if (error !== null) {
console.log(iguanaGrep + ' exec error: ' + error);
shepherd.writeLog(iguanaGrep + ' exec error: ' + error);
console.log(`${iguanaGrep} exec error: ${error}`);
shepherd.writeLog(`${iguanaGrep} exec error: ${error}`);
};
});
}
@ -138,7 +139,7 @@ guiapp.use(bodyParser.urlencoded({
})); // support encoded bodies
guiapp.get('/', function (req, res) {
res.send('Iguana app server');
res.send('Agama app server');
});
var guipath = path.join(__dirname, '/gui');
@ -149,11 +150,11 @@ var server = require('http').createServer(guiapp),
io = require('socket.io').listen(server);
server.listen(appConfig.agamaPort, function() {
console.log('guiapp and sockets.io are listening on port ' + appConfig.agamaPort + '!');
shepherd.writeLog('guiapp and sockets.io are listening on port ' + appConfig.agamaPort + '!');
console.log(`guiapp and sockets.io are listening on port ${appConfig.agamaPort}`);
shepherd.writeLog(`guiapp and sockets.io are listening on port ${appConfig.agamaPort}`);
});
io.set('origins', appConfig.dev ? 'http://127.0.0.1:3000' : 'http://127.0.0.1:' + appConfig.agamaPort); // set origin
io.set('origins', appConfig.dev ? 'http://127.0.0.1:3000' : `http://127.0.0.1:${appConfig.agamaPort}`); // set origin
io.on('connection', function(client) {
console.log('EDEX GUI is connected...');
@ -184,7 +185,6 @@ if (os.platform() === 'win32') {
var iguanaIcon = path.join(__dirname, '/assets/icons/agama_icons/agama_app_icon.ico');
}
let mainWindow;
let loadingWindow;
let willQuitApp = false;
@ -204,7 +204,7 @@ function createLoadingWindow() {
loadingWindow.createWindow = createWindow; // expose createWindow to front-end scripts
// load our index.html (i.e. easyDEX GUI)
loadingWindow.loadURL('http://' + appConfig.host + ':' + appConfig.agamaPort + '/gui/');
loadingWindow.loadURL(`http://${appConfig.host}:${appConfig.agamaPort}/gui/`);
shepherd.writeLog('show loading window');
// DEVTOOLS - only for dev purposes - ca333
@ -277,13 +277,13 @@ function createWindow (status) {
pm2Exit();
}
const staticMenu = Menu.buildFromTemplate([ //if static
const staticMenu = Menu.buildFromTemplate([ // if static
{ role: 'copy' },
{ type: 'separator' },
{ role: 'selectall' },
]);
const editMenu = Menu.buildFromTemplate([ //if editable
const editMenu = Menu.buildFromTemplate([ // if editable
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
@ -304,14 +304,14 @@ function createWindow (status) {
if (appConfig.dev) {
mainWindow.loadURL('http://127.0.0.1:3000');
} else {
mainWindow.loadURL('http://' + appConfig.host + ':' + appConfig.agamaPort + '/gui/EasyDEX-GUI/react/build');
mainWindow.loadURL(`http://${appConfig.host}:${appConfig.agamaPort}/gui/EasyDEX-GUI/react/build`);
}
} else {
shepherd.writeLog('show edex gui');
mainWindow.loadURL('http://' + appConfig.host + ':' + appConfig.agamaPort + '/gui/EasyDEX-GUI/');
mainWindow.loadURL(`http://${appConfig.host}:${appConfig.agamaPort}/gui/EasyDEX-GUI/`);
}
} else {
mainWindow.loadURL('http://' + appConfig.host + ':' + appConfig.agamaPort + '/gui/main.html');
mainWindow.loadURL(`http://${appConfig.host}:${appConfig.agamaPort}/gui/main.html`);
}
mainWindow.webContents.on('context-menu', (e, params) => { //context-menu returns params

9
private/mainmenu.js

@ -55,15 +55,6 @@ const template = [
focusedWindow.webContents.toggleDevTools();
}
},
/*{
label: 'Relaunch app',
click (item, focusedWindow) {
if (focusedWindow)
app.relaunch({ args: process.argv.slice(1).concat([ '--relaunch' ]) });
app.exit(0);
}
TODO: figure out a way to restart iguana and komodod, reload gui
},*/
{
type: 'separator'
},

41
private/setconf.js

@ -41,9 +41,8 @@ var coind_conf = module.exports = {
*
*/
function parse_status_block(block) {
var match;
var parsed = {
let match;
let parsed = {
settings: 'exists'
};
@ -98,45 +97,17 @@ function parse_status(callback) {
} else {
callback(error,
stdout.trim().split('\n\n').map(parse_status_block));
//stdout.trim().split(/\s\*-usb:/g).map(parse_status_block));
//console.log(stdout.trim().split(/\s\*-usb:/g))
}
};
}
/**
* The **coind_conf status** command is used to query the status of all
* configured interfaces.
*
* @static
* @category coind_conf
* @param {function} callback The callback function.
* @example
*
* var coind_conf = require('./coind_conf');
*
* coind_conf.status(function(err, status) {
* console.log(status);
* });
*
* // =>
* [
* {
* "rpcuser": "pi",
* "rpcpass": "c892f76fc45365d50cb744ec1d5cdde659c98e0b",
* "rpcport": "8336",
* "server": "1"
* }
* ]
*
*/
function status(confPath, callback) {
//console.log(confPath);
if (os.platform() === 'darwin' || os.platform() === 'linux') {
this.exec('cat "' + confPath + '"', parse_status(callback));
if (os.platform() === 'darwin' ||
os.platform() === 'linux') {
this.exec(`cat "${confPath}"`, parse_status(callback));
}
if (os.platform() === 'win32') {
this.exec('type "' + confPath + '"', parse_status(callback));
this.exec(`type "${confPath}"`, parse_status(callback));
}
}

118
routes/cache.js

@ -16,7 +16,7 @@ cache.setVar = function(variable, value) {
cache.dumpCacheBeforeExit = function() {
if (inMemCache) {
console.log('dumping cache before exit');
fs.writeFileSync(cache.iguanaDir + '/shepherd/cache-' + inMemPubkey + '.json', JSON.stringify(inMemCache), 'utf8');
fs.writeFileSync(`${cache.iguanaDir}/shepherd/cache-${inMemPubkey}.json`, JSON.stringify(inMemCache), 'utf8');
}
}
@ -29,8 +29,8 @@ cache.get = function(req, res, next) {
if (!inMemCache) {
console.log('serving cache from disk');
if (fs.existsSync(cache.iguanaDir + '/shepherd/cache-' + pubkey + '.json')) {
fs.readFile(cache.iguanaDir + '/shepherd/cache-' + pubkey + '.json', 'utf8', function (err, data) {
if (fs.existsSync(`${cache.iguanaDir}/shepherd/cache-${pubkey}.json`)) {
fs.readFile(`${cache.iguanaDir}/shepherd/cache-${pubkey}.json`, 'utf8', function (err, data) {
if (err) {
const errorObj = {
'msg': 'error',
@ -54,10 +54,10 @@ cache.get = function(req, res, next) {
if (e.toString().indexOf('at position') > -1) {
const errorPos = e.toString().split(' ');
console.log('JSON error ---> ' + data.substring(errorPos[errorPos.length - 1] - 20, errorPos[errorPos.length - 1] + 20) + ' | error sequence: ' + data.substring(errorPos[errorPos.length - 1], errorPos[errorPos.length - 1] + 1));
console.log(`JSON error ---> ${data.substring(errorPos[errorPos.length - 1] - 20, errorPos[errorPos.length - 1] + 20)} | error sequence: ${data.substring(errorPos[errorPos.length - 1], errorPos[errorPos.length - 1] + 1)}`);
console.log('attempting to recover JSON data');
fs.writeFile(cache.iguanaDir + '/shepherd/cache-' + pubkey + '.json', data.substring(0, errorPos[errorPos.length - 1]), function(err) {
fs.writeFile(`${cache.iguanaDir}/shepherd/cache-${pubkey}.json`, data.substring(0, errorPos[errorPos.length - 1]), function(err) {
const successObj = {
'msg': 'success',
'result': data.substring(0, errorPos[errorPos.length - 1])
@ -73,7 +73,7 @@ cache.get = function(req, res, next) {
} else {
const errorObj = {
'msg': 'error',
'result': 'no file with handle ' + pubkey
'result': `no file with handle ${pubkey}`
};
res.end(JSON.stringify(errorObj));
@ -100,8 +100,8 @@ cache.groomGet = function(req, res, next) {
const _filename = req.query.filename;
if (_filename) {
if (fs.existsSync(cache.iguanaDir + '/shepherd/cache-' + _filename + '.json')) {
fs.readFile(cache.iguanaDir + '/shepherd/cache-' + _filename + '.json', 'utf8', function (err, data) {
if (fs.existsSync(`${cache.iguanaDir}/shepherd/cache-${_filename}.json`)) {
fs.readFile(`${cache.iguanaDir}/shepherd/cache-${_filename}.json`, 'utf8', function (err, data) {
if (err) {
const errorObj = {
'msg': 'error',
@ -121,7 +121,7 @@ cache.groomGet = function(req, res, next) {
} else {
const errorObj = {
'msg': 'error',
'result': 'no file with name ' + _filename
'result': `no file with name ${_filename}`
};
res.end(JSON.stringify(errorObj));
@ -140,10 +140,10 @@ cache.groomDelete = function(req, res, next) {
const _filename = req.body.filename;
if (_filename) {
if (fs.existsSync(cache.iguanaDir + '/shepherd/cache-' + _filename + '.json')) {
if (fs.existsSync(`${cache.iguanaDir}/shepherd/cache-${_filename}.json`)) {
inMemCache = null;
fs.unlink(cache.iguanaDir + '/shepherd/cache-' + _filename + '.json', function(err) {
fs.unlink(`${cache.iguanaDir}/shepherd/cache-${_filename}.json`, function(err) {
if (err) {
const errorObj = {
'msg': 'error',
@ -163,7 +163,7 @@ cache.groomDelete = function(req, res, next) {
} else {
const errorObj = {
'msg': 'error',
'result': 'no file with name ' + _filename
'result': `no file with name ${_filename}`
};
res.end(JSON.stringify(errorObj));
@ -198,7 +198,7 @@ cache.groomPost = function(req, res) {
console.log('appending groom post to in mem cache');
console.log('appending groom post to on disk cache');
fs.writeFile(cache.iguanaDir + '/shepherd/cache-' + _filename + '.json', _payload, function (err) {
fs.writeFile(`${cache.iguanaDir}/shepherd/cache-${_filename}.json`, _payload, function (err) {
if (err) {
const errorObj = {
'msg': 'error',
@ -271,7 +271,7 @@ checkCallStack = function() {
*/
cache.one = function(req, res, next) {
if (req.query.pubkey &&
!fs.existsSync(cache.iguanaDir + '/shepherd/cache-' + req.query.pubkey + '.json')) {
!fs.existsSync(`${cache.iguanaDir}/shepherd/cache-${req.query.pubkey}.json`)) {
cacheCallInProgress = false;
}
@ -282,8 +282,8 @@ cache.one = function(req, res, next) {
if (!cacheCallInProgress) {
cache.dumpCacheBeforeExit();
if (fs.existsSync(cache.iguanaDir + '/shepherd/cache-' + req.query.pubkey + '.json')) {
let _data = fs.readFileSync(cache.iguanaDir + '/shepherd/cache-' + req.query.pubkey + '.json', 'utf8');
if (fs.existsSync(`${cache.iguanaDir}/shepherd/cache-${req.query.pubkey}.json`)) {
let _data = fs.readFileSync(`${cache.iguanaDir}/shepherd/cache-${req.query.pubkey}.json`, 'utf8');
if (_data) {
inMemCache = JSON.parse(_data);
_data = _data.replace('waiting', 'failed');
@ -327,7 +327,7 @@ cache.one = function(req, res, next) {
inMemPubkey = pubkey;
callStack[coin] = 1;
console.log(callsArray);
console.log('iguana core port ' + iguanaCorePort);
console.log(`iguana core port ${iguanaCorePort}`);
if (!sessionKey) {
const errorObj = {
@ -354,7 +354,7 @@ cache.one = function(req, res, next) {
function fixJSON(data) {
if (data && data.length) {
try {
var parsedJSON = JSON.parse(data);
const parsedJSON = JSON.parse(data);
return parsedJSON;
} catch (e) {
@ -362,7 +362,7 @@ cache.one = function(req, res, next) {
if (e.toString().indexOf('at position') > -1) {
const errorPos = e.toString().split(' ');
console.log('JSON error ---> ' + data.substring(errorPos[errorPos.length - 1] - 20, errorPos[errorPos.length - 1] + 20) + ' | error sequence: ' + data.substring(errorPos[errorPos.length - 1], errorPos[errorPos.length - 1] + 1));
console.log(`JSON error ---> ${data.substring(errorPos[errorPos.length - 1] - 20, errorPos[errorPos.length - 1] + 20)} | error sequence: ${data.substring(errorPos[errorPos.length - 1], errorPos[errorPos.length - 1] + 1)}`);
console.log('attempting to recover JSON data');
return JSON.parse(data.substring(0, errorPos[errorPos.length - 1]));
}
@ -375,14 +375,13 @@ cache.one = function(req, res, next) {
}
}
if (fs.existsSync(cache.iguanaDir + '/shepherd/cache-' + pubkey + '.json') && coin !== 'all') {
if (fs.existsSync(`${cache.iguanaDir}/shepherd/cache-${pubkey}.json`) && coin !== 'all') {
if (inMemCache) {
console.log('cache one from mem');
outObj = inMemCache;
} else {
var _file = fs.readFileSync(cache.iguanaDir + '/shepherd/cache-' + pubkey + '.json', 'utf8');
const _file = fs.readFileSync(`${cache.iguanaDir}/shepherd/cache-${pubkey}.json`, 'utf8');
console.log('cache one from disk');
//outObj = _file ? JSON.parse(_file) : {};
outObj = fixJSON(_file);
}
@ -419,23 +418,24 @@ cache.one = function(req, res, next) {
function execDEXRequests(coin, address) {
let dexUrls = {
'listunspent': 'http://' + cache.appConfig.host + ':' + iguanaCorePort + '/api/dex/listunspent?userpass=' + sessionKey + '&symbol=' + coin + '&address=' + address,
'listtransactions': 'http://' + cache.appConfig.host + ':' + iguanaCorePort + '/api/dex/listtransactions?userpass=' + sessionKey + '&count=100&skip=0&symbol=' + coin + '&address=' + address,
'getbalance': 'http://' + cache.appConfig.host + ':' + iguanaCorePort + '/api/dex/getbalance?userpass=' + sessionKey + '&symbol=' + coin + '&address=' + address,
'refresh': 'http://' + cache.appConfig.host + ':' + iguanaCorePort + '/api/basilisk/refresh?userpass=' + sessionKey + '&symbol=' + coin + '&address=' + address
'listunspent': `http://${cache.appConfig.host}:${iguanaCorePort}/api/dex/listunspent?userpass=${sessionKey}&symbol=${coin}&address=${address}`,
'listtransactions': `http://${cache.appConfig.host}:${iguanaCorePort}/api/dex/listtransactions?userpass=${sessionKey}&count=100&skip=0&symbol=${coin}&address=${address}`,
'getbalance': `http://${cache.appConfig.host}:${iguanaCorePort}/api/dex/getbalance?userpass=${sessionKey}&symbol=${coin}&address=${address}`,
'refresh': `http://${cache.appConfig.host}:${iguanaCorePort}/api/basilisk/refresh?userpass=${sessionKey}&symbol=${coin}&address=${address}`
},
_dexUrls = {};
for (var a = 0; a < callsArray.length; a++) {
for (let a = 0; a < callsArray.length; a++) {
_dexUrls[callsArray[a]] = dexUrls[callsArray[a]];
}
if (coin === 'BTC' || coin === 'SYS') {
if (coin === 'BTC' ||
coin === 'SYS') {
delete _dexUrls.refresh;
delete _dexUrls.getbalance;
}
console.log(coin + ' address ' + address);
console.log(`${coin} address ${address}`);
if (!outObj.basilisk[coin][address]) {
outObj.basilisk[coin][address] = {};
@ -493,7 +493,7 @@ cache.one = function(req, res, next) {
});
outObj.basilisk[coin][address][key].status = 'in progress';
request({
url: mock ? 'http://localhost:17777/shepherd/mock?url=' + dexUrl : dexUrl,
url: mock ? `http://localhost:17777/shepherd/mock?url=${dexUrl}` : dexUrl,
method: 'GET'
}, function (error, response, body) {
if (response &&
@ -519,9 +519,35 @@ cache.one = function(req, res, next) {
const _parsedJSON = JSON.parse(body);
if (key === 'getbalance' &&
coin === 'KMD'/* &&
((_parsedJSON && _parsedJSON.balance === 0) || _parsedJSON === [])*/) {
console.log('fallback to kmd explorer');
//http://kmd.explorer.supernet.org/api/addr/RDbGxL8QYdEp8sMULaVZS2E6XThcTKT9Jd/?noTxList=1
((_parsedJSON && _parsedJSON.balance === 0) || body === [])*/) {
console.log('fallback to kmd explorer ======>');
request({
url: `http://kmd.explorer.supernet.org/api/addr/${address}/?noTxList=1`,
method: 'GET'
}, function (error, response, body) {
if (response &&
response.statusCode &&
response.statusCode === 200) {
console.log(JSON.stringify(body));
/*cache.io.emit('messages', {
'message': {
'shepherd': {
'method': 'cache-one',
'status': 'in progress',
'iguanaAPI': {
'method': key,
'coin': coin,
'address': address,
'status': 'done',
'resp': body
}
}
}
});*/
} else {
}
});
}
outObj.basilisk[coin][address][key] = {};
@ -531,7 +557,7 @@ cache.one = function(req, res, next) {
console.log(dexUrl);
console.log(body);
callStack[coin]--;
console.log(coin + ' _stack len ' + callStack[coin]);
console.log(`${coin} _stack len ${callStack[coin]}`);
cache.io.emit('messages', {
'message': {
'shepherd': {
@ -555,7 +581,7 @@ cache.one = function(req, res, next) {
outObj.basilisk[coin][address][key].timestamp = 1471620867 // add timestamp
outObj.basilisk[coin][address][key].status = 'done';
callStack[coin]--;
console.log(coin + ' _stack len ' + callStack[coin]);
console.log(`${coin} _stack len ${callStack[coin]}`);
cache.io.emit('messages', {
'message': {
'shepherd': {
@ -572,9 +598,9 @@ cache.one = function(req, res, next) {
}
});
} else {
console.log(key + ' is fresh, check back in ' + (cacheGlobLifetime - checkTimestamp(outObj.basilisk[coin][address][key].timestamp)) + 's');
console.log(`${key} is fresh, check back in ${(cacheGlobLifetime - checkTimestamp(outObj.basilisk[coin][address][key].timestamp))}s`);
callStack[coin]--;
console.log(coin + ' _stack len ' + callStack[coin]);
console.log(`${coin} _stack len ${callStack[coin]}`);
cache.io.emit('messages', {
'message': {
'shepherd': {
@ -611,7 +637,7 @@ cache.one = function(req, res, next) {
writeCache();
const addrCount = outObj.basilisk[coin].addresses ? outObj.basilisk[coin].addresses.length : 0;
var callsArrayBTC = callsArray.length;
let callsArrayBTC = callsArray.length;
if (callsArray.indexOf('getbalance') > - 1) {
callsArrayBTC--;
@ -620,7 +646,7 @@ cache.one = function(req, res, next) {
callsArrayBTC--;
}
callStack[coin] = callStack[coin] + addrCount * (coin === 'BTC' || coin === 'SYS' ? callsArrayBTC : callsArray.length);
console.log(coin + ' stack len ' + callStack[coin]);
console.log(`${coin} stack len ${callStack[coin]}`);
cache.io.emit('messages', {
'message': {
@ -642,9 +668,9 @@ cache.one = function(req, res, next) {
if (addresses) {
parseAddresses(coin, addresses);
} else {
const tempUrl = 'http://' + cache.appConfig.host + ':' + cache.appConfig.iguanaCorePort + '/api/bitcoinrpc/getaddressesbyaccount?userpass=' + sessionKey + '&coin=' + coin + '&account=*';
const tempUrl = `http://${cache.appConfig.host}:${cache.appConfig.iguanaCorePort}/api/bitcoinrpc/getaddressesbyaccount?userpass=${sessionKey}&coin=${coin}&account=*`;
request({
url: mock ? 'http://localhost:17777/shepherd/mock?url=' + tempUrl : tempUrl,
url: mock ? `http://localhost:17777/shepherd/mock?url=${tempUrl}` : tempUrl,
method: 'GET'
}, function (error, response, body) {
if (response &&
@ -675,9 +701,9 @@ cache.one = function(req, res, next) {
});
if (coin === 'all') {
const tempUrl = 'http://' + cache.appConfig.host + ':' + cache.appConfig.iguanaCorePort + '/api/InstantDEX/allcoins?userpass=' + sessionKey;
const tempUrl = `http://${cache.appConfig.host}:${cache.appConfig.iguanaCorePort}/api/InstantDEX/allcoins?userpass=${sessionKey}`;
request({
url: mock ? 'http://localhost:17777/shepherd/mock?url=' + tempUrl : tempUrl,
url: mock ? `http://localhost:17777/shepherd/mock?url=${tempUrl}` : tempUrl,
method: 'GET'
}, function (error, response, body) {
if (response &&
@ -737,15 +763,17 @@ cache.one = function(req, res, next) {
getAddresses(coin);
}
} else {
var callsArrayBTC = callsArray.length; // restrict BTC and SYS only to listunspent and listtransactions calls
let callsArrayBTC = callsArray.length; // restrict BTC and SYS only to listunspent and listtransactions calls
if (callsArray.indexOf('getbalance') > - 1) {
callsArrayBTC--;
}
if (callsArray.indexOf('refresh') > - 1) {
callsArrayBTC--;
}
callStack[coin] = callStack[coin] + (coin === 'BTC' || coin === 'SYS' ? callsArrayBTC : callsArray.length);
console.log(coin + ' stack len ' + callStack[coin]);
console.log(`${coin} stack len ${callStack[coin]}`);
cache.io.emit('messages', {
'message': {

4
routes/mock.js

@ -3,14 +3,14 @@ const fs = require('fs-extra'),
async = require('async'),
url = require('url');
var mock = {};
let mock = {};
mock.setVar = function(variable, value) {
mock[variable] = value;
}
mock.get = function(req, res, next) {
var _url = req.query.url;
const _url = req.query.url;
if (_url.indexOf('/InstantDEX/allcoins') > -1) {
res.end(JSON.stringify({

2
routes/ports.js

@ -2,7 +2,7 @@ const assetChainPorts = {
'komodod': '7771',
'SUPERNET': '11341',
'REVS': '10196',
'WLC': '11667',
'WLC': '12167',
'PANGEA': '10074',
'DEX': '9503',
'JUMBLR': '10789',

246
routes/shepherd.js

@ -22,13 +22,13 @@ const electron = require('electron'),
const fixPath = require('fix-path');
var ps = require('ps-node'),
setconf = require('../private/setconf.js'),
//coincli = require('../private/coincli.js'),
assetChainPorts = require('./ports.js'),
shepherd = express.Router(),
iguanaInstanceRegistry = {},
syncOnlyIguanaInstanceInfo = {},
syncOnlyInstanceInterval = -1,
guiLog = {};
guiLog = {},
rpcConf = {};
// IGUANA FILES AND CONFIG SETTINGS
var iguanaConfsDirSrc = path.join(__dirname, '../assets/deps/confs'),
@ -39,32 +39,32 @@ var iguanaConfsDirSrc = path.join(__dirname, '../assets/deps/confs'),
if (os.platform() === 'darwin') {
fixPath();
var iguanaBin = path.join(__dirname, '../assets/bin/osx/iguana'),
iguanaDir = process.env.HOME + '/Library/Application Support/iguana',
iguanaConfsDir = iguanaDir + '/confs',
iguanaDir = `${process.env.HOME}/Library/Application Support/iguana`,
iguanaConfsDir = `${iguanaDir}/confs`,
komododBin = path.join(__dirname, '../assets/bin/osx/komodod'),
komodocliBin = path.join(__dirname, '../assets/bin/osx/komodo-cli'),
komodoDir = process.env.HOME + '/Library/Application Support/Komodo',
komodoDir = `${process.env.HOME}/Library/Application Support/Komodo`,
zcashdBin = '/Applications/ZCashSwingWalletUI.app/Contents/MacOS/zcashd',
zcashcliBin = '/Applications/ZCashSwingWalletUI.app/Contents/MacOS/zcash-cli',
zcashDir = process.env.HOME + '/Library/Application Support/Zcash';
zcashDir = `${process.env.HOME}/Library/Application Support/Zcash`;
}
if (os.platform() === 'linux') {
var iguanaBin = path.join(__dirname, '../assets/bin/linux64/iguana'),
iguanaDir = process.env.HOME + '/.iguana',
iguanaConfsDir = iguanaDir + '/confs',
iguanaDir = `${process.env.HOME}/.iguana`,
iguanaConfsDir = `${iguanaDir}/confs`,
iguanaIcon = path.join(__dirname, '/assets/icons/agama_icons/128x128.png'),
komododBin = path.join(__dirname, '../assets/bin/linux64/komodod'),
komodocliBin = path.join(__dirname, '../assets/bin/linux64/komodo-cli'),
komodoDir = process.env.HOME + '/.komodo';
komodoDir = `${process.env.HOME}/.komodo`;
}
if (os.platform() === 'win32') {
var iguanaBin = path.join(__dirname, '../assets/bin/win64/iguana.exe');
iguanaBin = path.normalize(iguanaBin);
iguanaDir = process.env.APPDATA + '/iguana';
iguanaDir = `${process.env.APPDATA}/iguana`;
iguanaDir = path.normalize(iguanaDir);
iguanaConfsDir = process.env.APPDATA + '/iguana/confs';
iguanaConfsDir = `${process.env.APPDATA}/iguana/confs`;
iguanaConfsDir = path.normalize(iguanaConfsDir);
iguanaIcon = path.join(__dirname, '/assets/icons/agama_icons/agama_app_icon.ico'),
iguanaConfsDirSrc = path.normalize(iguanaConfsDirSrc),
@ -72,7 +72,7 @@ if (os.platform() === 'win32') {
komododBin = path.normalize(komododBin),
komodocliBin = path.join(__dirname, '../assets/bin/win64/komodo-cli.exe'),
komodocliBin = path.normalize(komodocliBin),
komodoDir = process.env.APPDATA + '/Komodo',
komodoDir = `${process.env.APPDATA}/Komodo`,
komodoDir = path.normalize(komodoDir);
}
@ -94,20 +94,24 @@ shepherd.appConfig = {
"v2": true,
"useBasiliskInstance": true,
"debug": true,
"cli": {
"passthru": false,
"default": false
}
};
shepherd.writeLog = function(data) {
const logLocation = iguanaDir + '/shepherd';
const logLocation = `${iguanaDir}/shepherd`;
const timeFormatted = new Date(Date.now()).toLocaleString('en-US', { hour12: false });
if (fs.existsSync(logLocation + '/agamalog.txt')) {
fs.appendFile(logLocation + '/agamalog.txt', timeFormatted + ' ' + data + '\r\n', function (err) {
if (fs.existsSync(`${logLocation}/agamalog.txt`)) {
fs.appendFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, function (err) {
if (err) {
console.log('error writing log file');
}
});
} else {
fs.writeFile(logLocation + '/agamalog.txt', timeFormatted + ' ' + data + '\r\n', function (err) {
fs.writeFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, function (err) {
if (err) {
console.log('error writing log file');
}
@ -118,19 +122,21 @@ shepherd.writeLog = function(data) {
shepherd.createIguanaDirs = function() {
if (!fs.existsSync(iguanaDir)) {
fs.mkdirSync(iguanaDir);
if (fs.existsSync(iguanaDir)) {
console.log('created iguana folder at ' + iguanaDir);
shepherd.writeLog('created iguana folder at ' + iguanaDir);
console.log(`created iguana folder at ${iguanaDir}`);
shepherd.writeLog(`created iguana folder at ${iguanaDir}`);
}
} else {
console.log('iguana folder already exists');
}
if (!fs.existsSync(iguanaDir + '/shepherd')) {
fs.mkdirSync(iguanaDir + '/shepherd');
if (!fs.existsSync(`${iguanaDir}/shepherd`)) {
fs.mkdirSync(`${iguanaDir}/shepherd`);
if (fs.existsSync(iguanaDir)) {
console.log('created shepherd folder at ' + iguanaDir + '/shepherd');
shepherd.writeLog('create shepherd folder at ' + iguanaDir + '/shepherd');
console.log(`created shepherd folder at ${iguanaDir}/shepherd`);
shepherd.writeLog(`create shepherd folder at ${iguanaDir}/shepherd`);
}
} else {
console.log('shepherd folder already exists');
@ -138,8 +144,8 @@ shepherd.createIguanaDirs = function() {
}
shepherd.get('/coinslist', function(req, res, next) {
if (fs.existsSync(iguanaDir + '/shepherd/coinslist.json')) {
fs.readFile(iguanaDir + '/shepherd/coinslist.json', 'utf8', function (err, data) {
if (fs.existsSync(`${iguanaDir}/shepherd/coinslist.json`)) {
fs.readFile(`${iguanaDir}/shepherd/coinslist.json`, 'utf8', function (err, data) {
if (err) {
const errorObj = {
'msg': 'error',
@ -171,7 +177,7 @@ shepherd.get('/coinslist', function(req, res, next) {
* params: payload
*/
shepherd.post('/guilog', function(req, res, next) {
const logLocation = iguanaDir + '/shepherd';
const logLocation = `${iguanaDir}/shepherd`;
if (!guiLog[shepherd.appSessionHash]) {
guiLog[shepherd.appSessionHash] = {};
@ -190,7 +196,7 @@ shepherd.post('/guilog', function(req, res, next) {
};
}
fs.writeFile(logLocation + '/agamalog.json', JSON.stringify(guiLog), function (err) {
fs.writeFile(`${logLocation}/agamalog.json`, JSON.stringify(guiLog), function (err) {
if (err) {
shepherd.writeLog('error writing gui log file');
}
@ -207,8 +213,8 @@ shepherd.post('/guilog', function(req, res, next) {
shepherd.get('/getlog', function(req, res, next) {
const logExt = req.query.type === 'txt' ? 'txt' : 'json';
if (fs.existsSync(iguanaDir + '/shepherd/agamalog.' + logExt)) {
fs.readFile(iguanaDir + '/shepherd/agamalog.' + logExt, 'utf8', function (err, data) {
if (fs.existsSync(`${iguanaDir}/shepherd/agamalog.${logExt}`)) {
fs.readFile(`${iguanaDir}/shepherd/agamalog.${logExt}`, 'utf8', function (err, data) {
if (err) {
const errorObj = {
'msg': 'error',
@ -228,7 +234,7 @@ shepherd.get('/getlog', function(req, res, next) {
} else {
const errorObj = {
'msg': 'error',
'result': 'agama.' + logExt + ' doesn\'t exist'
'result': `agama.${logExt} doesnt exist`
};
res.end(JSON.stringify(errorObj));
@ -246,7 +252,7 @@ shepherd.post('/coinslist', function(req, res, next) {
res.end(JSON.stringify(errorObj));
} else {
fs.writeFile(cache.iguanaDir + '/shepherd/coinslist.json', JSON.stringify(_payload), function (err) {
fs.writeFile(`${cache.iguanaDir}/shepherd/coinslist.json`, JSON.stringify(_payload), function (err) {
if (err) {
const errorObj = {
'msg': 'error',
@ -271,15 +277,48 @@ shepherd.quitKomodod = function(chain) {
// exit komodod gracefully
console.log('exec ' + komodocliBin + (chain ? ' -ac_name=' + chain : '') + ' stop');
exec(komodocliBin + (chain ? ' -ac_name=' + chain : '') + ' stop', function(error, stdout, stderr) {
console.log('stdout: ' + stdout)
console.log('stderr: ' + stderr)
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log('exec error: ' + error)
console.log(`exec error: ${error}`);
}
});
}
shepherd.getConf = function(chain) {
const _confLocation = chain === 'komodod' ? `${komodoDir}/komodo.conf` : `${komodoDir}/${chain}/${chain}.conf`;
if (fs.existsSync(_confLocation)) {
const _port = assetChainPorts[chain];
const _rpcConf = fs.readFileSync(_confLocation, 'utf8');
if (_rpcConf.length) {
let _match;
let parsedRpcConfig = {
user: '',
pass: '',
port: _port
};
if (_match = _rpcConf.match(/rpcuser=\s*(.*)/)) {
parsedRpcConfig.user = _match[1];
}
if ((_match = _rpcConf.match(/rpcpass=\s*(.*)/)) ||
(_match = _rpcConf.match(/rpcpassword=\s*(.*)/))) {
parsedRpcConfig.pass = _match[1];
}
rpcConf[chain === 'komodod' ? 'KMD' : chain] = parsedRpcConfig;
} else {
console.log(`${_confLocation} is empty`);
}
} else {
console.log(`${_confLocation} doesnt exist`);
}
}
/*
* type: POST
* params: payload
@ -292,7 +331,7 @@ shepherd.post('/cli', function(req, res, next) {
};
res.end(JSON.stringify(errorObj));
} else if (!req.body.payload.cmd.match(/^[0-9a-zA-Z \[\]"'/\\]+$/g)) {
} else if (!req.body.payload.cmd.match(/^[0-9a-zA-Z _\[\]"'/\\]+$/g)) {
const errorObj = {
'msg': 'error',
'result': 'wrong cli string format'
@ -301,34 +340,75 @@ shepherd.post('/cli', function(req, res, next) {
res.end(JSON.stringify(errorObj));
} else {
const _mode = req.body.payload.mode === 'passthru' ? 'passthru' : 'default';
const _chain = req.body.payload.chain ? req.body.payload.chain : '';
const _chain = req.body.payload.chain === 'KMD' ? null : req.body.payload.chain;
const _cmd = req.body.payload.cmd;
const _params = req.body.payload.params ? ' ' + req.body.payload.params : '';
exec(komodocliBin + (_chain ? ' -ac_name=' + _chain : '') + ' ' + _cmd + _params, function(error, stdout, stderr) {
console.log('stdout: ' + stdout)
console.log('stderr: ' + stderr)
if (error !== null) {
console.log('exec error: ' + error)
}
if (!rpcConf[_chain]) {
shepherd.getConf(req.body.payload.chain === 'KMD' ? 'komodod' : req.body.payload.chain);
}
let responseObj;
if (_mode === 'default') {
let _body = {
'agent': 'bitcoinrpc',
'method': _cmd
};
if (stderr) {
responseObj = {
'msg': 'error',
'result': stderr
};
} else {
responseObj = {
'msg': 'success',
'result': stdout
if (req.body.payload.params) {
_body = {
'agent': 'bitcoinrpc',
'method': _cmd,
'params': req.body.payload.params === ' ' ? [''] : req.body.payload.params
};
}
res.end(JSON.stringify(responseObj));
});
const options = {
url: `http://localhost:${rpcConf[_chain].port}`,
method: 'POST',
auth: {
'user': rpcConf[_chain].user,
'pass': rpcConf[_chain].pass
},
body: JSON.stringify(_body)
};
// send back body on both success and error
// this bit replicates iguana core's behaviour
request(options, function (error, response, body) {
if (response &&
response.statusCode &&
response.statusCode === 200) {
res.end(body);
} else {
res.end(body);
}
});
} else {
exec(komodocliBin + (_chain ? ' -ac_name=' + _chain : '') + ' ' + _cmd + _params, function(error, stdout, stderr) {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
let responseObj;
if (stderr) {
responseObj = {
'msg': 'error',
'result': stderr
};
} else {
responseObj = {
'msg': 'success',
'result': stdout
};
}
res.end(JSON.stringify(responseObj));
});
}
}
});
@ -357,14 +437,14 @@ shepherd.post('/appconf', function(req, res, next) {
});
shepherd.saveLocalAppConf = function(appSettings) {
var appConfFileName = iguanaDir + '/config.json';
let appConfFileName = `${iguanaDir}/config.json`;
_fs.access(iguanaDir, fs.constants.R_OK, function(err) {
if (!err) {
var FixFilePermissions = function() {
return new Promise(function(resolve, reject) {
var result = 'config.json file permissions updated to Read/Write';
const result = 'config.json file permissions updated to Read/Write';
fsnode.chmodSync(appConfFileName, '0666');
@ -378,7 +458,7 @@ shepherd.saveLocalAppConf = function(appSettings) {
var FsWrite = function() {
return new Promise(function(resolve, reject) {
var result = 'config.json write file is done'
const result = 'config.json write file is done';
fs.writeFile(appConfFileName,
JSON.stringify(appSettings)
@ -393,8 +473,8 @@ shepherd.saveLocalAppConf = function(appSettings) {
fsnode.chmodSync(appConfFileName, '0666');
setTimeout(function() {
console.log(result);
console.log('app conf.json file is created successfully at: ' + iguanaConfsDir);
shepherd.writeLog('app conf.json file is created successfully at: ' + iguanaConfsDir);
console.log(`app conf.json file is created successfully at: ${iguanaConfsDir}`);
shepherd.writeLog(`app conf.json file is created successfully at: ${iguanaConfsDir}`);
resolve(result);
}, 2000);
});
@ -407,15 +487,15 @@ shepherd.saveLocalAppConf = function(appSettings) {
}
shepherd.loadLocalConfig = function() {
if (fs.existsSync(iguanaDir + '/config.json')) {
var localAppConfig = fs.readFileSync(iguanaDir + '/config.json', 'utf8');
if (fs.existsSync(`${iguanaDir}/config.json`)) {
let localAppConfig = fs.readFileSync(`${iguanaDir}/config.json`, 'utf8');
console.log('app config set from local file');
shepherd.writeLog('app config set from local file');
// find diff between local and hardcoded configs
// append diff to local config
var compareJSON = function(obj1, obj2) {
var result = {};
let result = {};
for (var i in obj1) {
if (!obj2.hasOwnProperty(i)) {
@ -457,15 +537,15 @@ shepherd.loadLocalConfig = function() {
shepherd.appConfig = shepherd.loadLocalConfig();
console.log('iguana dir: ' + iguanaDir);
console.log('iguana bin: ' + iguanaBin);
console.log(`iguana dir: ${iguanaDir}`);
console.log(`iguana bin: ${iguanaBin}`);
console.log('--------------------------')
console.log('iguana dir: ' + komododBin);
console.log('iguana bin: ' + komodoDir);
shepherd.writeLog('iguana dir: ' + iguanaDir);
shepherd.writeLog('iguana bin: ' + iguanaBin);
shepherd.writeLog('iguana dir: ' + komododBin);
shepherd.writeLog('iguana bin: ' + komodoDir);
console.log(`iguana dir: ${komododBin}`);
console.log(`iguana bin: ${komodoDir}`);
shepherd.writeLog(`iguana dir: ${iguanaDir}`);
shepherd.writeLog(`iguana bin: ${iguanaBin}`);
shepherd.writeLog(`iguana dir: ${komododBin}`);
shepherd.writeLog(`iguana bin: ${komodoDir}`);
// END IGUANA FILES AND CONFIG SETTINGS
// default route
@ -526,7 +606,7 @@ shepherd.getSyncOnlyForksInfo = function() {
if (iguanaInstanceRegistry[port].mode.indexOf('/sync') > -1) {
syncOnlyIguanaInstanceInfo[port] = {};
request({
url: 'http://localhost:' + port + '/api/bitcoinrpc/getinfo?userpass=tmpIgRPCUser@' + shepherd.appSessionHash,
url: `http://localhost:${port}/api/bitcoinrpc/getinfo?userpass=tmpIgRPCUser@${shepherd.appSessionHash}`,
method: 'GET'
}, function (error, response, body) {
if (response &&
@ -541,7 +621,7 @@ shepherd.getSyncOnlyForksInfo = function() {
}
});
request({
url: 'http://localhost:' + port + '/api/SuperNET/activehandle?userpass=' + shepherd.appSessionHash,
url: `http://localhost:${port}/api/SuperNET/activehandle?userpass=${shepherd.appSessionHash}`,
method: 'GET'
}, function (error, response, body) {
if (response &&
@ -609,7 +689,7 @@ shepherd.get('/forks/restart', function(req, res, next) {
'msg': 'success',
'result': 'restarted'
};
shepherd.writeLog('iguana fork pmid ' + _pmid + ' restarted');
shepherd.writeLog(`iguana fork pmid ${_pmid} restarted`);
res.end(JSON.stringify(successObj));
});
@ -1219,10 +1299,24 @@ function herder(flock, data) {
if (status === 'closed') {
// start komodod via exec
if (data.ac_name === 'komodod') {
console.log('exec' + komododBin + ' ' + data.ac_options.join(' '));
shepherd.writeLog('exec' + komododBin + ' ' + data.ac_options.join(' '));
const _customParamDict = {
'silent': '&',
'reindex': '-reindex',
'change': '-pubkey='
};
let _customParam;
if (data.ac_custom_param === 'silent' ||
data.ac_custom_param === 'reindex') {
_customParam = ' ' + _customParamDict[data.ac_custom_param];
} else if (data.ac_custom_param === 'change' && data.ac_custom_param_value) {
_customParam = ' ' + _customParamDict[data.ac_custom_param] + data.ac_custom_param_value;
}
console.log('exec' + komododBin + ' ' + data.ac_options.join(' ') + _customParam);
shepherd.writeLog('exec' + komododBin + ' ' + data.ac_options.join(' ') + _customParam);
exec(komododBin + ' ' + data.ac_options.join(' '), {
exec(komododBin + ' ' + data.ac_options.join(' ') + _customParam, {
maxBuffer: 1024 * 10000 // 10 mb
}, function(error, stdout, stderr) {
// console.log('stdout: ' + stdout);

Loading…
Cancel
Save