Browse Source

Merge pull request #159 from SuperNETorg/master

autobuild update
pkg_automation_electrum
ca333 7 years ago
committed by GitHub
parent
commit
dbcf313b20
  1. 2
      gui/EasyDEX-GUI
  2. 28
      gui/agama-instance-error.html
  3. BIN
      gui/bg.jpg
  4. BIN
      gui/bg2.jpg
  5. 31
      gui/bluebird.min.js
  6. 34
      gui/index.html
  7. 48
      gui/init.js
  8. 6
      gui/jRoll.min.css
  9. 1
      gui/jRoll.min.js
  10. 28
      gui/loading.css
  11. 189
      gui/loading.js
  12. 4
      gui/module-hack.js
  13. 117
      main.js
  14. 30
      make-patch.sh
  15. 7
      package.json
  16. 2
      routes/cache.js
  17. 24
      routes/ports.js
  18. 789
      routes/shepherd.js
  19. 3
      version

2
gui/EasyDEX-GUI

@ -1 +1 @@
Subproject commit ba50df3108aa7c3dc27583f15e4f85d80ac08cda
Subproject commit 7399c05db6464596edf4c242f5a3a57445c70ded

28
gui/agama-instance-error.html

@ -0,0 +1,28 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="EasyDEX-GUI/assets/global/css/bootstrap.min.css">
<link rel="stylesheet" href="EasyDEX-GUI/assets/mainWindow/css/jRoll.min.css">
<link rel="stylesheet" href="EasyDEX-GUI/assets/mainWindow/css/loading.css">
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/module-hack.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/global/vendor/jquery/jquery.min.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/scripts/config.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/bluebird.min.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/loading.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/jRoll.min.js"></script>
<script>if (window.module) module = window.module;</script>
</head>
<body class="agamaMode">
<div class="text-center">
<div id="agamaMode">
<img src="EasyDEX-GUI/assets/mainWindow/img/agama-icon.svg" class="agama-logo" alt="Agama Wallet" width="80" height="100" />
<div id="agamaModeStatus">Another Agama instance is already running!</div>
<div>Please close all other instaces and restart the app.</div>
<br />
<button onClick="quitApp()" class="btn btn-primary btn-close-app">Quit</button>
</div>
</div>
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/init.js"></script>
</body>
</html>

BIN
gui/bg.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

BIN
gui/bg2.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

31
gui/bluebird.min.js

File diff suppressed because one or more lines are too long

34
gui/index.html

@ -3,25 +3,33 @@
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="EasyDEX-GUI/assets/global/css/bootstrap.min.css">
<link rel="stylesheet" href="jRoll.min.css">
<link rel="stylesheet" href="loading.css">
<script type="text/javascript" src="module-hack.js"></script>
<link rel="stylesheet" href="EasyDEX-GUI/assets/mainWindow/css/jRoll.min.css">
<link rel="stylesheet" href="EasyDEX-GUI/assets/mainWindow/css/loading.css">
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/module-hack.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/global/vendor/jquery/jquery.min.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/scripts/config.js"></script>
<script type="text/javascript" src="bluebird.min.js"></script>
<script type="text/javascript" src="loading.js"></script>
<script type="text/javascript" src="jRoll.min.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/bluebird.min.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/loading.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/jRoll.min.js"></script>
<script>if (window.module) module = window.module;</script>
</head>
<body>
<body class="agamaMode">
<div class="text-center">
<div class="loader-block">
<div id="loading_status_text">Starting Wallet. Please wait...</div>
<div id="loading_sub_status_text"></div>
<div id="loading_sub_status_output_text"></div>
<!--div id="normalStart">
<div class="loader-block">
<div id="loading_status_text">Starting Wallet. Please wait...</div>
<div id="loading_sub_status_text"></div>
<div id="loading_sub_status_output_text"></div>
</div>
<div id="pulse" class="pulse-loader"></div>
</div-->
<div id="agamaMode">
<img src="EasyDEX-GUI/assets/mainWindow/img/agama-icon.svg" class="agama-logo" alt="Agama Wallet" width="80" height="100" />
<div id="agamaModeStatus">Choose Agama mode</div>
<button onClick="closeMainWindow()" class="btn btn-primary">Native only</button>
<button onClick="normalStart()" class="btn btn-primary">Normal start</button>
</div>
<div id="pulse" class="pulse-loader"></div>
</div>
<script type="text/javascript" src="init.js"></script>
<script type="text/javascript" src="EasyDEX-GUI/assets/mainWindow/js/init.js"></script>
</body>
</html>

48
gui/init.js

@ -1,48 +0,0 @@
$(document).ready(function() {
const remote = require('electron').remote;
var window = remote.getCurrentWindow();
$('#pulse').jRoll({
radius: 100,
animation: 'pulse'
});
$('#loading_status_text').text('Starting Iguana daemon...');
GetAppConf(inititalWalletLoading);
function inititalWalletLoading(appConf) {
if (appConf && !appConf.manualIguanaStart) {
StartIguana();
}
var portcheck;
function startcheck() {
portcheck = setInterval(function(){
Iguana_activehandle(appConf).then(function(result){
console.log(result);
if (result !== 'error') {
stopcheck();
if (appConf && appConf.useBasiliskInstance) {
StartIguana_Cache();
}
$('#loading_status_text').text('Connecting to Basilisk Network...');
EDEX_DEXgetinfoAll(appConf.skipBasiliskNetworkCheck, appConf.minNotaries, appConf);
}
})
//var check = Iguana_activehandle();
//console.log(check[0])
}, 2000);
}
function stopcheck() {
clearInterval(portcheck);
}
startcheck();
}
});

6
gui/jRoll.min.css

File diff suppressed because one or more lines are too long

1
gui/jRoll.min.js

File diff suppressed because one or more lines are too long

28
gui/loading.css

