From 684afdc398f9a6525a81827285a70733141e070d Mon Sep 17 00:00:00 2001 From: pbca26 Date: Thu, 29 Mar 2018 16:22:04 +0300 Subject: [PATCH] cleanup --- routes/shepherd/addCoinShortcuts.js | 15 ++++--- routes/shepherd/binsUtils.js | 12 ++++-- routes/shepherd/coindWalletKeys.js | 11 +++-- routes/shepherd/coinsList.js | 8 ++-- routes/shepherd/confMaxconnections.js | 5 ++- routes/shepherd/config.js | 21 ++++++---- routes/shepherd/daemonControl.js | 16 +++++--- routes/shepherd/dashboardUpdate.js | 5 ++- routes/shepherd/debugLog.js | 12 ++++-- routes/shepherd/downloadBins.js | 19 +++++---- routes/shepherd/downloadPatch.js | 28 ++++++++----- routes/shepherd/downloadUtil.js | 7 +++- routes/shepherd/downloadZcparams.js | 16 +++++--- routes/shepherd/elections.js | 47 +++++++++++++++++----- routes/shepherd/electrum/balance.js | 6 ++- routes/shepherd/electrum/block.js | 6 ++- routes/shepherd/electrum/createtx-multi.js | 15 ++++--- routes/shepherd/electrum/createtx-split.js | 5 ++- routes/shepherd/electrum/createtx.js | 16 ++++---- routes/shepherd/electrum/insight.js | 5 ++- routes/shepherd/electrum/listunspent.js | 27 +++++++++---- routes/shepherd/electrum/merkle.js | 21 ++++++---- routes/shepherd/electrum/transactions.js | 26 +++++++----- routes/shepherd/init.js | 2 +- routes/shepherd/log.js | 17 ++++---- routes/shepherd/quitDaemon.js | 1 + routes/shepherd/rpc.js | 11 +++-- 27 files changed, 247 insertions(+), 133 deletions(-) diff --git a/routes/shepherd/addCoinShortcuts.js b/routes/shepherd/addCoinShortcuts.js index 6397de901..79d2249a5 100644 --- a/routes/shepherd/addCoinShortcuts.js +++ b/routes/shepherd/addCoinShortcuts.js @@ -1,4 +1,7 @@ const electrumServers = require('../electrumjs/electrumServers'); +const request = require('request'); + +// TODO: refactor module.exports = (shepherd) => { shepherd.startSPV = (coin) => { @@ -44,7 +47,7 @@ module.exports = (shepherd) => { }), }; - shepherd.request(options, (error, response, body) => { + request(options, (error, response, body) => { if (response && response.statusCode && response.statusCode === 200) { @@ -78,7 +81,7 @@ module.exports = (shepherd) => { }), }; - shepherd.request(options, (error, response, body) => { + request(options, (error, response, body) => { if (response && response.statusCode && response.statusCode === 200) { @@ -112,7 +115,7 @@ module.exports = (shepherd) => { }), }; - shepherd.request(options, (error, response, body) => { + request(options, (error, response, body) => { if (response && response.statusCode && response.statusCode === 200) { @@ -146,7 +149,7 @@ module.exports = (shepherd) => { }), }; - shepherd.request(options, (error, response, body) => { + request(options, (error, response, body) => { if (response && response.statusCode && response.statusCode === 200) { @@ -180,7 +183,7 @@ module.exports = (shepherd) => { }), }; - shepherd.request(options, (error, response, body) => { + request(options, (error, response, body) => { if (response && response.statusCode && response.statusCode === 200) { @@ -231,7 +234,7 @@ module.exports = (shepherd) => { }), }; - shepherd.request(options, (error, response, body) => { + request(options, (error, response, body) => { if (response && response.statusCode && response.statusCode === 200) { diff --git a/routes/shepherd/binsUtils.js b/routes/shepherd/binsUtils.js index c4a7cbefb..32d4a0754 100644 --- a/routes/shepherd/binsUtils.js +++ b/routes/shepherd/binsUtils.js @@ -1,7 +1,11 @@ +const os = require('os'); +const fsnode = require('fs'); +const _fs = require('graceful-fs'); + module.exports = (shepherd) => { // osx and linux shepherd.binFixRights = () => { - const osPlatform = shepherd.os.platform(); + const osPlatform = os.platform(); const _bins = [ shepherd.komododBin, shepherd.komodocliBin @@ -10,11 +14,11 @@ module.exports = (shepherd) => { if (osPlatform === 'darwin' || osPlatform === 'linux') { for (let i = 0; i < _bins.length; i++) { - shepherd._fs.stat(_bins[i], (err, stat) => { + _fs.stat(_bins[i], (err, stat) => { if (!err) { if (parseInt(stat.mode.toString(8), 10) !== 100775) { shepherd.log(`${_bins[i]} fix permissions`); - shepherd.fsnode.chmodSync(_bins[i], '0775'); + fsnode.chmodSync(_bins[i], '0775'); } } else { shepherd.log(`error: ${_bins[i]} not found`); @@ -26,8 +30,8 @@ module.exports = (shepherd) => { shepherd.killRogueProcess = (processName) => { // kill rogue process copies on start + const osPlatform = os.platform(); let processGrep; - const osPlatform = shepherd.os.platform(); switch (osPlatform) { case 'darwin': diff --git a/routes/shepherd/coindWalletKeys.js b/routes/shepherd/coindWalletKeys.js index e8c1d3b3e..b3c7b98cf 100644 --- a/routes/shepherd/coindWalletKeys.js +++ b/routes/shepherd/coindWalletKeys.js @@ -1,3 +1,8 @@ +const fs = require('fs-extra'); +const _fs = require('graceful-fs'); +const wif = require('wif'); +const bitcoinJS = require('bitcoinjs-lib'); + module.exports = (shepherd) => { /* * type: GET @@ -5,8 +10,6 @@ module.exports = (shepherd) => { */ shepherd.get('/coindwalletkeys', (req, res, next) => { if (shepherd.checkToken(req.query.token)) { - const wif = require('wif'); - const fs = require('fs'); const chain = req.query.chain; // ref: https://gist.github.com/kendricktan/1e62495150ad236b38616d733aac4eb9 @@ -14,7 +17,7 @@ module.exports = (shepherd) => { _walletDatLocation = chain === 'CHIPS' ? `${shepherd.chipsDir}/wallet.dat` : _walletDatLocation; try { - shepherd._fs.access(_walletDatLocation, shepherd.fs.constants.R_OK, (err) => { + _fs.access(_walletDatLocation, shepherd.fs.constants.R_OK, (err) => { if (err) { shepherd.log(`error reading ${_walletDatLocation}`); successObj = { @@ -60,7 +63,7 @@ module.exports = (shepherd) => { const keyObj = wif.decode(key); const wifKey = wif.encode(keyObj); - const keyPair = shepherd.bitcoinJS.ECPair.fromWIF(wifKey, shepherd.electrumJSNetworks.komodo); + const keyPair = bitcoinJS.ECPair.fromWIF(wifKey, shepherd.electrumJSNetworks.komodo); const _keyPair = { priv: keyPair.toWIF(), pub: keyPair.getAddress(), diff --git a/routes/shepherd/coinsList.js b/routes/shepherd/coinsList.js index de4f6e32f..40dbac7f7 100644 --- a/routes/shepherd/coinsList.js +++ b/routes/shepherd/coinsList.js @@ -1,3 +1,5 @@ +const fs = require('fs-extra'); + module.exports = (shepherd) => { /* * type: GET @@ -5,8 +7,8 @@ module.exports = (shepherd) => { */ shepherd.get('/coinslist', (req, res, next) => { if (shepherd.checkToken(req.query.token)) { - if (shepherd.fs.existsSync(`${shepherd.agamaDir}/shepherd/coinslist.json`)) { - shepherd.fs.readFile(`${shepherd.agamaDir}/shepherd/coinslist.json`, 'utf8', (err, data) => { + if (fs.existsSync(`${shepherd.agamaDir}/shepherd/coinslist.json`)) { + fs.readFile(`${shepherd.agamaDir}/shepherd/coinslist.json`, 'utf8', (err, data) => { if (err) { const errorObj = { msg: 'error', @@ -57,7 +59,7 @@ module.exports = (shepherd) => { res.end(JSON.stringify(errorObj)); } else { - shepherd.fs.writeFile(`${shepherd.agamaDir}/shepherd/coinslist.json`, JSON.stringify(_payload), (err) => { + fs.writeFile(`${shepherd.agamaDir}/shepherd/coinslist.json`, JSON.stringify(_payload), (err) => { if (err) { const errorObj = { msg: 'error', diff --git a/routes/shepherd/confMaxconnections.js b/routes/shepherd/confMaxconnections.js index ebf0f0ab7..7320399af 100644 --- a/routes/shepherd/confMaxconnections.js +++ b/routes/shepherd/confMaxconnections.js @@ -1,8 +1,9 @@ const fs = require('fs-extra'); +const Promise = require('bluebird'); module.exports = (shepherd) => { shepherd.getMaxconKMDConf = () => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { fs.readFile(`${shepherd.komodoDir}/komodo.conf`, 'utf8', (err, data) => { if (err) { shepherd.log('kmd conf maxconnections param read failed'); @@ -23,7 +24,7 @@ module.exports = (shepherd) => { } shepherd.setMaxconKMDConf = (limit) => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { fs.readFile(`${shepherd.komodoDir}/komodo.conf`, 'utf8', (err, data) => { const _maxconVal = limit ? 1 : 10; diff --git a/routes/shepherd/config.js b/routes/shepherd/config.js index 30629d7bc..9aa2c2995 100644 --- a/routes/shepherd/config.js +++ b/routes/shepherd/config.js @@ -1,7 +1,12 @@ +const fs = require('fs-extra'); +const _fs = require('graceful-fs'); +const fsnode = require('fs'); +const Promise = require('bluebird'); + module.exports = (shepherd) => { shepherd.loadLocalConfig = () => { - if (shepherd.fs.existsSync(`${shepherd.agamaDir}/config.json`)) { - let localAppConfig = shepherd.fs.readFileSync(`${shepherd.agamaDir}/config.json`, 'utf8'); + if (fs.existsSync(`${shepherd.agamaDir}/config.json`)) { + let localAppConfig = fs.readFileSync(`${shepherd.agamaDir}/config.json`, 'utf8'); shepherd.log('app config set from local file'); shepherd.writeLog('app config set from local file'); @@ -53,14 +58,14 @@ module.exports = (shepherd) => { shepherd.saveLocalAppConf = (appSettings) => { let appConfFileName = `${shepherd.agamaDir}/config.json`; - shepherd._fs.access(shepherd.agamaDir, shepherd.fs.constants.R_OK, (err) => { + _fs.access(shepherd.agamaDir, shepherd.fs.constants.R_OK, (err) => { if (!err) { const FixFilePermissions = () => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { const result = 'config.json file permissions updated to Read/Write'; - shepherd.fsnode.chmodSync(appConfFileName, '0666'); + fsnode.chmodSync(appConfFileName, '0666'); setTimeout(() => { shepherd.log(result); @@ -71,10 +76,10 @@ module.exports = (shepherd) => { } const FsWrite = () => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { const result = 'config.json write file is done'; - shepherd.fs.writeFile(appConfFileName, + fs.writeFile(appConfFileName, JSON.stringify(appSettings) .replace(/,/g, ',\n') // format json in human readable form .replace(/":/g, '": ') @@ -84,7 +89,7 @@ module.exports = (shepherd) => { return shepherd.log(err); }); - shepherd.fsnode.chmodSync(appConfFileName, '0666'); + fsnode.chmodSync(appConfFileName, '0666'); setTimeout(() => { shepherd.log(result); shepherd.log(`app conf.json file is created successfully at: ${shepherd.agamaDir}`); diff --git a/routes/shepherd/daemonControl.js b/routes/shepherd/daemonControl.js index 67eade48e..bf9d71939 100644 --- a/routes/shepherd/daemonControl.js +++ b/routes/shepherd/daemonControl.js @@ -58,12 +58,12 @@ module.exports = (shepherd) => { } break; case 'coind': - DaemonConfPath = _platform === 'win32' ? shepherd.path.normalize(`${shepherd.coindRootDir}/${coind.toLowerCase()}`) : `${shepherd.coindRootDir}/${coind.toLowerCase()}`; + DaemonConfPath = _platform === 'win32' ? path.normalize(`${shepherd.coindRootDir}/${coind.toLowerCase()}`) : `${shepherd.coindRootDir}/${coind.toLowerCase()}`; break; default: DaemonConfPath = `${shepherd.komodoDir}/${flock}`; if (_platform === 'win32') { - DaemonConfPath = shepherd.path.normalize(DaemonConfPath); + DaemonConfPath = path.normalize(DaemonConfPath); } } @@ -230,7 +230,11 @@ module.exports = (shepherd) => { let spawnErr = fs.openSync(_daemonLogName, 'a'); spawn(shepherd.komododBin, _arg, { - stdio: ['ignore', spawnOut, spawnErr], + stdio: [ + 'ignore', + spawnOut, + spawnErr + ], detached: true, }).unref(); } else { @@ -439,7 +443,7 @@ module.exports = (shepherd) => { fs.unlink(coindDebugLogLocation); } }); - } catch(e) { + } catch (e) { shepherd.log(`coind ${coind} debug.log access err: ${e}`); shepherd.writeLog(`coind ${coind} debug.log access err: ${e}`); } @@ -475,7 +479,7 @@ module.exports = (shepherd) => { shepherd.writeLog(`port ${_port} (${coind}) is already in use`); } }); - } catch(e) { + } catch (e) { shepherd.log(`failed to start ${coind} err: ${e}`); shepherd.writeLog(`failed to start ${coind} err: ${e}`); } @@ -609,7 +613,7 @@ module.exports = (shepherd) => { shepherd.log('rpcuser: OK'); shepherd.writeLog('rpcuser: OK'); } else { - const randomstring = shepherd.md5((Math.random() * Math.random() * 999).toString()); + const randomstring = md5((Math.random() * Math.random() * 999).toString()); shepherd.log('rpcuser: NOT FOUND'); shepherd.writeLog('rpcuser: NOT FOUND'); diff --git a/routes/shepherd/dashboardUpdate.js b/routes/shepherd/dashboardUpdate.js index 2cca1f6f9..8223bee20 100644 --- a/routes/shepherd/dashboardUpdate.js +++ b/routes/shepherd/dashboardUpdate.js @@ -1,4 +1,5 @@ const Promise = require('bluebird'); +const request = require('request'); module.exports = (shepherd) => { /* @@ -24,7 +25,7 @@ module.exports = (shepherd) => { _promiseStack = [ 'getinfo', 'listtransactions', - 'getbalance', + 'getbalance' ]; } else { _returnObj = { @@ -272,7 +273,7 @@ module.exports = (shepherd) => { timeout: 120000, }; - shepherd.request(options, (error, response, body) => { + request(options, (error, response, body) => { if (response && response.statusCode && response.statusCode === 200) { diff --git a/routes/shepherd/debugLog.js b/routes/shepherd/debugLog.js index 9970e8ba5..9658f8154 100644 --- a/routes/shepherd/debugLog.js +++ b/routes/shepherd/debugLog.js @@ -1,3 +1,7 @@ +const path = require('path'); +const _fs = require('graceful-fs'); +const Promise = require('bluebird'); + module.exports = (shepherd) => { /* * type: POST @@ -20,7 +24,7 @@ module.exports = (shepherd) => { if (shepherd.os.platform() === 'win32') { shepherd.komodoDir = shepherd.appConfig.dataDir.length ? shepherd.appConfig.dataDir : `${process.env.APPDATA}/Komodo`; - shepherd.komodoDir = shepherd.path.normalize(shepherd.komodoDir); + shepherd.komodoDir = path.normalize(shepherd.komodoDir); } if (_herd === 'komodo') { @@ -93,18 +97,18 @@ module.exports = (shepherd) => { }); shepherd.readDebugLog = (fileLocation, lastNLines) => { - return new shepherd.Promise( + return new Promise( (resolve, reject) => { if (lastNLines) { try { - shepherd._fs.access(fileLocation, shepherd.fs.constants.R_OK, (err) => { + _fs.access(fileLocation, shepherd.fs.constants.R_OK, (err) => { if (err) { shepherd.log(`error reading ${fileLocation}`); shepherd.writeLog(`error reading ${fileLocation}`); reject(`readDebugLog error: ${err}`); } else { shepherd.log(`reading ${fileLocation}`); - shepherd._fs.readFile(fileLocation, 'utf-8', (err, data) => { + _fs.readFile(fileLocation, 'utf-8', (err, data) => { if (err) { shepherd.writeLog(`readDebugLog err: ${err}`); shepherd.log(`readDebugLog err: ${err}`); diff --git a/routes/shepherd/downloadBins.js b/routes/shepherd/downloadBins.js index f4dcfe92c..7f7376ec2 100644 --- a/routes/shepherd/downloadBins.js +++ b/routes/shepherd/downloadBins.js @@ -1,3 +1,8 @@ +const path = require('path'); +const os = require('os'); +const fs = require('fs-extra'); +const remoteFileSize = require('remote-file-size'); + const remoteBinLocation = { win32: 'https://artifacts.supernet.org/latest/windows/', darwin: 'https://artifacts.supernet.org/latest/osx/', @@ -47,7 +52,7 @@ module.exports = (shepherd) => { // TODO: promises shepherd.get('/update/bins/check', (req, res, next) => { if (shepherd.checkToken(req.query.token)) { - const rootLocation = shepherd.path.join(__dirname, '../../'); + const rootLocation = path.join(__dirname, '../../'); const successObj = { msg: 'success', result: 'bins', @@ -55,7 +60,7 @@ module.exports = (shepherd) => { res.end(JSON.stringify(successObj)); - const _os = shepherd.os.platform(); + const _os = os.platform(); shepherd.log(`checking bins: ${_os}`); shepherd.io.emit('patch', { @@ -67,8 +72,8 @@ module.exports = (shepherd) => { }); // get list of bins/dlls that can be updated to the latest for (let i = 0; i < latestBins[_os].length; i++) { - shepherd.remoteFileSize(remoteBinLocation[_os] + latestBins[_os][i], (err, remoteBinSize) => { - const localBinSize = shepherd.fs.statSync(rootLocation + localBinLocation[_os] + latestBins[_os][i]).size; + remoteFileSize(remoteBinLocation[_os] + latestBins[_os][i], (err, remoteBinSize) => { + const localBinSize = fs.statSync(rootLocation + localBinLocation[_os] + latestBins[_os][i]).size; shepherd.log('remote url: ' + (remoteBinLocation[_os] + latestBins[_os][i]) + ' (' + remoteBinSize + ')'); shepherd.log('local file: ' + (rootLocation + localBinLocation[_os] + latestBins[_os][i]) + ' (' + localBinSize + ')'); @@ -110,8 +115,8 @@ module.exports = (shepherd) => { */ shepherd.get('/update/bins', (req, res, next) => { if (shepherd.checkToken(req.query.token)) { - const rootLocation = shepherd.path.join(__dirname, '../../'); - const _os = shepherd.os.platform(); + const rootLocation = path.join(__dirname, '../../'); + const _os = os.platform(); const successObj = { msg: 'success', result: { @@ -145,7 +150,7 @@ module.exports = (shepherd) => { }) .then(() => { // verify that remote file is matching to DL'ed file - const localBinSize = shepherd.fs.statSync(`${rootLocation}${localBinLocation[_os]}patch/${binsToUpdate[i].name}`).size; + const localBinSize = fs.statSync(`${rootLocation}${localBinLocation[_os]}patch/${binsToUpdate[i].name}`).size; shepherd.log('compare dl file size'); if (localBinSize === binsToUpdate[i].rSize) { diff --git a/routes/shepherd/downloadPatch.js b/routes/shepherd/downloadPatch.js index 58b3667b4..596cd28b9 100644 --- a/routes/shepherd/downloadPatch.js +++ b/routes/shepherd/downloadPatch.js @@ -1,3 +1,9 @@ +const path = require('path'); +const AdmZip = require('adm-zip'); +const remoteFileSize = require('remote-file-size'); +const fs = require('fs-extra'); +const request = require('request'); + module.exports = (shepherd) => { /* * DL app patch @@ -25,7 +31,7 @@ module.exports = (shepherd) => { }); shepherd.updateAgama = () => { - const rootLocation = shepherd.path.join(__dirname, '../../'); + const rootLocation = path.join(__dirname, '../../'); shepherd.downloadFile({ remoteFile: 'https://github.com/pbca26/dl-test/raw/master/patch.zip', @@ -50,18 +56,18 @@ module.exports = (shepherd) => { .then(() => { shepherd.remoteFileSize('https://github.com/pbca26/dl-test/raw/master/patch.zip', (err, remotePatchSize) => { // verify that remote file is matching to DL'ed file - const localPatchSize = shepherd.fs.statSync(`${rootLocation}patch.zip`).size; + const localPatchSize = fs.statSync(`${rootLocation}patch.zip`).size; shepherd.log('compare dl file size'); if (localPatchSize === remotePatchSize) { - const zip = new shepherd.AdmZip(`${rootLocation}patch.zip`); + const zip = new AdmZip(`${rootLocation}patch.zip`); shepherd.log('patch succesfully downloaded'); shepherd.log('extracting contents'); if (shepherd.appConfig.dev) { - if (!shepherd.fs.existsSync(`${rootLocation}/patch`)) { - shepherd.fs.mkdirSync(`${rootLocation}/patch`); + if (!fs.existsSync(`${rootLocation}/patch`)) { + fs.mkdirSync(`${rootLocation}/patch`); } } @@ -73,7 +79,7 @@ module.exports = (shepherd) => { status: 'done', }, }); - shepherd.fs.unlinkSync(`${rootLocation}patch.zip`); + fs.unlinkSync(`${rootLocation}patch.zip`); } else { shepherd.io.emit('patch', { msg: { @@ -95,18 +101,18 @@ module.exports = (shepherd) => { */ shepherd.get('/update/patch/check', (req, res, next) => { if (shepherd.checkToken(req.query.token)) { - const rootLocation = shepherd.path.join(__dirname, '../../'); + const rootLocation = path.join(__dirname, '../../'); const options = { url: 'https://github.com/pbca26/dl-test/raw/master/version', method: 'GET', }; - shepherd.request(options, (error, response, body) => { + request(options, (error, response, body) => { if (response && response.statusCode && response.statusCode === 200) { const remoteVersion = body.split('\n'); - const localVersionFile = shepherd.fs.readFileSync(`${rootLocation}version`, 'utf8'); + const localVersionFile = fs.readFileSync(`${rootLocation}version`, 'utf8'); let localVersion; if (localVersionFile.indexOf('\r\n') > -1) { @@ -157,8 +163,8 @@ module.exports = (shepherd) => { */ shepherd.get('/unpack', (req, res, next) => { if (shepherd.checkToken(req.query.token)) { - const dlLocation = shepherd.path.join(__dirname, '../../'); - const zip = new shepherd.AdmZip(`${dlLocation}patch.zip`); + const dlLocation = path.join(__dirname, '../../'); + const zip = new AdmZip(`${dlLocation}patch.zip`); zip.extractAllTo(/*target path*/ `${dlLocation}/patch/unpack`, /*overwrite*/true); const successObj = { diff --git a/routes/shepherd/downloadUtil.js b/routes/shepherd/downloadUtil.js index dfc4a964a..43a2760d9 100644 --- a/routes/shepherd/downloadUtil.js +++ b/routes/shepherd/downloadUtil.js @@ -1,9 +1,12 @@ +const Promise = require('bluebird'); +const fs = require('fs-extra'); + module.exports = (shepherd) => { /** * Promise based download file method */ shepherd.downloadFile = (configuration) => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { // Save variable to know progress let receivedBytes = 0; let totalBytes = 0; @@ -17,7 +20,7 @@ module.exports = (shepherd) => { }, }); - let out = shepherd.fs.createWriteStream(configuration.localFile); + let out = fs.createWriteStream(configuration.localFile); req.pipe(out); req.on('response', (data) => { diff --git a/routes/shepherd/downloadZcparams.js b/routes/shepherd/downloadZcparams.js index 2cc8f8f6f..4236952e5 100644 --- a/routes/shepherd/downloadZcparams.js +++ b/routes/shepherd/downloadZcparams.js @@ -1,3 +1,7 @@ +const fs = require('fs-extra'); +const _fs = require('graceful-fs'); +const Promise = require('bluebird'); + module.exports = (shepherd) => { shepherd.zcashParamsDownloadLinks = { 'agama.komodoplatform.com': { @@ -16,10 +20,10 @@ module.exports = (shepherd) => { shepherd.zcashParamsExist = () => { let _checkList = { - rootDir: shepherd._fs.existsSync(shepherd.zcashParamsDir), - provingKey: shepherd._fs.existsSync(`${shepherd.zcashParamsDir}/sprout-proving.key`), + rootDir: _fs.existsSync(shepherd.zcashParamsDir), + provingKey: _fs.existsSync(`${shepherd.zcashParamsDir}/sprout-proving.key`), provingKeySize: false, - verifyingKey: shepherd._fs.existsSync(`${shepherd.zcashParamsDir}/sprout-verifying.key`), + verifyingKey: _fs.existsSync(`${shepherd.zcashParamsDir}/sprout-verifying.key`), verifyingKeySize: false, errors: false, }; @@ -28,8 +32,8 @@ module.exports = (shepherd) => { _checkList.provingKey || _checkList.verifyingKey) { // verify each key size - const _provingKeySize = _checkList.provingKey ? shepherd.fs.lstatSync(`${shepherd.zcashParamsDir}/sprout-proving.key`) : 0; - const _verifyingKeySize = _checkList.verifyingKey ? shepherd.fs.lstatSync(`${shepherd.zcashParamsDir}/sprout-verifying.key`) : 0; + const _provingKeySize = _checkList.provingKey ? fs.lstatSync(`${shepherd.zcashParamsDir}/sprout-proving.key`) : 0; + const _verifyingKeySize = _checkList.verifyingKey ? fs.lstatSync(`${shepherd.zcashParamsDir}/sprout-verifying.key`) : 0; if (Number(_provingKeySize.size) === 910173851) { // bytes _checkList.provingKeySize = true; @@ -55,7 +59,7 @@ module.exports = (shepherd) => { } shepherd.zcashParamsExistPromise = () => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { const _verify = shepherd.zcashParamsExist(); resolve(_verify); }); diff --git a/routes/shepherd/elections.js b/routes/shepherd/elections.js index 8f65f7fae..ac27e1cc2 100644 --- a/routes/shepherd/elections.js +++ b/routes/shepherd/elections.js @@ -1,5 +1,6 @@ const bs58check = require('bs58check'); const bitcoin = require('bitcoinjs-lib'); +const Promise = require('bluebird'); module.exports = (shepherd) => { shepherd.elections = {}; @@ -111,11 +112,11 @@ module.exports = (shepherd) => { shepherd.electionsDecodeTx = (decodedTx, ecl, network, _network, transaction, blockInfo, address) => { let txInputs = []; - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { if (decodedTx && decodedTx.inputs) { - shepherd.Promise.all(decodedTx.inputs.map((_decodedInput, index) => { - return new shepherd.Promise((_resolve, _reject) => { + Promise.all(decodedTx.inputs.map((_decodedInput, index) => { + return new Promise((_resolve, _reject) => { if (_decodedInput.txid !== '0000000000000000000000000000000000000000000000000000000000000000') { ecl.blockchainTransactionGet(_decodedInput.txid) .then((rawInput) => { @@ -186,8 +187,8 @@ module.exports = (shepherd) => { shepherd.log(json.length, true); - shepherd.Promise.all(json.map((transaction, index) => { - return new shepherd.Promise((resolve, reject) => { + Promise.all(json.map((transaction, index) => { + return new Promise((resolve, reject) => { ecl.blockchainBlockGetHeader(transaction.height) .then((blockInfo) => { if (blockInfo && @@ -256,7 +257,8 @@ module.exports = (shepherd) => { if (type === 'candidate') { if (_region === 'ne2k18-na-1-eu-2-ae-3-sh-4') { - if (decodedTx.outputs[i].scriptPubKey.addresses[0] === _address && decodedTx.outputs[i].scriptPubKey.asm.indexOf('OP_RETURN') === -1) { + if (decodedTx.outputs[i].scriptPubKey.addresses[0] === _address && + decodedTx.outputs[i].scriptPubKey.asm.indexOf('OP_RETURN') === -1) { const _regionsLookup = [ 'ne2k18-na', 'ne2k18-eu', @@ -264,7 +266,15 @@ module.exports = (shepherd) => { 'ne2k18-sh' ]; - shepherd.electionsDecodeTx(decodedTx, ecl, network, _network, transaction, blockInfo, _address) + shepherd.electionsDecodeTx( + decodedTx, + ecl, + network, + _network, + transaction, + blockInfo, + _address + ) .then((res) => { shepherd.log(`i received ${decodedTx.outputs[i].value} from ${res.outputAddresses[0]} out ${i} region ${_regionsLookup[i]}`); _rawtx.push({ @@ -277,7 +287,15 @@ module.exports = (shepherd) => { }); } } else { - shepherd.electionsDecodeTx(decodedTx, ecl, network, _network, transaction, blockInfo, _address) + shepherd.electionsDecodeTx( + decodedTx, + ecl, + network, + _network, + transaction, + blockInfo, + _address + ) .then((res) => { if (decodedTx.outputs[i].scriptPubKey.addresses[0] === _address) { _candidate.amount = decodedTx.outputs[i].value; @@ -298,7 +316,15 @@ module.exports = (shepherd) => { } } else { shepherd.log('elections regular tx', true); - shepherd.electionsDecodeTx(decodedTx, ecl, network, _network, transaction, blockInfo, _address) + shepherd.electionsDecodeTx( + decodedTx, + ecl, + network, + _network, + transaction, + blockInfo, + _address + ) .then((_regularTx) => { if (_regularTx[0] && _regularTx[1]) { @@ -311,7 +337,8 @@ module.exports = (shepherd) => { hash: transaction['tx_hash'], }); } else { - if ((type === 'voter' && _regularTx.type !== 'received') && (type === 'candidate' && _regularTx.type !== 'sent')) { + if ((type === 'voter' && _regularTx.type !== 'received') && + (type === 'candidate' && _regularTx.type !== 'sent')) { _rawtx.push({ address: _regularTx.address || 'self', timestamp: _regularTx.timestamp, diff --git a/routes/shepherd/electrum/balance.js b/routes/shepherd/electrum/balance.js index 3d596b2e9..b580c5a91 100644 --- a/routes/shepherd/electrum/balance.js +++ b/routes/shepherd/electrum/balance.js @@ -1,3 +1,5 @@ +const Promise = require('bluebird'); + module.exports = (shepherd) => { shepherd.get('/electrum/getbalance', (req, res, next) => { if (shepherd.checkToken(req.query.token)) { @@ -35,8 +37,8 @@ module.exports = (shepherd) => { _utxo.length) { let interestTotal = 0; - shepherd.Promise.all(_utxo.map((_utxoItem, index) => { - return new shepherd.Promise((resolve, reject) => { + Promise.all(_utxo.map((_utxoItem, index) => { + return new Promise((resolve, reject) => { shepherd.getTransaction(_utxoItem['tx_hash'], network, ecl) .then((_rawtxJSON) => { shepherd.log('electrum gettransaction ==>', true); diff --git a/routes/shepherd/electrum/block.js b/routes/shepherd/electrum/block.js index 38e603d26..5ac9a3cab 100644 --- a/routes/shepherd/electrum/block.js +++ b/routes/shepherd/electrum/block.js @@ -1,3 +1,5 @@ +const Promise = require('bluebird'); + module.exports = (shepherd) => { shepherd.get('/electrum/getblockinfo', (req, res, next) => { if (shepherd.checkToken(req.query.token)) { @@ -21,7 +23,7 @@ module.exports = (shepherd) => { }); shepherd.electrumGetBlockInfo = (height, network) => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { const ecl = new shepherd.electrumJSCore(shepherd.electrumServers[network].port, shepherd.electrumServers[network].address, shepherd.electrumServers[network].proto); // tcp or tls ecl.connect(); @@ -58,7 +60,7 @@ module.exports = (shepherd) => { }); shepherd.electrumGetCurrentBlock = (network) => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { const ecl = new shepherd.electrumJSCore(shepherd.electrumServers[network].port, shepherd.electrumServers[network].address, shepherd.electrumServers[network].proto); // tcp or tls ecl.connect(); diff --git a/routes/shepherd/electrum/createtx-multi.js b/routes/shepherd/electrum/createtx-multi.js index 4bdc1b893..92b91ad24 100644 --- a/routes/shepherd/electrum/createtx-multi.js +++ b/routes/shepherd/electrum/createtx-multi.js @@ -1,6 +1,8 @@ +const bitcoinJS = require('bitcoinjs-lib'); const bitcoinJSForks = require('bitcoinforksjs-lib'); const bitcoinZcash = require('bitcoinjs-lib-zcash'); const bitcoinPos = require('bitcoinjs-lib-pos'); +const coinSelect = require('coinselect'); // not prod ready, only for voting! // needs a fix @@ -94,7 +96,7 @@ module.exports = (shepherd) => { // default coin selection algo blackjack with fallback to accumulative // make a first run, calc approx tx fee // if ins and outs are empty reduce max spend by txfee - const firstRun = shepherd.coinSelect(utxoListFormatted, targets, btcFee ? btcFee : 0); + const firstRun = coinSelect(utxoListFormatted, targets, btcFee ? btcFee : 0); let inputs = firstRun.inputs; let outputs = firstRun.outputs; @@ -117,7 +119,7 @@ module.exports = (shepherd) => { shepherd.log('coinselect adjusted targets =>', true); shepherd.log(targets, true); - const secondRun = shepherd.coinSelect(utxoListFormatted, targets, 0); + const secondRun = coinSelect(utxoListFormatted, targets, 0); inputs = secondRun.inputs; outputs = secondRun.outputs; fee = fee ? fee : secondRun.fee; @@ -427,7 +429,7 @@ module.exports = (shepherd) => { // single sig shepherd.buildSignedTxMulti = (sendTo, changeAddress, wif, network, utxo, changeValue, spendValue, opreturn) => { - let key = shepherd.isZcash(network) ? bitcoinZcash.ECPair.fromWIF(wif, shepherd.getNetworkData(network)) : shepherd.bitcoinJS.ECPair.fromWIF(wif, shepherd.getNetworkData(network)); + let key = shepherd.isZcash(network) ? bitcoinZcash.ECPair.fromWIF(wif, shepherd.getNetworkData(network)) : bitcoinJS.ECPair.fromWIF(wif, shepherd.getNetworkData(network)); let tx; if (shepherd.isZcash(network)) { @@ -435,7 +437,7 @@ module.exports = (shepherd) => { } else if (shepherd.isPos(network)) { tx = new bitcoinPos.TransactionBuilder(shepherd.getNetworkData(network)); } else { - tx = new shepherd.bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); + tx = new bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); } shepherd.log('buildSignedTx', true); @@ -466,10 +468,11 @@ module.exports = (shepherd) => { if (opreturn && opreturn.length) { for (let i = 0; i < opreturn.length; i++) { - shepherd.log(`opreturn ${i} ${opreturn[i]}`); const data = Buffer.from(opreturn[i], 'utf8'); - const dataScript = shepherd.bitcoinJS.script.nullData.output.encode(data); + const dataScript = bitcoinJS.script.nullData.output.encode(data); tx.addOutput(dataScript, 1000); + + shepherd.log(`opreturn ${i} ${opreturn[i]}`); } } diff --git a/routes/shepherd/electrum/createtx-split.js b/routes/shepherd/electrum/createtx-split.js index c161a6262..bce7cacac 100644 --- a/routes/shepherd/electrum/createtx-split.js +++ b/routes/shepherd/electrum/createtx-split.js @@ -1,3 +1,4 @@ +const bitcoinJS = require('bitcoinjs-lib'); const bitcoinJSForks = require('bitcoinforksjs-lib'); const bitcoinZcash = require('bitcoinjs-lib-zcash'); const bitcoinPos = require('bitcoinjs-lib-pos'); @@ -14,7 +15,7 @@ module.exports = (shepherd) => { const outputAddress = req.body.payload.outputAddress; const changeAddress = req.body.payload.changeAddress; - let key = shepherd.isZcash(network) ? bitcoinZcash.ECPair.fromWIF(wif, shepherd.getNetworkData(network)) : shepherd.bitcoinJS.ECPair.fromWIF(wif, shepherd.getNetworkData(network)); + let key = shepherd.isZcash(network) ? bitcoinZcash.ECPair.fromWIF(wif, shepherd.getNetworkData(network)) : bitcoinJS.ECPair.fromWIF(wif, shepherd.getNetworkData(network)); let tx; if (shepherd.isZcash(network)) { @@ -22,7 +23,7 @@ module.exports = (shepherd) => { } else if (shepherd.isPos(network)) { tx = new bitcoinPos.TransactionBuilder(shepherd.getNetworkData(network)); } else { - tx = new shepherd.bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); + tx = new bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); } shepherd.log('buildSignedTx', true); diff --git a/routes/shepherd/electrum/createtx.js b/routes/shepherd/electrum/createtx.js index 04b979522..e824d0f14 100644 --- a/routes/shepherd/electrum/createtx.js +++ b/routes/shepherd/electrum/createtx.js @@ -1,6 +1,8 @@ +const bitcoinJS = require('bitcoinjs-lib'); const bitcoinJSForks = require('bitcoinforksjs-lib'); const bitcoinZcash = require('bitcoinjs-lib-zcash'); const bitcoinPos = require('bitcoinjs-lib-pos'); +const coinSelect = require('coinselect'); module.exports = (shepherd) => { // unsigned tx @@ -9,11 +11,11 @@ module.exports = (shepherd) => { // TODO: finish unsigned for zcash, btc forks and pos coins if (network === 'btg') { - shepherd.log('enable btg', true); tx = new bitcoinJSForks.TransactionBuilder(shepherd.getNetworkData(network)); tx.enableBitcoinGold(true); + shepherd.log('enable btg', true); } else { - tx = new shepherd.bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); + tx = new bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); } shepherd.log('buildSignedTx', true); @@ -55,7 +57,7 @@ module.exports = (shepherd) => { // single sig shepherd.buildSignedTx = (sendTo, changeAddress, wif, network, utxo, changeValue, spendValue, opreturn) => { - let key = shepherd.isZcash(network) ? bitcoinZcash.ECPair.fromWIF(wif, shepherd.getNetworkData(network)) : shepherd.bitcoinJS.ECPair.fromWIF(wif, shepherd.getNetworkData(network)); + let key = shepherd.isZcash(network) ? bitcoinZcash.ECPair.fromWIF(wif, shepherd.getNetworkData(network)) : bitcoinJS.ECPair.fromWIF(wif, shepherd.getNetworkData(network)); let tx; if (shepherd.isZcash(network)) { @@ -63,7 +65,7 @@ module.exports = (shepherd) => { } else if (shepherd.isPos(network)) { tx = new bitcoinPos.TransactionBuilder(shepherd.getNetworkData(network)); } else { - tx = new shepherd.bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); + tx = new bitcoinJS.TransactionBuilder(shepherd.getNetworkData(network)); } shepherd.log('buildSignedTx', true); @@ -90,10 +92,10 @@ module.exports = (shepherd) => { } if (opreturn) { - console.log(`opreturn ${opreturn}`); const data = Buffer.from(opreturn, 'utf8'); const dataScript = shepherd.bitcoinJS.script.nullData.output.encode(data); tx.addOutput(dataScript, 1000); + console.log(`opreturn ${opreturn}`); } if (network === 'komodo' || @@ -279,7 +281,7 @@ module.exports = (shepherd) => { // default coin selection algo blackjack with fallback to accumulative // make a first run, calc approx tx fee // if ins and outs are empty reduce max spend by txfee - const firstRun = shepherd.coinSelect(utxoListFormatted, targets, btcFee ? btcFee : 0); + const firstRun = coinSelect(utxoListFormatted, targets, btcFee ? btcFee : 0); let inputs = firstRun.inputs; let outputs = firstRun.outputs; @@ -302,7 +304,7 @@ module.exports = (shepherd) => { shepherd.log('coinselect adjusted targets =>', true); shepherd.log(targets, true); - const secondRun = shepherd.coinSelect(utxoListFormatted, targets, 0); + const secondRun = coinSelect(utxoListFormatted, targets, 0); inputs = secondRun.inputs; outputs = secondRun.outputs; fee = fee ? fee : secondRun.fee; diff --git a/routes/shepherd/electrum/insight.js b/routes/shepherd/electrum/insight.js index b2d4d30bf..6dd93ad70 100644 --- a/routes/shepherd/electrum/insight.js +++ b/routes/shepherd/electrum/insight.js @@ -1,4 +1,5 @@ const request = require('request'); +const Promise = require('bluebird'); // abstraction layer to communicate with insight explorers @@ -55,7 +56,7 @@ module.exports = (shepherd) => { blockchainAddressGetBalance: (address) => { shepherd.log('insight blockchainAddressGetBalance', true); - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { let options = { url: `${shepherd.insightJSCoreActiveCoin.address}/${apiRoutes('utxo', address)}`, method: 'GET', @@ -97,7 +98,7 @@ module.exports = (shepherd) => { blockchainAddressListunspent: (address) => { shepherd.log('insight blockchainAddressListunspent', true); - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { let options = { url: `${shepherd.insightJSCoreActiveCoin.address}/${apiRoutes('utxo', address)}`, method: 'GET', diff --git a/routes/shepherd/electrum/listunspent.js b/routes/shepherd/electrum/listunspent.js index ace82936c..f0376d173 100644 --- a/routes/shepherd/electrum/listunspent.js +++ b/routes/shepherd/electrum/listunspent.js @@ -1,11 +1,14 @@ // TODO: watchonly spendable switch +const Promise = require('bluebird'); + module.exports = (shepherd) => { shepherd.listunspent = (ecl, address, network, full, verify) => { let _atLeastOneDecodeTxFailed = false; - if (full && !ecl.insight) { - return new shepherd.Promise((resolve, reject) => { + if (full && + !ecl.insight) { + return new Promise((resolve, reject) => { ecl.connect(); ecl.blockchainAddressListunspent(address) .then((_utxoJSON) => { @@ -29,12 +32,12 @@ module.exports = (shepherd) => { ecl.close(); resolve('no valid utxo'); } else { - shepherd.Promise.all(_utxo.map((_utxoItem, index) => { - return new shepherd.Promise((resolve, reject) => { + Promise.all(_utxo.map((_utxoItem, index) => { + return new Promise((resolve, reject) => { shepherd.getTransaction(_utxoItem['tx_hash'], network, ecl) .then((_rawtxJSON) => { shepherd.log('electrum gettransaction ==>', true); - shepherd.log(index + ' | ' + (_rawtxJSON.length - 1), true); + shepherd.log(`${index} | ${(_rawtxJSON.length - 1)}`, true); shepherd.log(_rawtxJSON, true); // decode tx @@ -72,7 +75,11 @@ module.exports = (shepherd) => { // merkle root verification against another electrum server if (verify) { - shepherd.verifyMerkleByCoin(shepherd.findCoinName(network), _utxoItem['tx_hash'], _utxoItem.height) + shepherd.verifyMerkleByCoin( + shepherd.findCoinName(network), + _utxoItem['tx_hash'], + _utxoItem.height + ) .then((verifyMerkleRes) => { if (verifyMerkleRes && verifyMerkleRes === shepherd.CONNECTION_ERROR_OR_INCOMPLETE_DATA) { @@ -99,7 +106,11 @@ module.exports = (shepherd) => { // merkle root verification against another electrum server if (verify) { - shepherd.verifyMerkleByCoin(shepherd.findCoinName(network), _utxoItem['tx_hash'], _utxoItem.height) + shepherd.verifyMerkleByCoin( + shepherd.findCoinName(network), + _utxoItem['tx_hash'], + _utxoItem.height + ) .then((verifyMerkleRes) => { if (verifyMerkleRes && verifyMerkleRes === shepherd.CONNECTION_ERROR_OR_INCOMPLETE_DATA) { @@ -141,7 +152,7 @@ module.exports = (shepherd) => { }); }); } else { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { ecl.connect(); ecl.blockchainAddressListunspent(address) .then((json) => { diff --git a/routes/shepherd/electrum/merkle.js b/routes/shepherd/electrum/merkle.js index 2385d6768..82a52c464 100644 --- a/routes/shepherd/electrum/merkle.js +++ b/routes/shepherd/electrum/merkle.js @@ -1,10 +1,13 @@ +const Promise = require('bluebird'); +const reverse = require('buffer-reverse'); +const crypto = require('crypto'); +const _sha256 = (data) => { + return crypto.createHash('sha256').update(data).digest(); +}; + module.exports = (shepherd) => { // get merkle root shepherd.getMerkleRoot = (txid, proof, pos) => { - const reverse = require('buffer-reverse'); - const _sha256 = (data) => { - return shepherd.crypto.createHash('sha256').update(data).digest(); - } let hash = txid; let serialized; @@ -46,7 +49,7 @@ module.exports = (shepherd) => { let ecl = new shepherd.electrumJSCore(_mainServer[1], _mainServer[0], _mainServer[2]); // tcp or tls - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { shepherd.log(`main server: ${mainServer}`, true); shepherd.log(`verification server: ${randomServer}`, true); @@ -106,7 +109,7 @@ module.exports = (shepherd) => { shepherd.log(shepherd.electrumCoins[coin].server, true); shepherd.log(shepherd.electrumCoins[coin].serverList, true); - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { if (_serverList !== 'none') { let _filteredServerList = []; @@ -134,7 +137,11 @@ module.exports = (shepherd) => { shepherd.get('/electrum/merkle/verify', (req, res, next) => { if (shepherd.checkToken(req.query.token)) { - shepherd.verifyMerkleByCoin(req.query.coin, req.query.txid, req.query.height) + const _coin = req.query.coin; + const _txid = req.query.txid; + const _height = req.query.height; + + shepherd.verifyMerkleByCoin(_coin, _txid, _height) .then((verifyMerkleRes) => { const successObj = { msg: 'success', diff --git a/routes/shepherd/electrum/transactions.js b/routes/shepherd/electrum/transactions.js index da7642514..47a44da0e 100644 --- a/routes/shepherd/electrum/transactions.js +++ b/routes/shepherd/electrum/transactions.js @@ -1,4 +1,5 @@ const async = require('async'); +const Promise = require('bluebird'); module.exports = (shepherd) => { shepherd.sortTransactions = (transactions, sortBy) => { @@ -16,7 +17,7 @@ module.exports = (shepherd) => { } shepherd.getTransaction = (txid, network, ecl) => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { if (!shepherd.electrumCache[network]) { shepherd.electrumCache[network] = {}; } @@ -40,7 +41,7 @@ module.exports = (shepherd) => { } shepherd.getBlockHeader = (height, network, ecl) => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { if (!shepherd.electrumCache[network]) { shepherd.electrumCache[network] = {}; } @@ -67,12 +68,15 @@ module.exports = (shepherd) => { if (shepherd.checkToken(req.query.token)) { const network = req.query.network || shepherd.findNetworkObj(req.query.coin); const ecl = shepherd.electrumServers[network].proto === 'insight' ? shepherd.insightJSCore(shepherd.electrumServers[network]) : new shepherd.electrumJSCore(shepherd.electrumServers[network].port, shepherd.electrumServers[network].address, shepherd.electrumServers[network].proto); // tcp or tls + const _address = req.query.address; + const _maxlength = req.query.maxlength; shepherd.log('electrum listtransactions ==>', true); - if (!req.query.full || ecl.insight) { + if (!req.query.full || + ecl.insight) { ecl.connect(); - ecl.blockchainAddressGetHistory(req.query.address) + ecl.blockchainAddressGetHistory(_address) .then((json) => { ecl.close(); shepherd.log(json, true); @@ -89,14 +93,14 @@ module.exports = (shepherd) => { } else { // !expensive call! // TODO: limit e.g. 1-10, 10-20 etc - const MAX_TX = req.query.maxlength || 10; + const MAX_TX = _maxlength || 10; ecl.connect(); ecl.blockchainNumblocksSubscribe() .then((currentHeight) => { if (currentHeight && Number(currentHeight) > 0) { - ecl.blockchainAddressGetHistory(req.query.address) + ecl.blockchainAddressGetHistory(_address) .then((json) => { if (json && json.length) { @@ -108,6 +112,7 @@ module.exports = (shepherd) => { shepherd.log(json.length, true); let index = 0; + // callback hell, use await? async.eachOfSeries(json, (transaction, ind, callback) => { shepherd.getBlockHeader(transaction.height, network, ecl) .then((blockInfo) => { @@ -130,11 +135,12 @@ module.exports = (shepherd) => { // shepherd.log(decodedTx.outputs, true); let index2 = 0; + if (decodedTx && decodedTx.inputs && decodedTx.inputs.length) { async.eachOfSeries(decodedTx.inputs, (_decodedInput, ind2, callback2) => { - function checkLoop() { + const checkLoop = () => { index2++; if (index2 === decodedTx.inputs.length) { @@ -149,7 +155,7 @@ module.exports = (shepherd) => { confirmations: Number(transaction.height) === 0 ? 0 : currentHeight - transaction.height, }; - const formattedTx = shepherd.parseTransactionAddresses(_parsedTx, req.query.address, network); + const formattedTx = shepherd.parseTransactionAddresses(_parsedTx, _address, network); if (formattedTx.type) { formattedTx.height = transaction.height; @@ -223,7 +229,7 @@ module.exports = (shepherd) => { confirmations: Number(transaction.height) === 0 ? 0 : currentHeight - transaction.height, }; - const formattedTx = shepherd.parseTransactionAddresses(_parsedTx, req.query.address, network); + const formattedTx = shepherd.parseTransactionAddresses(_parsedTx, _address, network); _rawtx.push(formattedTx); index++; @@ -251,7 +257,7 @@ module.exports = (shepherd) => { timestamp: 'cant get block info', confirmations: Number(transaction.height) === 0 ? 0 : currentHeight - transaction.height, }; - const formattedTx = shepherd.parseTransactionAddresses(_parsedTx, req.query.address, network); + const formattedTx = shepherd.parseTransactionAddresses(_parsedTx, _address, network); _rawtx.push(formattedTx); index++; diff --git a/routes/shepherd/init.js b/routes/shepherd/init.js index 1746c4010..f91909058 100644 --- a/routes/shepherd/init.js +++ b/routes/shepherd/init.js @@ -18,7 +18,7 @@ module.exports = (shepherd) => { fs.readdir(rootLocation, (err, items) => { for (let i = 0; i < items.length; i++) { if (items[i].substr(0, 3) === 'gen') { - console.log(items[i]); + shepherd.log(`remove items[i]`); fs.unlinkSync(rootLocation + items[i]); } } diff --git a/routes/shepherd/log.js b/routes/shepherd/log.js index 6ab2a9e7f..3a0944526 100644 --- a/routes/shepherd/log.js +++ b/routes/shepherd/log.js @@ -1,3 +1,6 @@ +const fs = require('fs-extra'); +const Promise = require('bluebird'); + module.exports = (shepherd) => { shepherd.log = (msg, isSpvOut) => { if (shepherd.appConfig.dev || @@ -23,14 +26,14 @@ module.exports = (shepherd) => { const timeFormatted = new Date(Date.now()).toLocaleString('en-US', { hour12: false }); if (shepherd.appConfig.debug) { - if (shepherd.fs.existsSync(`${logLocation}/agamalog.txt`)) { - shepherd.fs.appendFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, (err) => { + if (fs.existsSync(`${logLocation}/agamalog.txt`)) { + fs.appendFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, (err) => { if (err) { shepherd.log('error writing log file'); } }); } else { - shepherd.fs.writeFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, (err) => { + fs.writeFile(`${logLocation}/agamalog.txt`, `${timeFormatted} ${data}\r\n`, (err) => { if (err) { shepherd.log('error writing log file'); } @@ -58,7 +61,7 @@ module.exports = (shepherd) => { }); shepherd.getAppRuntimeLog = () => { - return new shepherd.Promise((resolve, reject) => { + return new Promise((resolve, reject) => { resolve(shepherd.appRuntimeLog); }); }; @@ -88,7 +91,7 @@ module.exports = (shepherd) => { }; } - shepherd.fs.writeFile(`${logLocation}/agamalog.json`, JSON.stringify(shepherd.guiLog), (err) => { + fs.writeFile(`${logLocation}/agamalog.json`, JSON.stringify(shepherd.guiLog), (err) => { if (err) { shepherd.writeLog('error writing gui log file'); } @@ -118,8 +121,8 @@ module.exports = (shepherd) => { if (shepherd.checkToken(req.query.token)) { const logExt = req.query.type === 'txt' ? 'txt' : 'json'; - if (shepherd.fs.existsSync(`${shepherd.agamaDir}/shepherd/agamalog.${logExt}`)) { - shepherd.fs.readFile(`${shepherd.agamaDir}/shepherd/agamalog.${logExt}`, 'utf8', (err, data) => { + if (fs.existsSync(`${shepherd.agamaDir}/shepherd/agamalog.${logExt}`)) { + fs.readFile(`${shepherd.agamaDir}/shepherd/agamalog.${logExt}`, 'utf8', (err, data) => { if (err) { const errorObj = { msg: 'error', diff --git a/routes/shepherd/quitDaemon.js b/routes/shepherd/quitDaemon.js index 15c90219a..45fa7b806 100644 --- a/routes/shepherd/quitDaemon.js +++ b/routes/shepherd/quitDaemon.js @@ -23,6 +23,7 @@ module.exports = (shepherd) => { const execCliStop = () => { let _arg = []; + if (chain && !shepherd.nativeCoindList[key.toLowerCase()] && key !== 'CHIPS') { _arg.push(`-ac_name=${chain}`); diff --git a/routes/shepherd/rpc.js b/routes/shepherd/rpc.js index 2e64bd9b4..d43f5c8b0 100644 --- a/routes/shepherd/rpc.js +++ b/routes/shepherd/rpc.js @@ -1,5 +1,8 @@ const fs = require('fs-extra'); const os = require('os'); +const exec = require('child_process').exec; +const execFile = require('child_process').execFile; +const request = require('request'); module.exports = (shepherd) => { shepherd.getConf = (chain) => { @@ -16,8 +19,8 @@ module.exports = (shepherd) => { } if (fs.existsSync(_confLocation)) { - let _port = shepherd.assetChainPorts[chain]; const _rpcConf = fs.readFileSync(_confLocation, 'utf8'); + let _port = shepherd.assetChainPorts[chain]; // any coind if (shepherd.nativeCoindList[chain.toLowerCase()]) { @@ -111,7 +114,7 @@ module.exports = (shepherd) => { _arg = `${_arg} -datadir=${shepherd.appConfig.dataDir + (_chain ? '/' + key : '')}`; } - shepherd.exec(`"${_coindCliBin}" ${_arg}`, (error, stdout, stderr) => { + exec(`"${_coindCliBin}" ${_arg}`, (error, stdout, stderr) => { //shepherd.log(`stdout: ${stdout}`); //shepherd.log(`stderr: ${stderr}`); @@ -265,7 +268,7 @@ module.exports = (shepherd) => { // send back body on both success and error // this bit replicates iguana core's behaviour - shepherd.request(options, (error, response, body) => { + request(options, (error, response, body) => { if (response && response.statusCode && response.statusCode === 200) { @@ -299,7 +302,7 @@ module.exports = (shepherd) => { } _arg = _arg.trim().split(' '); - shepherd.execFile(_coindCliBin, _arg, (error, stdout, stderr) => { + execFile(_coindCliBin, _arg, (error, stdout, stderr) => { shepherd.log(`stdout: ${stdout}`); shepherd.log(`stderr: ${stderr}`);