Browse Source

Merge branch 'master' of https://github.com/SuperNETorg/Agama into aes-pin

all-modes
pbca26 8 years ago
parent
commit
c94c40d43a
  1. 66
      binary_artifacts_mac.sh
  2. 2
      gui/EasyDEX-GUI
  3. 154
      main.js
  4. 9
      private/mainmenu.js
  5. 41
      private/setconf.js
  6. 118
      routes/cache.js
  7. 4
      routes/mock.js
  8. 2
      routes/ports.js
  9. 596
      routes/shepherd.js

66
binary_artifacts_mac.sh

@ -0,0 +1,66 @@
echo Refreshing binaries from artifacts.supernet.org
echo =========================================
echo Step: Removing old binaries
mkdir -p build
cd build
rm -rvf artifacts.supernet.org
echo
echo Step: Cloning latest binaries for build
mkdir -p artifacts.supernet.org/latest/osx
curl "https://artifacts.supernet.org/latest/osx/iguana" -o "artifacts.supernet.org/latest/osx/iguana"
curl "https://artifacts.supernet.org/latest/osx/komodo-cli" -o "artifacts.supernet.org/latest/osx/komodo-cli"
curl "https://artifacts.supernet.org/latest/osx/komodod" -o "artifacts.supernet.org/latest/osx/komodod"
curl "https://artifacts.supernet.org/latest/osx/libgcc_s.1.dylib" -o "artifacts.supernet.org/latest/osx/libgcc_s.1.dylib"
curl "https://artifacts.supernet.org/latest/osx/libgomp.1.dylib" -o "artifacts.supernet.org/latest/osx/libgomp.1.dylib"
curl "https://artifacts.supernet.org/latest/osx/libnanomsg.5.0.0.dylib" -o "artifacts.supernet.org/latest/osx/libnanomsg.5.0.0.dylib"
curl "https://artifacts.supernet.org/latest/osx/libstdc%2B%2B.6.dylib" -o "artifacts.supernet.org/latest/osx/libstdc++.6.dylib"
chmod -R +x artifacts.supernet.org/latest/
cd ..
echo =========================================
echo
echo =========================================
echo Step: Moving osx binaries from artifacts to assets/bin/osx/
echo
mv -fv build/artifacts.supernet.org/latest/osx/iguana assets/bin/osx/
mv -fv build/artifacts.supernet.org/latest/osx/komodo-cli assets/bin/osx/
mv -fv build/artifacts.supernet.org/latest/osx/komodod assets/bin/osx/
mv -fv build/artifacts.supernet.org/latest/osx/libgcc_s.1.dylib assets/bin/osx/
mv -fv build/artifacts.supernet.org/latest/osx/libgomp.1.dylib assets/bin/osx/
mv -fv build/artifacts.supernet.org/latest/osx/libnanomsg.5.0.0.dylib assets/bin/osx/
mv -fv build/artifacts.supernet.org/latest/osx/libstdc++.6.dylib assets/bin/osx/
echo
echo =========================================
echo Step: Moving Win64 binaries from artifacts to assets/bin/win64/
echo
mv -fv build/artifacts.supernet.org/latest/windows/genkmdconf.bat assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/iguana.exe assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/index.html assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/komodo-cli.exe assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/komodo-tx.exe assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/komodod.exe assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/libcrypto-1_1.dll assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/libcurl-4.dll assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/libcurl.dll assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/libgcc_s_sjlj-1.dll assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/libnanomsg.dll assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/libssl-1_1.dll assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/libwinpthread-1.dll assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/nanomsg.dll assets/bin/win64/
mv -fv build/artifacts.supernet.org/latest/windows/pthreadvc2.dll assets/bin/win64/
echo
echo =========================================
echo Step: Moving linux64 binaries from artifacts to assets/bin/linux64
echo
mv -fv build/artifacts.supernet.org/latest/linux/iguana assets/bin/linux64/
mv -fv build/artifacts.supernet.org/latest/linux/komodo-cli assets/bin/linux64/
mv -fv build/artifacts.supernet.org/latest/linux/komodod assets/bin/linux64/
echo
echo =========================================
echo Step: Cleaning artifacts data
echo
rm -rf build/
echo
echo =========================================
echo Step: Finished Updating binaries from artifacts
echo

2
gui/EasyDEX-GUI

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