@ -1,28 +0,0 @@
body {
overflow: hidden !important;
border: solid 1px #ccc;
height: 300px;
}
.text-center {
text-align: center;
}
.loader-block {
height: 240px;
width: 100%;
position: absolute;
top: -30px;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
.pulse-loader {
position: absolute;
top: 10px;
left: -100px;
margin: 80px 50px;
width: 400px !important;
}

189
gui/loading.js

@ -1,189 +0,0 @@
function IguanaAJAX(url, ajax_data, timeout) {
return $.ajax({
data: JSON.stringify(ajax_data),
url: url,
type: 'POST',
dataType: 'json',
timeout: timeout ? timeout : 120000
//beforeSend: showLoadingImgFn
})
.fail(function(xhr, textStatus, error) {
// handle request failures
});
}
function Iguana_activehandle(appConf) {
return new Promise((resolve) => {
var ajax_data = {
'agent': 'SuperNET',
'method': 'activehandle'
},
AjaxOutputData = IguanaAJAX('http://127.0.0.1:' + appConf.iguanaCorePort, ajax_data).done(function(data) {
//$('#loading_status_text').text('Retrieving active handle...');
//console.log(AjaxOutputData.responseText);
AjaxOutputData = JSON.parse(AjaxOutputData.responseText)
//console.log(AjaxOutputData);
resolve(AjaxOutputData);
})
.fail(function(xhr, textStatus, error) {
// $('#loading_status_text').text('Retrieving active handle error!');
// handle request failures
console.log(xhr.statusText);
if ( xhr.readyState == 0 ) {
}
console.log(textStatus);
console.log(error);
});
});
}
//Iguana_activehandle().then(function(result){
//console.log(result)
//})
function StartIguana() {
var ajax_data = { 'herd': 'iguana'};
console.log(ajax_data);
$.ajax({
type: 'POST',
data: JSON.stringify(ajax_data),
url: 'http://127.0.0.1:17777/shepherd/herd',
dataType: 'xml/html/script/json', // expected format for response
contentType: 'application/json', // send as JSON
success: function(data, textStatus, jqXHR) {
var AjaxOutputData = JSON.parse(data);
console.log('== ActiveHandle Data OutPut ==');
console.log(AjaxOutputData);
},
error: function(xhr, textStatus, error) {
console.log(xhr.statusText);
if ( xhr.readyState == 0 ) {
}
console.log(textStatus);
console.log(error);
}
});
}
function StartIguana_Cache() {
var ajax_data = {
'mode': 'basilisk',
'coin': 'all'
};
var start_iguana_cache= $.ajax({
type: 'POST',
data: JSON.stringify(ajax_data),
url: 'http://127.0.0.1:17777/shepherd/forks',
contentType: 'application/json', // send as JSON
})
start_iguana_cache.done(function(data) {
_data = JSON.parse(data);
console.log(_data.result);
sessionStorage.setItem('IguanaCachePort', _data.result);
});
}
function GetAppConf(cb) { // get iguana app conf
var ajax_data = { 'herd': 'iguana' },
data = false;
console.log(ajax_data);
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:17777/shepherd/appconf'
})
.done(function(_data) {
console.log('== App Conf Data OutPut ==');
console.log(_data);
data = _data;
cb.call(this, data);
})
.fail(function(xhr, textStatus, error) {
// handle request failures
console.log(xhr.statusText);
if ( xhr.readyState == 0 ) {
}
console.log(textStatus);
console.log(error);
cb.call(this, data);
});
return data;
}
function EDEX_DEXgetinfoAll(skip, minNotaries, appConf) {
const remote = require('electron').remote;
var window = remote.getCurrentWindow();
if (!skip) {
var tmpIguanaRPCAuth = 'tmpIgRPCUser@' + sessionStorage.getItem('IguanaRPCAuth'),
ajax_data = {
'userpass': tmpIguanaRPCAuth,
'agent': 'dpow',
'method': 'notarychains'
},
tmp_index = 0,
tmp_index_failed = 0,
get_dex_notarychains = IguanaAJAX('http://127.0.0.1:' + appConf.iguanaCorePort, ajax_data, 10000).done(function(data) {
get_dex_notarychains = JSON.parse(get_dex_notarychains.responseText);
if (minNotaries > get_dex_notarychains.length) { // if config value exceeds total num of notaries
minNotaries = get_dex_notarychains.length;
}
get_dex_notarychains = get_dex_notarychains.splice(0, minNotaries);
$.each(get_dex_notarychains, function( coin_index, coin_value ) {
console.log(coin_index + ': ' + coin_value);
var tmpIguanaRPCAuth = 'tmpIgRPCUser@' + sessionStorage.getItem('IguanaRPCAuth'),
ajax_data = {
'userpass': tmpIguanaRPCAuth,
'agent': 'dex',
'method': 'getinfo',
'symbol': coin_value
};
console.log(ajax_data);
if (coin_value !== 'MESH' || coin_value !== 'CEAL') {
var getinfo_each_chain = IguanaAJAX('http://127.0.0.1:' + appConf.iguanaCorePort, ajax_data, 10000).done(function(data) {
getinfo_each_chain = JSON.parse(getinfo_each_chain.responseText);
console.log(getinfo_each_chain);
tmp_index++;
$('#loading_sub_status_text').text('Connection status... ' + tmp_index + '/' + get_dex_notarychains.length + ': ' + coin_value);
if (getinfo_each_chain.error === 'less than required responses') {
$('#loading_sub_status_output_text').text('Output: ' + getinfo_each_chain.error);
} else {
$('#loading_sub_status_output_text').text('Output: Connected');
}
if ( tmp_index + tmp_index_failed === minNotaries ) {
console.log('min notaries connected');
window.createWindow('open');
window.hide();
}
})
.fail(function(xhr, textStatus, error) {
tmp_index_failed++;
if ( tmp_index + tmp_index_failed === minNotaries ) {
console.log('min notaries connected');
window.createWindow('open');
window.hide();
}
// handle request failures
console.log(xhr.statusText);
if ( xhr.readyState == 0 ) {
}
console.log(textStatus);
console.log(error);
});
}
});
});
} else {
window.createWindow('open');
window.hide();
}
}

4
gui/module-hack.js

@ -1,4 +0,0 @@
if (typeof module === 'object') {
window.module = module;
module = undefined;
}

117
main.js