154
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,22 +139,22 @@ 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');
const guipath = path.join(__dirname, '/gui');
guiapp.use('/gui', express.static(guipath));
guiapp.use('/shepherd', shepherd);
var server = require('http').createServer(guiapp),
io = require('socket.io').listen(server);
const server = require('http').createServer(guiapp);
const 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...');
@ -176,15 +177,15 @@ shepherd.setVar('appBasicInfo', appBasicInfo);
shepherd.setVar('appSessionHash', appSessionHash);
module.exports = guiapp;
var iguanaIcon;
if (os.platform() === 'linux') {
var iguanaIcon = path.join(__dirname, '/assets/icons/agama_icons/128x128.png');
iguanaIcon = path.join(__dirname, '/assets/icons/agama_icons/128x128.png');
}
if (os.platform() === 'win32') {
var iguanaIcon = path.join(__dirname, '/assets/icons/agama_icons/agama_app_icon.ico');
iguanaIcon = path.join(__dirname, '/assets/icons/agama_icons/agama_app_icon.ico');
}
let mainWindow;
let loadingWindow;
let willQuitApp = false;
@ -204,7 +205,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
@ -227,35 +228,6 @@ function createLoadingWindow() {
e.preventDefault();
}
});
/*
* var ipc = require('electron').ipcRenderer;
* ipc.once('coincliReply', function(event, response){
* console.log(response);
* });
* ipc.send('InvokeCoinCliAction', '{"cli":"kmd","command":"getinfo"}');
*/
ipc.on('InvokeCoinCliAction', function(event, data){
console.log(JSON.stringify(data));
console.log(data.cli)
console.log(data.command)
if (data.cli == 'kmd') {
coincli.kmdcommand(data.command, function(err, command) {
//console.log(command);
var result = command;
event.sender.send('coincliReply', result);
});
}
if (data.cli == 'zec') {
coincli.zeccommand(data.command, function(err, command) {
//console.log(command);
var result = command;
event.sender.send('coincliReply', result);
});
}
});
}
app.on('ready', createLoadingWindow);
@ -277,13 +249,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,18 +276,18 @@ 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
const { selectionText, isEditable } = params; //params obj
mainWindow.webContents.on('context-menu', (e, params) => { // context-menu returns params
const { selectionText, isEditable } = params; // params obj
if (isEditable) {
editMenu.popup(mainWindow);
@ -328,7 +300,7 @@ function createWindow (status) {
// mainWindow.webContents.openDevTools()
function pm2Exit() {
var ConnectToPm2 = function() {
const ConnectToPm2 = function() {
return new Promise(function(resolve, reject) {
console.log('Closing Main Window...');
shepherd.writeLog('exiting app...');
@ -349,7 +321,7 @@ function createWindow (status) {
}
});
var result = 'Connecting To Pm2: done';
const result = 'Connecting To Pm2: done';
console.log(result);
shepherd.writeLog(result);
@ -357,7 +329,7 @@ function createWindow (status) {
})
}
var KillPm2 = function() {
const KillPm2 = function() {
return new Promise(function(resolve, reject) {
console.log('killing to pm2...');
shepherd.writeLog('killing to pm2...');
@ -371,7 +343,7 @@ function createWindow (status) {
throw err;
});
var result = 'Killing Pm2: done';
const result = 'Killing Pm2: done';
setTimeout(function() {
console.log(result);
@ -382,21 +354,21 @@ function createWindow (status) {
})
}
var HideMainWindow = function() {
const HideMainWindow = function() {
return new Promise(function(resolve, reject) {
console.log('Exiting App...');
mainWindow = null;
var result = 'Hiding Main Window: done';
const result = 'Hiding Main Window: done';
console.log(result);
resolve(result);
});
}
var QuitApp = function() {
const QuitApp = function() {
return new Promise(function(resolve, reject) {
app.quit();
var result = 'Quiting App: done';
const result = 'Quiting App: done';
console.log(result);
resolve(result);
});
@ -471,20 +443,20 @@ function formatBytes(bytes, decimals) {
if (bytes === 0)
return '0 Bytes';
var k = 1000,
dm = decimals + 1 || 3,
sizes = [
'Bytes',
'KB',
'MB',
'GB',
'TB',
'PB',
'EB',
'ZB',
'YB'
],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
const k = 1000,
dm = decimals + 1 || 3,
sizes = [
'Bytes',
'KB',
'MB',
'GB',
'TB',
'PB',
'EB',
'ZB',
'YB'
],
i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
}

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',

596
routes/shepherd.js

File diff suppressed because it is too large
Loading…
Cancel
Save