@ -11,6 +11,8 @@ const electron = require('electron'),
spawn = require('child_process').spawn,
exec = require('child_process').exec,
{ Menu } = require('electron'),
portscanner = require('portscanner'),
osPlatform = os.platform(),
fixPath = require('fix-path');
var express = require('express'),
@ -26,23 +28,32 @@ var express = require('express'),
Promise = require('bluebird');
if (osPlatform === 'linux') {
process.env.ELECTRON_RUN_AS_NODE = true;
// console.log(process.env);
}
// GUI APP settings and starting gui on address http://120.0.0.1:17777
var shepherd = require('./routes/shepherd');
var guiapp = express();
let localVersion;
let localVersionFile = shepherd.readVersionFile();
if (localVersionFile.indexOf('\r\n') > -1) {
localVersion = localVersionFile.split('\r\n');
} else {
localVersion = localVersionFile.split('\n');
}
const appBasicInfo = {
name: 'Agama',
version: '0.2.0.1a-beta'
version: localVersion[0],
};
app.setName(appBasicInfo.name);
app.setVersion(appBasicInfo.version);
if (os.platform() === 'linux') {
process.env.ELECTRON_RUN_AS_NODE = true;
// console.log(process.env);
}
// GUI APP settings and starting gui on address http://120.0.0.1:17777
var shepherd = require('./routes/shepherd'),
guiapp = express();
shepherd.createIguanaDirs();
const appSessionHash = md5(Date.now());
@ -54,7 +65,7 @@ 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(`platform: ${osPlatform}`);
shepherd.writeLog(`os_release: ${os.release()}`);
shepherd.writeLog(`os_type: ${os.type()}`);
@ -64,21 +75,25 @@ shepherd.writeLog(`app started in ${(appConfig.dev ? 'dev mode' : ' user mode')}
shepherd.setConfKMD();
// kill rogue iguana copies on start
if (appConfig.killIguanaOnStart) {
let iguanaGrep;
if (os.platform() === 'darwin') {
iguanaGrep = "ps -p $(ps -A | grep -m1 iguana | awk '{print $1}') | grep -i iguana";
}
if (os.platform() === 'linux') {
iguanaGrep = 'ps -p $(pidof iguana) | grep -i iguana';
}
if (os.platform() === 'win32') {
iguanaGrep = 'tasklist';
switch (osPlatform) {
case 'darwin':
iguanaGrep = "ps -p $(ps -A | grep -m1 iguana | awk '{print $1}') | grep -i iguana";
break;
case 'linux':
iguanaGrep = 'ps -p $(pidof iguana) | grep -i iguana';
break;
case 'win32':
iguanaGrep = 'tasklist';
break;
}
exec(iguanaGrep, function(error, stdout, stderr) {
if (stdout.indexOf('iguana') > -1) {
const pkillCmd = os.platform() === 'win32' ? 'taskkill /f /im iguana.exe' : 'pkill -15 iguana';
const pkillCmd = osPlatform === 'win32' ? 'taskkill /f /im iguana.exe' : 'pkill -15 iguana';
console.log('found another iguana process(es)');
shepherd.writeLog('found another iguana process(es)');
@ -118,7 +133,7 @@ process.once('loaded', () => {
global.setImmediate = _setImmediate;
global.clearImmediate = _clearImmediate;
if (os.platform() === 'darwin') {
if (osPlatform === 'darwin') {
process.setFdLimit(appConfig.maxDescriptors.darwin);
app.setAboutPanelOptions({
applicationName: app.getName(),
@ -127,7 +142,7 @@ process.once('loaded', () => {
credits: 'SuperNET Team'
})
}
if (os.platform() === 'linux') {
if (osPlatform === 'linux') {
process.setFdLimit(appConfig.maxDescriptors.linux);
}
});
@ -148,10 +163,25 @@ guiapp.use('/shepherd', shepherd);
const server = require('http').createServer(guiapp);
const io = require('socket.io').listen(server);
let willQuitApp = false;
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}`);
// check if agama is already running
portscanner.checkPortStatus(appConfig.agamaPort, '127.0.0.1', function(error, status) {
// Status is 'open' if currently in use or 'closed' if available
if (status === 'closed') {
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}`);
});
} else {
willQuitApp = true;
server.listen(appConfig.agamaPort + 1, function() {
console.log(`guiapp and sockets.io are listening on port ${appConfig.agamaPort + 1}`);
shepherd.writeLog(`guiapp and sockets.io are listening on port ${appConfig.agamaPort + 1}`);
});
loadingWindow.loadURL(`http://${appConfig.host}:${appConfig.agamaPort + 1}/gui/agama-instance-error.html`);
console.log('another agama app is already running');
}
});
io.set('origins', appConfig.dev ? 'http://127.0.0.1:3000' : `http://127.0.0.1:${appConfig.agamaPort}`); // set origin
@ -188,7 +218,6 @@ if (os.platform() === 'win32') {
let mainWindow;
let loadingWindow;
let willQuitApp = false;
let closeAppAfterLoading = false;
function createLoadingWindow() {
@ -199,13 +228,21 @@ function createLoadingWindow() {
width: 500,
height: 300,
frame: false,
icon: iguanaIcon
icon: iguanaIcon,
show: false,
});
loadingWindow.createWindow = createWindow; // expose createWindow to front-end scripts
loadingWindow.appConfig = appConfig;
loadingWindow.forseCloseApp = forseCloseApp;
// load our index.html (i.e. easyDEX GUI)
loadingWindow.loadURL(`http://${appConfig.host}:${appConfig.agamaPort}/gui/`);
loadingWindow.webContents.on('did-finish-load', function() {
setTimeout(function() {
loadingWindow.show();
}, 40);
});
shepherd.writeLog('show loading window');
// DEVTOOLS - only for dev purposes - ca333
@ -230,17 +267,25 @@ function createLoadingWindow() {
});
}
// close app
function forseCloseApp() {
loadingWindow = null;
mainWindow = null;
app.quit();
}
app.on('ready', createLoadingWindow);
function createWindow (status) {
if ( status === 'open') {
if (status === 'open') {
require(path.join(__dirname, 'private/mainmenu'));
// initialise window
mainWindow = new BrowserWindow({ // dirty hack to prevent main window flash on quit
width: closeAppAfterLoading ? 1 : 1280,
height: closeAppAfterLoading ? 1 : 800,
icon: iguanaIcon
icon: iguanaIcon,
show: false,
});
if (closeAppAfterLoading) {
@ -271,13 +316,22 @@ function createWindow (status) {
if (appConfig.v2) {
shepherd.writeLog('show edex gui');
mainWindow.appConfig = appConfig;
mainWindow.appBasicInfo = appBasicInfo;
mainWindow.appSessionHash = appSessionHash;
mainWindow.assetChainPorts = require('./routes/ports.js');
mainWindow.zcashParamsExist = shepherd.zcashParamsExist();
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.webContents.on('did-finish-load', function() {
setTimeout(function() {
mainWindow.show();
}, 40);
});
} else {
shepherd.writeLog('show edex gui');
mainWindow.loadURL(`http://${appConfig.host}:${appConfig.agamaPort}/gui/EasyDEX-GUI/`);
@ -307,10 +361,6 @@ function createWindow (status) {
shepherd.dumpCacheBeforeExit();
shepherd.quitKomodod();
// if komodod is under heavy load it may not respond to cli stop the first time
setInterval(function() {
shepherd.quitKomodod();
}, 100);
pm2.connect(true, function(err) {
console.log('connecting to pm2...');
@ -367,6 +417,7 @@ function createWindow (status) {
const QuitApp = function() {
return new Promise(function(resolve, reject) {
KillPm2(); // required for normal app quit in iguana-less mode
app.quit();
const result = 'Quiting App: done';
console.log(result);

30
make-patch.sh

@ -0,0 +1,30 @@
cd gui/EasyDEX-GUI/react
echo "building gui..."
rm -rf ./build
mkdir build
mkdir build/assets
cp -R src/assets build/
NODE_ENV="production" webpack
cd ../../../
echo "copy patch files"
rm -rf ./patch.zip
rm -rf ./patch
mkdir patch
mkdir patch/gui
mkdir patch/gui/EasyDEX-GUI
mkdir patch/gui/EasyDEX-GUI/react
mkdir patch/gui/EasyDEX-GUI/react
cp -R gui/EasyDEX-GUI/react/build patch/gui/EasyDEX-GUI/react/build
cp -R gui/EasyDEX-GUI/assets patch/gui/EasyDEX-GUI
cp gui/index.html patch/gui/index.html
cp ./main.js patch
cp ./version patch
cp -R routes patch/routes
cp -R private patch/private
echo "package patch.zip"
cd patch
zip -r patch.zip gui routes private main.js version
cd ../
cp patch/patch.zip ./
rm -rf patch
echo "patch.zip is ready"

7
package.json

@ -5,7 +5,8 @@
"description": "Agama Desktop App",
"main": "main.js",
"scripts": {
"start": "electron ."
"start": "electron .",
"make-patch": "./make-patch.sh"
},
"repository": "https://github.com/SuperNETorg/Agama/",
"keywords": [
@ -23,9 +24,9 @@
"electron": "^1.4.1"
},
"dependencies": {
"adm-zip": "^0.4.7",
"bluebird": "^3.4.7",
"body-parser": "^1.15.2",
"corsproxy": "^1.5.0",
"electron": "^1.6.5",
"express": "^4.14.0",
"fix-path": "^2.1.0",
@ -33,9 +34,11 @@
"graceful-fs": "^4.1.11",
"md5": "^2.2.1",
"mkdirp": "^0.5.1",
"nodejs-aes256": "^1.0.1",
"pm2": "^2.4.3",
"portscanner": "^2.1.1",
"ps-node": "^0.1.5",
"remote-file-size": "^3.0.3",
"request": "^2.80.0",
"rimraf": "^2.6.1",
"socket.io": "^1.7.3"

2
routes/cache.js

@ -457,7 +457,7 @@ cache.one = function(req, res, next) {
var tooEarly = false;
if (outObj.basilisk[coin][address][key] &&
outObj.basilisk[coin][address][key].timestamp &&
checkTimestamp(outObj.basilisk[coin][address][key].timestamp) < cacheGlobLifetime) {
(!skipTimeout && checkTimestamp(outObj.basilisk[coin][address][key].timestamp) < cacheGlobLifetime)) {
tooEarly = true;
outObj.basilisk[coin][address][key].status = 'done';
cache.io.emit('messages', {

24
routes/ports.js

@ -3,19 +3,20 @@ const assetChainPorts = {
'SUPERNET': '11341',
'REVS': '10196',
'WLC': '12167',
'PANGEA': '10074',
'DEX': '9503',
'JUMBLR': '10789',
'BET': '11222',
'CRYPTO': '10420',
'PANGEA': '14068',
'DEX': '11890',
'JUMBLR': '15106',
'BET': '14250',
'CRYPTO': '8516',
'HODL': '8010',
'SHARK': '14104',
'BOTS': '10151',
'MGW': '15524',
'SHARK': '10114',
'BOTS': '11964',
'MGW': '12386',
'COQUI': '14276',
'MVP': '11676',
'KV': '9747',
'CEAL': '13097',
'MESH': '8400',
'KV': '8299',
'CEAL': '11116',
'MESH': '9455',
'USD': '13967',
'CHF': '15312',
'CAD': '8720',
@ -35,6 +36,7 @@ const assetChainPorts = {
'IDR': '14459',
'HKD': '15409',
'HUF': '13699',
'HRK': '12617',
'GBP': '11505',
'EUR': '8065',
'DKK': '13830',

789
routes/shepherd.js

@ -17,6 +17,8 @@ const electron = require('electron'),
async = require('async'),
rimraf = require('rimraf'),
portscanner = require('portscanner'),
AdmZip = require('adm-zip'),
remoteFileSize = require('remote-file-size'),
Promise = require('bluebird');
const fixPath = require('fix-path');
@ -25,6 +27,7 @@ var ps = require('ps-node'),
assetChainPorts = require('./ports.js'),
shepherd = express.Router(),
iguanaInstanceRegistry = {},
coindInstanceRegistry = {},
syncOnlyIguanaInstanceInfo = {},
syncOnlyInstanceInterval = -1,
guiLog = {},
@ -46,7 +49,7 @@ if (os.platform() === 'darwin') {
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/ZcashParams`;
}
if (os.platform() === 'linux') {
@ -57,6 +60,7 @@ if (os.platform() === 'linux') {
komododBin = path.join(__dirname, '../assets/artifacts.supernet.org/latest/linux/komodod'),
komodocliBin = path.join(__dirname, '../assets/artifacts.supernet.org/latest/linux/komodo-cli'),
komodoDir = `${process.env.HOME}/.komodo`;
zcashDir = `${process.env.HOME}/.zcash-params`;
}
if (os.platform() === 'win32') {
@ -74,6 +78,7 @@ if (os.platform() === 'win32') {
komodocliBin = path.normalize(komodocliBin),
komodoDir = `${process.env.APPDATA}/Komodo`,
komodoDir = path.normalize(komodoDir);
zcashDir = `${process.env.APPDATA}/ZcashParams`;
}
shepherd.appConfig = {
@ -93,29 +98,55 @@ shepherd.appConfig = {
"dev": false,
"v2": true,
"useBasiliskInstance": true,
"debug": true,
"debug": false,
"cli": {
"passthru": false,
"default": false
}
"passthru": true,
"default": true
},
"iguanaLessMode": true,
"roundValues": false,
};
shepherd.defaultAppConfig = Object.assign({}, shepherd.appConfig);
shepherd.zcashParamsExist = function() {
if (fs.existsSync(zcashDir) &&
fs.existsSync(`${zcashDir}/sprout-proving.key`) &&
fs.existsSync(`${zcashDir}/sprout-verifying.key`)) {
console.log('zcashparams exist');
return true;
}
console.log('zcashparams doesnt exist');
return false;
}
shepherd.readVersionFile = function() {
// read app version
const rootLocation = path.join(__dirname, '../');
const localVersionFile = fs.readFileSync(rootLocation + 'version', 'utf8');
return localVersionFile;
}
shepherd.writeLog = function(data) {
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 (err) {
console.log('error writing log file');
}
});
} else {
fs.writeFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, function (err) {
if (err) {
console.log('error writing log file');
}
});
if (shepherd.appConfig.debug) {
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) {
if (err) {
console.log('error writing log file');
}
});
}
}
}
@ -143,6 +174,365 @@ shepherd.createIguanaDirs = function() {
}
}
/**
* Promise based download file method
*/
function downloadFile(configuration) {
return new Promise(function(resolve, reject) {
// Save variable to know progress
let receivedBytes = 0;
let totalBytes = 0;
let req = request({
method: 'GET',
uri: configuration.remoteFile,
agentOptions: {
keepAlive: true,
keepAliveMsecs: 15000,
}
});
let out = fs.createWriteStream(configuration.localFile);
req.pipe(out);
req.on('response', function(data) {
// Change the total bytes value to get progress later.
totalBytes = parseInt(data.headers['content-length']);
});
// Get progress if callback exists
if (configuration.hasOwnProperty('onProgress')) {
req.on('data', function(chunk) {
// Update the received bytes
receivedBytes += chunk.length;
configuration.onProgress(receivedBytes, totalBytes);
});
} else {
req.on('data', function(chunk) {
// Update the received bytes
receivedBytes += chunk.length;
});
}
req.on('end', function() {
resolve();
});
});
}
const remoteBinLocation = {
'win32': 'https://artifacts.supernet.org/latest/windows/',
'darwin': 'https://artifacts.supernet.org/latest/osx/',
'linux': 'https://artifacts.supernet.org/latest/linux/',
};
const localBinLocation = {
'win32': 'assets/bin/win64/',
'darwin': 'assets/bin/osx/',
'linux': 'assets/bin/linux64/',
};
const latestBins = {
'win32': [
'iguana.exe',
'komodo-cli.exe',
'komodod.exe',
'libcrypto-1_1.dll',
'libcurl-4.dll',
'libcurl.dll',
'libgcc_s_sjlj-1.dll',
'libnanomsg.dll',
'libssl-1_1.dll',
'libwinpthread-1.dll',
'nanomsg.dll',
'pthreadvc2.dll',
],
'darwin': [
'iguana',
'komodo-cli',
'komodod',
'libgcc_s.1.dylib',
'libgomp.1.dylib',
'libnanomsg.5.0.0.dylib',
'libstdc++.6.dylib', // encode %2B
],
'linux': [
'iguana',
'komodo-cli',
'komodod',
]
};
let binsToUpdate = [];
/*
* Check bins file size
* type:
* params:
*/
shepherd.get('/update/bins/check', function(req, res, next) {
const rootLocation = path.join(__dirname, '../');
const successObj = {
'msg': 'success',
'result': 'bins',
};
res.end(JSON.stringify(successObj));
const _os = os.platform();
console.log('checking bins: ' + _os);
cache.io.emit('patch', {
'patch': {
'type': 'bins-check',
'status': 'progress',
'message': 'checking bins: ' + _os,
},
});
// get list of bins/dlls that can be updated to the latest
for (let i = 0; i < latestBins[_os].length; i++) {
remoteFileSize(remoteBinLocation[_os] + latestBins[_os][i], function(err, remoteBinSize) {
const localBinSize = fs.statSync(rootLocation + localBinLocation[_os] + latestBins[_os][i]).size;
console.log('remote url: ' + (remoteBinLocation[_os] + latestBins[_os][i]) + ' (' + remoteBinSize + ')');
console.log('local file: ' + (rootLocation + localBinLocation[_os] + latestBins[_os][i]) + ' (' + localBinSize + ')');
if (remoteBinSize !== localBinSize) {
console.log(latestBins[_os][i] + ' can be updated');
binsToUpdate.push({
'name': latestBins[_os][i],
'rSize': remoteBinSize,
'lSize': localBinSize,
});
}
if (i === latestBins[_os].length - 1) {
cache.io.emit('patch', {
'patch': {
'type': 'bins-check',
'status': 'done',
'fileList': binsToUpdate,
}
});
}
});
}
});
/*
* Update bins
* type:
* params:
*/
shepherd.get('/update/bins', function(req, res, next) {
const rootLocation = path.join(__dirname, '../');
const _os = os.platform();
const successObj = {
'msg': 'success',
'result': {
'filesCount': binsToUpdate.length,
'list': binsToUpdate,
}
};
res.end(JSON.stringify(successObj));
for (let i = 0; i < binsToUpdate.length; i++) {
downloadFile({
remoteFile: remoteBinLocation[_os] + binsToUpdate[i].name,
localFile: rootLocation + localBinLocation[_os] + 'patch/' + binsToUpdate[i].name,
onProgress: function(received, total) {
const percentage = (received * 100) / total;
cache.io.emit('patch', {
'msg': {
'type': 'bins-update',
'status': 'progress',
'file': binsToUpdate[i].name,
'bytesTotal': total,
'bytesReceived': received,
}
});
console.log(binsToUpdate[i].name + ' ' + percentage + '% | ' + received + ' bytes out of ' + total + ' bytes.');
}
})
.then(function() {
// verify that remote file is matching to DL'ed file
const localBinSize = fs.statSync(rootLocation + localBinLocation[_os] + 'patch/' + binsToUpdate[i].name).size;
console.log('compare dl file size');
if (localBinSize === binsToUpdate[i].rSize) {
cache.io.emit('patch', {
'msg': {
'type': 'bins-update',
'file': binsToUpdate[i].name,
'status': 'done',
}
});
console.log('file ' + binsToUpdate[i].name + ' succesfully downloaded');
} else {
cache.io.emit('patch', {
'msg': {
'type': 'bins-update',
'file': binsToUpdate[i].name,
'message': 'size mismatch',
}
});
console.log('error: ' + binsToUpdate[i].name + ' file size doesnt match remote!');
}
});
}
});
/*
* DL app patch
* type:
* params: patchList
*/
shepherd.get('/update/patch', function(req, res, next) {
const successObj = {
'msg': 'success',
'result': 'dl started'
};
res.end(JSON.stringify(successObj));
shepherd.updateAgama();
});
shepherd.updateAgama = function() {
const rootLocation = path.join(__dirname, '../');
downloadFile({
remoteFile: 'https://github.com/pbca26/dl-test/raw/master/patch.zip',
localFile: rootLocation + 'patch.zip',
onProgress: function(received, total) {
const percentage = (received * 100) / total;
if (Math.floor(percentage) % 5 === 0 ||
Math.floor(percentage) % 10 === 0) {
console.log('patch ' + percentage + '% | ' + received + ' bytes out of ' + total + ' bytes.');
cache.io.emit('patch', {
'msg': {
'status': 'progress',
'type': 'ui',
'progress': percentage,
'bytesTotal': total,
'bytesReceived': received
}
});
}
}
})
.then(function() {
remoteFileSize('https://github.com/pbca26/dl-test/raw/master/patch.zip', function(err, remotePatchSize) {
// verify that remote file is matching to DL'ed file
const localPatchSize = fs.statSync(rootLocation + 'patch.zip').size;
console.log('compare dl file size');
if (localPatchSize === remotePatchSize) {
console.log('patch succesfully downloaded');
console.log('extracting contents');
const zip = new AdmZip(rootLocation + 'patch.zip');
if (shepherd.appConfig.dev) {
if (!fs.existsSync(`${rootLocation}/patch`)) {
fs.mkdirSync(`${rootLocation}/patch`);
}
}
zip.extractAllTo(/*target path*/rootLocation + (shepherd.appConfig.dev ? '/patch' : ''), /*overwrite*/true);
// TODO: extract files in chunks
cache.io.emit('patch', {
'msg': {
'type': 'ui',
'status': 'done'
}
});
fs.unlink(rootLocation + 'patch.zip');
} else {
cache.io.emit('patch', {
'msg': {
'type': 'ui',
'status': 'error',
'message': 'size mismatch'
}
});
console.log('patch file size doesnt match remote!');
}
});
});
}
/*
* check latest version
* type:
* params:
*/
shepherd.get('/update/patch/check', function(req, res, next) {
const rootLocation = path.join(__dirname, '../');
const options = {
url: 'https://github.com/pbca26/dl-test/raw/master/version',
method: 'GET'
};
request(options, function (error, response, body) {
if (response &&
response.statusCode &&
response.statusCode === 200) {
const remoteVersion = body.split('\n');
const localVersionFile = fs.readFileSync(rootLocation + 'version', 'utf8');
let localVersion;
if (localVersionFile.indexOf('\r\n') > -1) {
localVersion = localVersionFile.split('\r\n');
} else {
localVersion = localVersionFile.split('\n');
}
if (remoteVersion[0] === localVersion[0]) {
const successObj = {
'msg': 'success',
'result': 'latest'
};
res.end(JSON.stringify(successObj));
} else {
const successObj = {
'msg': 'success',
'result': 'update',
'version': {
'local': localVersion[0],
'remote': remoteVersion[0],
}
};
res.end(JSON.stringify(successObj));
}
} else {
res.end({
'err': 'error getting update'
});
}
});
});
/*
* unpack zip
* type:
* params:
*/
shepherd.get('/unpack', function(req, res, next) {
const dlLocation = path.join(__dirname, '../');
var zip = new AdmZip(dlLocation + 'patch.zip');
zip.extractAllTo(/*target path*/dlLocation + '/patch/unpack', /*overwrite*/true);
const successObj = {
'msg': 'success',
'result': 'unpack started'
};
res.end(JSON.stringify(successObj));
});
shepherd.get('/coinslist', function(req, res, next) {
if (fs.existsSync(`${iguanaDir}/shepherd/coinslist.json`)) {
fs.readFile(`${iguanaDir}/shepherd/coinslist.json`, 'utf8', function (err, data) {
@ -273,17 +663,33 @@ shepherd.post('/coinslist', function(req, res, next) {
});
// TODO: check if komodod is running
shepherd.quitKomodod = function(chain) {
shepherd.quitKomodod = function() {
// if komodod is under heavy load it may not respond to cli stop the first time
// 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}`);
let coindExitInterval = {};
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
for (let key in coindInstanceRegistry) {
const chain = key !== 'komodod' ? key : null;
coindExitInterval[key] = setInterval(function() {
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}`);
if (stdout.indexOf('EOF reached') > -1 ||
stderr.indexOf('EOF reached') > -1 ||
stdout.indexOf('connect to server: unknown (code -1)') > -1 ||
stderr.indexOf('connect to server: unknown (code -1)') > -1) {
clearInterval(coindExitInterval[key]);
}
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
}, 100);
}
}
shepherd.getConf = function(chain) {
@ -331,7 +737,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'
@ -427,15 +833,30 @@ shepherd.post('/appconf', function(req, res, next) {
} else {
shepherd.saveLocalAppConf(req.body.payload);
const errorObj = {
const successObj = {
'msg': 'success',
'result': 'config saved'
};
res.end(JSON.stringify(errorObj));
res.end(JSON.stringify(successObj));
}
});
/*
* type: POST
* params: none
*/
shepherd.post('/appconf/reset', function(req, res, next) {
shepherd.saveLocalAppConf(shepherd.defaultAppConfig);
const successObj = {
'msg': 'success',
'result': 'config saved'
};
res.end(JSON.stringify(successObj));
});
shepherd.saveLocalAppConf = function(appSettings) {
let appConfFileName = `${iguanaDir}/config.json`;
@ -489,7 +910,7 @@ shepherd.saveLocalAppConf = function(appSettings) {
shepherd.loadLocalConfig = function() {
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');
@ -509,7 +930,7 @@ shepherd.loadLocalConfig = function() {
if (localAppConfig) {
const compareConfigs = compareJSON(shepherd.appConfig, JSON.parse(localAppConfig));
if (Object.keys(compareConfigs).length) {
const newConfig = Object.assign(JSON.parse(localAppConfig), compareConfigs);
@ -767,13 +1188,29 @@ shepherd.post('/forks', function(req, res, next) {
args: [`-port=${_port}`],
cwd: iguanaDir //set correct iguana directory
}, function(err, apps) {
iguanaInstanceRegistry[_port] = {
'mode': mode,
'coin': coin,
'pid': apps[0].process && apps[0].process.pid,
'pmid': apps[0].pm2_env.pm_id
};
cache.setVar('iguanaInstances', iguanaInstanceRegistry);
if (apps && apps[0] && apps[0].process && apps[0].process.pid) {
iguanaInstanceRegistry[_port] = {
'mode': mode,
'coin': coin,
'pid': apps[0].process && apps[0].process.pid,
'pmid': apps[0].pm2_env.pm_id
};
cache.setVar('iguanaInstances', iguanaInstanceRegistry);
const successObj = {
'msg': 'success',
'result': _port
};
res.end(JSON.stringify(successObj));
} else {
const errorObj = {
'msg': 'success',
'error': 'iguana start error'
};
res.end(JSON.stringify(errorObj));
}
// get sync only forks info
if (syncOnlyInstanceInterval === -1) {
@ -785,24 +1222,100 @@ shepherd.post('/forks', function(req, res, next) {
}, 20000);
}
const successObj = {
'msg': 'success',
'result': _port
};
res.end(JSON.stringify(successObj));
pm2.disconnect(); // Disconnect from PM2
if (err) {
throw err;
shepherd.writeLog(`iguana fork error: ${err}`);
console.log(`iguana fork error: ${err}`);
throw err;
}
});
});
});
});
/*
* type: GET
*
*/
shepherd.get('/InstantDEX/allcoins', function(req, res, next) {
// TODO: if only native return obj
// else query main iguana instance and return combined response
// http://localhost:7778/api/InstantDEX/allcoins?userpass=tmpIgRPCUser@1234
let successObj;
let nativeCoindList = [];
for (let key in coindInstanceRegistry) {
nativeCoindList.push(key === 'komodod' ? 'KMD' : key);
}
if (Object.keys(iguanaInstanceRegistry).length) {
// call to iguana
request({
url: `http://localhost:${shepherd.appConfig.iguanaCorePort}/api/InstantDEX/allcoins?userpass=${req.query.userpass}`,
method: 'GET'
}, function (error, response, body) {
if (response &&
response.statusCode &&
response.statusCode === 200) {
const _body = JSON.parse(body);
_body.native = nativeCoindList;
console.log(_body);
} else {
console.log('main iguana instance is not ready yet');
}
res.send(body);
});
} else {
successObj = {
'native': nativeCoindList,
'basilisk': [],
'full': []
};
res.end(JSON.stringify(successObj));
}
});
/*
* type: GET
*
*/
shepherd.get('/SuperNET/activehandle', function(req, res, next) {
// TODO: if only native return obj
// else query main iguana instance and return combined response
// http://localhost:7778/api/SuperNET/activehandle?userpass=tmpIgRPCUser@1234
let successObj;
if (Object.keys(iguanaInstanceRegistry).length) {
// call to iguana
request({
url: `http://localhost:${shepherd.appConfig.iguanaCorePort}/api/SuperNET/activehandle?userpass=${req.query.userpass}`,
method: 'GET'
}, function (error, response, body) {
if (response &&
response.statusCode &&
response.statusCode === 200) {
console.log(body);
} else {
console.log('main iguana instance is not ready yet');
}
res.send(body);
});
} else {
successObj = {
'pubkey': 'nativeonly',
'result': 'success',
'handle': '',
'status': Object.keys(coindInstanceRegistry).length ? 'unlocked' : 'locked',
'duration': 2507830
};
res.end(JSON.stringify(successObj));
}
});
/*
* type: GET
* params: pubkey
@ -863,9 +1376,10 @@ shepherd.get('/mock', function(req, res, next) {
* params: herd, lastLines
*/
shepherd.post('/debuglog', function(req, res) {
let _herd = req.body.herdname,
_lastNLines = req.body.lastLines,
_location;
let _herd = req.body.herdname;
let _ac = req.body.ac;
let _lastNLines = req.body.lastLines;
let _location;
if (_herd === 'iguana') {
_location = iguanaDir;
@ -873,22 +1387,26 @@ shepherd.post('/debuglog', function(req, res) {
_location = komodoDir;
}
if (_ac) {
_location = `${komodoDir}/${_ac}`;
}
shepherd.readDebugLog(`${_location}/debug.log`, _lastNLines)
.then(function(result) {
const _obj = {
'msg': 'success',
'result': result
};
.then(function(result) {
const _obj = {
'msg': 'success',
'result': result
};
res.end(JSON.stringify(_obj));
}, function(result) {
const _obj = {
'msg': 'error',
'result': result
};
res.end(JSON.stringify(_obj));
}, function(result) {
const _obj = {
'msg': 'error',
'result': result
};
res.end(JSON.stringify(_obj));
});
res.end(JSON.stringify(_obj));
});
});
/*
@ -1179,7 +1697,7 @@ shepherd.readDebugLog = function(fileLocation, lastNLines) {
const lines = data.trim().split('\n');
const lastLine = lines.slice(lines.length - lastNLines, lines.length).join('\n');
resolve(lastLine);
});
}
@ -1262,17 +1780,19 @@ function herder(flock, data) {
pm2.disconnect(); // Disconnect from PM2
if (err) {
throw err;
shepherd.writeLog(`iguana core port ${shepherd.appConfig.iguanaCorePort}`);
console.log(`iguana fork error: ${err}`);
throw err;
}
});
});
}
// TODO: notify gui that reindex/rescan param is used to reflect on the screen
// asset chain debug.log unlink
if (flock === 'komodod') {
let kmdDebugLogLocation = (data.ac_name !== 'komodod' ? komodoDir + '/' + data.ac_name : komodoDir) + '/debug.log';
console.log('komodod flock selected...');
console.log(`selected data: ${data}`);
shepherd.writeLog('komodod flock selected...');
@ -1285,9 +1805,13 @@ function herder(flock, data) {
console.log(`error accessing ${kmdDebugLogLocation}`);
shepherd.writeLog(`error accessing ${kmdDebugLogLocation}`);
} else {
console.log(`truncate ${kmdDebugLogLocation}`);
shepherd.writeLog(`truncate ${kmdDebugLogLocation}`);
fs.unlink(kmdDebugLogLocation);
try {
fs.unlink(kmdDebugLogLocation);
console.log(`truncate ${kmdDebugLogLocation}`);
shepherd.writeLog(`truncate ${kmdDebugLogLocation}`);
} catch (e) {
console.log('cant unlink debug.log');
}
}
});
} catch(e) {
@ -1304,59 +1828,50 @@ function herder(flock, data) {
// Status is 'open' if currently in use or 'closed' if available
if (status === 'closed') {
// start komodod via exec
if (data.ac_name === 'komodod') {
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(' ')}${_customParam}`, {
maxBuffer: 1024 * 10000 // 10 mb
}, function(error, stdout, stderr) {
// console.log('stdout: ' + stdout);
// console.log('stderr: ' + stderr);
shepherd.writeLog(`stdout: ${stdout}`);
shepherd.writeLog(`stderr: ${stderr}`);
const _customParamDict = {
'silent': '&',
'reindex': '-reindex',
'change': '-pubkey=',
'datadir': '-datadir=',
'rescan': '-rescan'
};
let _customParam = '';
if (data.ac_custom_param === 'silent' ||
data.ac_custom_param === 'reindex' ||
data.ac_custom_param === 'rescan') {
_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}`;
}
if (error !== null) {
console.log(`exec error: ${error}`)
shepherd.writeLog(`exec error: ${error}`);
console.log(`exec ${komododBin} ${data.ac_options.join(' ')}${_customParam}`);
shepherd.writeLog(`exec ${komododBin} ${data.ac_options.join(' ')}${_customParam}`);
const isChain = data.ac_name.match(/^[A-Z]*$/);
const coindACParam = isChain ? ` -ac_name=${data.ac_name} ` : '';
console.log('daemon param ' + data.ac_custom_param);
coindInstanceRegistry[data.ac_name] = true;
exec(`${komododBin} ${coindACParam}${data.ac_options.join(' ')}${_customParam}`, {
maxBuffer: 1024 * 10000 // 10 mb
}, function(error, stdout, stderr) {
shepherd.writeLog(`stdout: ${stdout}`);
shepherd.writeLog(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
shepherd.writeLog(`exec error: ${error}`);
if (error.toString().indexOf('using -reindex') > -1) {
cache.io.emit('service', {
'komodod': {
'error': 'run -reindex'
}
});
}
});
} else {
pm2.connect(true, function(err) { // start up pm2 god
if (err) {
console.error(err);
process.exit(2);
}
pm2.start({
script: komododBin, // path to binary
name: data.ac_name, // REVS, USD, EUR etc.
exec_mode : 'fork',
cwd: komodoDir,
args: data.ac_options
}, function(err, apps) {
shepherd.writeLog(`komodod fork started ${data.ac_name} ${JSON.stringify(data.ac_options)}`);
pm2.disconnect(); // Disconnect from PM2
if (err)
throw err;
});
});
}
}
});
} else {
console.log(`port ${_port} (${data.ac_name}) is already in use`);
shepherd.writeLog(`port ${_port} (${data.ac_name}) is already in use`);
@ -1385,7 +1900,7 @@ function herder(flock, data) {
pm2.start({
script: zcashdBin, // path to binary
name: data.ac_name, // REVS, USD, EUR etc.
exec_mode : 'fork',
exec_mode: 'fork',
cwd: zcashDir,
args: data.ac_options
}, function(err, apps) {
@ -1397,30 +1912,6 @@ function herder(flock, data) {
});
});
}
// deprecated, to be removed
if (flock === 'corsproxy') {
console.log('corsproxy flock selected...');
console.log(`selected data: ${data}`);
pm2.connect(true,function(err) { //start up pm2 god
if (err) {
console.error(err);
process.exit(2);
}
pm2.start({
script: CorsProxyBin, // path to binary
name: 'CORSPROXY',
exec_mode : 'fork',
cwd: iguanaDir
}, function(err, apps) {
pm2.disconnect(); // Disconnect from PM2
if (err)
throw err;
});
});
}
}
function slayer(flock) {
@ -1493,14 +1984,14 @@ function setConf(flock) {
switch (flock) {
case 'komodod':
DaemonConfPath = `${komodoDir}/komodo.conf`;
if (os.platform() === 'win32') {
DaemonConfPath = path.normalize(DaemonConfPath);
}
break;
case 'zcashd':
DaemonConfPath = `${ZcashDir}/zcash.conf`;
if (os.platform() === 'win32') {
DaemonConfPath = path.normalize(DaemonConfPath);
}
@ -1550,11 +2041,11 @@ function setConf(flock) {
const RemoveLines = function() {
return new Promise(function(resolve, reject) {
const result = 'RemoveLines is done'
const result = 'RemoveLines is done';
fs.readFile(DaemonConfPath, 'utf8', function(err, data) {
if (err) {
shepherd.writeLog(`setconf error '${err}`);
shepherd.writeLog(`setconf error ${err}`);
return console.log(err);
}
@ -1777,7 +2268,7 @@ function formatBytes(bytes, decimals) {
return '0 Bytes';
const k = 1000,
dm = decimals + 1 || 3,
dm = (decimals + 1) || 3,
sizes = [
'Bytes',
'KB',

3
version

@ -1,2 +1,3 @@
version=0.2.0.1
version=0.2.0.21a
type=e-beta
minversion=0.2.0.2
Loading…
Cancel
Save